Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to initialise fields outside of an explicit constructor [duplicate]

Possible Duplicate:
Initialize class fields in constructor or at declaration?

We are arguing about coding practices. The examples here are a little too simple, but the real deal has several constructors. In order to initialise the simple values (eg dates to their min value) I have moved the code out of the constructors and into the field definitions.

public class ConstructorExample
{
    string _string = "John";
}

public class ConstructorExample2
{
    string _string;

    public ConstructorExample2()
    {
        _string = "John";
    }
}

How should it be done by the book? I tend to be very case by case and so am maybe a little lax about this kind of thing. However i feel that occams razor tells me to move the initialisation out of multiple constructors. Of course, I could always move this shared initialisation into a private method.

The question is essentially ... is initialising fields where they are defined as opposed to the constructor bad in any way?

The argument I am facing is one of error handling, but i do not feel it is relevant as there are no possible exceptions that won't be picked up at compile time.

like image 697
John Nicholas Avatar asked May 10 '10 14:05

John Nicholas


People also ask

Should I initialize variable within constructor or outside constructor?

I recommend initializing variables in constructors. That's why they exist: to ensure your objects are constructed (initialized) properly.

Is Empty constructor a bad practice?

So we can create an empty object with new Object() . Side note: you should NEVER create an object using the constructor. It's considered bad practice, see Airbnb Style Guide and ESLint .

Do fields need to be initialized before use?

It is only necessary that they be declared and initialized before they are used.

Can we initialize variable in constructor?

A constructor is typically used to initialize instance variables representing the main properties of the created object. If we don't supply a constructor explicitly, the compiler will create a default constructor which has no arguments and just allocates memory for the object.


2 Answers

It's not necessarily bad to initialize values outside of the constructor, and the problem you have here:

 string _string;

    public ConstructorExample2()
    {
        _string = "John";
    }

Is that if you have multiple constructors you have to remember to either
1. Reinitialize _string in every constructor
2. Separate the logic out into a common method and call that method in every constructor
3. Call the constructor with the logic in it, from the other constructors. (Chain the constructors)
Now this isn't necessarily a problem, but you have to remember to do it. By initializing it outside of the constructor, it's done for you. It's one less thing you need to remember to do.

like image 157
kemiller2002 Avatar answered Oct 04 '22 17:10

kemiller2002


Note that all such field declaration-level initialization will be performed once for each constructor-chain, even if the constructor by itself sets the field to something else.

If you chain constructors together, the fields will be initialized in the common, first, constructor that is called.

Look at this example:

using System;

namespace ClassLibrary3
{
    public class Class1
    {
        private string _Name = "Lasse";

        public Class1()
        {
        }

        public Class1(int i)
            : this()
        {
        }

        public Class1(bool b)
        {
            _Name = "Test";
        }
    }
}

This code compiles as this:

using System;

namespace ClassLibrary3
{
    public class Class1
    {
        private string _Name;

        public Class1()
        {
            _Name = "Lasse"
        }

        public Class1(int i)
            : this()
        {
            // not here, as this() takes care of it
        }

        public Class1(bool b)
        {
            _Name = "Lasse"
            _Name = "Test";
        }
    }
}
like image 31
Lasse V. Karlsen Avatar answered Oct 04 '22 16:10

Lasse V. Karlsen