4

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();
    }
}
  • This is very much language-dependent. In C++ for instance, you typically do neither, but use initializer lists. – MSalters Sep 28 '18 at 17:57
7

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.

| improve this answer | |
  • "their values are undefined until you call the constructor". That's not quite true. Static fields are auto initialised to their "zero fill" value. See this code snippet for example – David Arno Sep 26 '18 at 14:05
  • @DavidArno I have edited it. – Simon B Sep 26 '18 at 14:18
  • +1 from me then as your comment about static fields makes your answer a better one than mine I feel. – David Arno Sep 26 '18 at 14:31
  • Thank you very much for the answer, this makes a lot of sense! – Paul Gildehaus Sep 26 '18 at 16:41
2

As you have observed, different people do it different ways. This is because there is no "best practice" for this; it's really just a matter of style.

I'm assuming your code is C#. For that specific language, I'd opt for a simplified form of your first version, as the empty constructor serves no purpose here (you get such a default constructor for free if you do not define one):

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

For me, it makes the code simpler as the fields are defined and assigned together; I don't need to jump up and down the file from the fields to the constructor to see their default values.

But other people will have equally valid personal reasons for preferring your second option.

The best coding practice therefore is consistency: pick the style you like and stick with it. Flipping between the two, seemingly at random, is not a good idea.

Caveat: there are times when you might need to mix the two through necessity. Pragmatism should always win out over principles here, so if you need to mix them do so. Just avoid mixing them if you don't need to.

| improve this answer | |
  • I only assign in the constructor if its value cannot be determined without first requiring the parameters passed into the constructor. I.e. this.transaction = connection.beginTransaction(); where connection is a passed argument. – Neil Sep 26 '18 at 14:26
  • I think is a fantastic answer thank you very much. I was going to give you the green checkmark but then you commented on the first answer saying you agree with his answer more. I just wanted to let you know I feel your answer is more descriptive and very helpful. – Paul Gildehaus Sep 26 '18 at 16:40
1

Where a variable is initialized depends on its scope and intended use.

Static fields

I would set their default value when declaring them in order to keep declaration and initialization together.

class Foo {
    private static int firstNumber = 1;
}

Instance fields

If the default value will always be the same for all instances, then I see nothing wrong with including the initialization with the declaration.

class Foo {
    private FooBar fooBar = new FooBar();
}

If there is a chance that the initial value may vary based on other initialization logic or be passed to the constructor, then I would set the value in the constructor. I ask myself whether I should be concerned with the value of fooBar when constructing Foo.

class Foo {
    private FooBar fooBar;

    public Foo(int number) {
        fooBar = new FooBar();
        fooBar.Size = number;
    }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.