Best Practices for Initializing Variables in Constructors

constructorsvariables

I try to use the best coding standards/practices, however in all of my googling and classes I have never learned which is proper form for declaring/defining variables like the examples below. I have seen numerous different people (teachers, classmates, coworkers) define variables inside and outside of the constructor seemingly at random. Any information about this would be awesome!

class Foo
{
    private static int firstNumber = 1;
    private int secondNumber = 25;
    private FooBar fooBar = new FooBar();

    public Foo()
    {
    }
}

or

class Foo
{
    private static int firstNumber;
    private int secondNumber;
    private FooBar fooBar;

    public Foo()
    {
        firstNumber = 1;
        secondNumber = 25;
        fooBar = new FooBar();
    }
}

Best Answer

Given that you have declared some of the variables "static", use the first option.

Static variables are not bound to one instance of a class - they are shared across all of them. They even exist before you have created an instance.

The second initialises them in the constructor, which means their values are not set to the desired values until you call the constructor. Every time you call the constructor, it initialises them again.

The first option is simpler and behaves as expected.