0

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;
   }
}
3
  • 3
    They are useless at least, both default to null anyway. Commented May 12, 2017 at 22:32
  • Maybe just a little clearer? Commented May 12, 2017 at 22:36
  • I don't think so, but apparently for some. On the other hand I once spent several hours tracking down a bug caused by initialization to null (although in a very special case). Commented May 12, 2017 at 22:46

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

you should accept @Alex 's answer. I explains all cases with pros and cons in a clear way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.