Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing on declaration vs initializing in constructors [duplicate]

Tags:

java

Possible Duplicate:
Should I initialize variable within constructor or outside constructor

I was wondering, which is a better practice and why. Should I initialize class fields upon declaration, or should I do it in the constructor? Given that it's a simple one-line initialization.

class Dude
{
    String name = "El duderino";

    Dude() {
        // irrelevant code
    }
}

vs.

class Dude
{
    String name;

    Dude() {
        name = "El duderino";

        // irrelevant code
    }
}

Edit: I am aware of the situations where one of the styles would be preferred over the other like in the case of executing initializer code that might throw an exception. What I'm talking about here are cases when both styles are absolutely equivalent. Both ways would accomplish the same task. Which should I use then?

like image 681
amrhassan Avatar asked Aug 09 '11 22:08

amrhassan


1 Answers

If the member can only be set via an accessor (a "setter" method), I prefer the first style. It provides a hint that the initialized value is the default upon construction.

If the member can be specified during construction, I generally pass the default value to an appropriate constructor from constructor with fewer parameters. For example,

final class Dude {

  private final String name;

  Dude() {
    this("El Duderino");
  }

  Dude(String name) {
    this.name = name;
  }

}
like image 158
erickson Avatar answered Oct 01 '22 19:10

erickson