Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why javadoc parameter-less constructors?

In item 56 of Effective Java (Third Edition), Joshua Bloch states:

Public classes should not use default constructors because there is no way to provide doc comments for them.

The default contructor doesn't do anything unexpected, though, it just makes a new instance. What sort of information ought to be documented in a doc comment on the parameter-less constructor that shouldn't just live in the class comment?

I can understand doing this if a class has interesting behaviour in initializer blocks (since otherwise there is no where to doc comment these), or even non-standard value assignments for fields (perhaps calling methods to get initial values). But it seems like for most classes this doesn't add much. Is there something I'm missing?

like image 260
Tom Tresansky Avatar asked Aug 09 '26 00:08

Tom Tresansky


1 Answers

In the very most of cases you are right.
And I think that in these cases, using the default constructor makes sense as you has nothing to document.

Now in some other cases, it makes be useful to document what the method does and more specifically its default state.

Because even if a default constructor has an empty body, it may use a default value in its fields that may be interesting to document.

Here are two examples of JDK classes where javadoc may bring useful information for constructors with an empty body.

Stack

/**
 * Creates an empty Stack.
 */
public Stack() {
}

Of course, clients may guess that the Stack is empty as this constructor is invoked but having its clearly specified is better.

AtomicInteger

Take the AtomicInteger empty constructor:

/**
 * Creates a new AtomicInteger with initial value {@code 0}.
 */
public AtomicInteger() {
}

The AtomicInteger constructor is overloaded. So we are not in a potential default constructor case.
But whatever, it is an empty-arg constructor with an empty body, similar to what a default constructor produces.

Without these constructors javadoc, clients of these classes should look into the implementation to guess the information and an API that constraints clients to look the implementation to understand its specification is not a good designed API.

like image 111
davidxxx Avatar answered Aug 10 '26 13:08

davidxxx