HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaCritical

Initialize class fields in constructor or at declaration?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
constructordeclarationclassinitializefields

Problem

I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.

Should I do it at declaration?:

public class Dice
{
    private int topFace = 1;
    private Random myRand = new Random();

    public void Roll()
    {
       // ......
    }
}


or in a constructor?:

public class Dice
{
    private int topFace;
    private Random myRand;

    public Dice()
    {
        topFace = 1;
        myRand = new Random();
    }

    public void Roll()
    {
        // .....
    }
}


I'm really curious what some of you veterans think is the best practice. I want to be consistent and stick to one approach.

Solution

My rules:

  • Don't initialize with the default values in declaration (null, false, 0, 0.0…).



  • Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.



  • If the value of the field changes because of a constructor parameter put the initialization in the constructors.



  • Be consistent in your practice (the most important rule).

Context

Stack Overflow Q#24551, score: 350

Revisions (0)

No revisions yet.