user697911
user697911

Reputation: 10531

Explicitly initialize String and Enum variables in Java?

Is it better to remove the initialization statements in the constructor in below code?

class Dog {

   private String name;
   private Type type;

   public Dog() {
       this.name = null;
       this.type = null;
   }

   public static Enum Type {
       large, medium, small;
   }
}

Upvotes: 0

Views: 510

Answers (2)

Alex
Alex

Reputation: 63

It depends, better in what sense?

If you value short clean code above all else, then this is good. Here's an example:

class Dog {
private String name;
private Type type;

public static enum Type {
    large, medium, small;
}

This works because uninitialized Objects start off as null. Also empty constructors need not be specified.

If you value clarity but still want to keep the code as short as possible, then

class Dog {
    private String name = null;
    private Type type = null;

    public Dog() {}

    public static enum Type {
        large, medium, small;
    }
}

is better because other (less experienced) devs can see clearly what the values are, and the constructor is clearly defined.

Initializing constant values in the constructor also has its own benefits:

  • Clearly separate declarations from values/logic
  • Flexibility to add logic in future when needed (extensibility)

Just evaluate the pros and cons for each situation, see what you like. The only exception is when you work with an existing codebase; in this case keep to the conventions / style guide.

Upvotes: 1

Thijs Steel
Thijs Steel

Reputation: 1272

This kind of question tends to generate a lot of opinions, and this answer is no different. Here is how i was tought at university:

Declare a default value for all (non-final) variables, even when those are equal to the standard value (null, 0, ...). The reasoning is that it's now easier to see that unless explicitly defined, the variables will default to null.

So that would be:

class Dog {

   private String name = null;
   private Type type = null;

   public Dog(){}

   public static Enum Type {
       large, medium, small;
   }
}

Remember that this is just an opinion about clean code. Both behave in exactly the same way.

Upvotes: 0

Related Questions