tags:

views:

3045

answers:

10

I've been programming in C# and Java recently and I am curious what people would consider the best practice concerning when you should initialize your classes fields?

Should you do it at declaration?:

public class Die
{

    private int topFace = 1;
    private Random myRand = new Random();

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

or in a constructor..

public class Die
{

    private int topFace;
    private Random myRand;

    public Die()
    {
        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.

+23  A: 

My rules:
1. Don't initialize with the default values in declaration (null, false, 0, 0.0...).
2. Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
3. If the value of the field changes because of a constructor parameter put the initialization in the constructors.
4. Be consistent in your practice. (the most important rule)

kokos
A: 

Assuming the type in your example, definitely prefer to initialize fields in the constructor. The exceptional cases are:

  • Fields in static classes/methods
  • Fields typed as static/final/et al

I always think of the field listing at the top of a class as the table of contents (what is contained herein, not how it is used), and the constructor as the introduction. Methods of course are chapters.

Noel
+1  A: 

Code Complete - Chapter 10.6 - Binding Time

It can be to your advantage to use the latest binding time possible. In general, the later you make the binding time, the more flexibility you build into your code. The next example shows binding at the earliest possible time, when the code is written:

Java Example of a Variable That's Bound at Code-Writing Time titleBar.color = 0xFF; // 0xFF is hex value for color blue

The value 0xFF is bound to the variable titleBar.color at the time the code is written because 0xFF is a literal value hard-coded into the program. Hard-coding like this is nearly always a bad idea because if this 0xFF changes, it can get out of synch with 0xFFs used elsewhere in the code that must be the same value as this one.

Artur Carvalho
A: 

If you don't mind, I would edit your question title--it makes it seem like you're talking about static variables at the class level, whereas the meat of your question is actually dealing with instance variables.

If 1 is your default value for the variable in this case, I would recommend setting the value at declaration. To me, that much more clearly marks it as a default value instead of some magic value in the constructor.

Out of curiosity, though, why are you using 1 as the default top face for the die? Might be cooler to randomly pick a number between 1 and 6. That would be a good reason to set the top face in the constructor.

Brian Warshaw
A: 

What if I told you, it depends?

I in general initialize everything and do it in a consistent way. Yes it's overly explicit but its also a little easier to maintain.

If we are worried about performance, well then I initialize only what has to be done and place it in the areas it gives the most bang for the buck.

In a real time system, I question if I even need the variable or constant at all.

And in C++ I often do next to no initialization in either place and move it into an Init() function. Why? Well in c++ if your initializing something that can throw an exception during object construction you open yourself to memory leaks.

Dan Blair
A: 

I normally try the constructor to do nothing but getting the dependencies and initializing the related instance members with them. This will make you life easier if you want to unit test your classes.

If the value you are going to assign to an instance variable does not get influenced by any of the parameters you are going to pass to you constructor then assign it at declaration time.

Iker Jimenez
+12  A: 

In C# it doesn't matter. The two code samples you give are utterly equivalent. In the first example the C# compiler (or is it the CLR?) will construct an empty constructor and initialise the variables as if they were in the constructor. If there is already a constructor then any initialisation "above" will be moved into the top of it.

In terms of best practice the former is less error prone than the latter as someone could easily add another constructor and forget to chain it.

Quibblesome
+1 the constructor chaining argument is strong
annakata
A: 

There is a slight performance benefit to setting the value in the declaration. If you set it in the constructor it is actually being set twice (first to the default value, then reset in the ctor).

John Meagher
In C#, fields are always set the default value first. The presence of an initializer makes no difference.
Jeffrey L Whitledge
A: 

The semantics of C# differs slightly from Java here. In C# assignment in declaration is performed before calling the superclass constructor. In Java it is done immediately after which allows 'this' to be used (particularly useful for anonymous inner classes), and means that the semantics of the two forms really do match.

If you can, make the fields final.

Tom Hawtin - tackline
A: 

Don't initialize with the default values in declaration

why?

Learn2comment ;)
Simucal