Should I Initialize Variable Within Constructor or Outside Constructor

Should I initialize variable within constructor or outside constructor

I find the second style (declaration + initialization in one go) superior. Reasons:

  • It makes it clear at a glance how the variable is initialized. Typically, when reading a program and coming across a variable, you'll first go to its declaration (often automatic in IDEs). With style 2, you see the default value right away. With style 1, you need to look at the constructor as well.
  • If you have more than one constructor, you don't have to repeat the initializations (and you cannot forget them).

Of course, if the initialization value is different in different constructors (or even calculated in the constructor), you must do it in the constructor.

Initilizing outside constructor vs inside

There is no difference between the two methods. If you were working in an activity or fragment class then it would be best to initialize a variable inside onCreate. The only advantage of initializing it outside constructor in such a scenario would be if other functions need to load before onCreate is called.

But in a situation of a class, then there is no difference is by the preference of the coder.

Java: Initialiasing objects inside or outside the constructor?

There's no difference: the compiler will move any outside initialization within the constructor.

See Java for a Nutshell, section 3.2.4: Field Defaults and Initializers.

Initialize class fields in constructor or at declaration?

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).

Why should I use constructor if I can initialize instance variable another way

You should use me because I will help you keep your initializations in one place. Because it will help you other colleagues to know where to expect initializations and not miss one if they're scattered aroudn the code.

Instance variables in methods outside the constructor (Python) -- why and how?

Why is it best practice to initialize the instance variable within the
constructor?

Clarity.

Because it makes it easy to see at a glance all of the attributes of the class. If you initialize the variables in multiple methods, it becomes difficult to understand the complete data structure without reading every line of code.

Initializing within the __init__ also makes documentation easier. With your example, you can't write "an instance of Cat has a roar attribute". Instead, you have to add a paragraph explaining that an instance of Cat might have a "roar" attribute, but only after calling the "meow_louder" method.

Clarity is king. One of the smartest programmers I ever met once told me "show me your data structures, and I can tell you how your code works without seeing any of your code". While that's a tiny bit hyperbolic, there's definitely a ring of truth to it. One of the biggest hurdles to learning a code base is understanding the data that it manipulates.

What general/specific mess could arise if instance variables are
regularly initialized in methods other than the constructor?

The most obvious one is that an object may not have an attribute available during all parts of the program, leading to having to add a lot of extra code to handle the case where the attribute is undefined.

In what scenarios would it be better to initialize instance variables
in the other methods, rather than in the constructor?

I don't think there are any.

Note: you don't necessarily have to initialize an attribute with it's final value. In your case it's acceptable to initialize roar to None. The mere fact that it has been initialized to something shows that it's a piece of data that the class maintains. It's fine if the value changes later.

Java instance variable initialization inside and outside constructor confusion

Precedence

In your case the int j happens first and defaults to 0, then gets reassigned to 5 when the constructor is called on to create a new instance.

j only gets re-assigned when the constructor runs. Instance members get initialized first when you assign them something outside the constructor.

Order of Execution

Each line of code gets executed in the order it appears. The declarations happen before the constructor always, in the order they are listed in the code.

Deterministic and Predictable

You should only initialize instance members in a single place, inside a single constructor.

Relying on defaults leads to hard to track down bugs, and makes testing a nightmare, but a instance member that is unassigned will stand out like a sore thumb to the IDE, the compiler and at runtime. Unfortunately for primitives like int they default to 0 which might not be what you want/need.

A better design is:

 private final int j;

public Foo(final int j) { this.j = j; }

This keeps the j from getting assigned anything on initialization and you never have to worry about it changing.

Initializing on declaration vs initializing in constructors

If the member can only be set via an accessor (a "setter" method), I prefer the first style. It provides a hint that the initialized value is the default upon construction.

If the member can be specified during construction, I generally pass the default value to an appropriate constructor from constructor with fewer parameters. For example,

final class Dude {

private final String name;

Dude() {
this("El Duderino");
}

Dude(String name) {
this.name = name;
}

}

c# declaring variables inside or outside a constructor

There's a fair bit of room for personal opinion here, but in general terms:

  1. Declaring and initializing the field on the same line helps you to verify the field is initialized without needing to look in multiple places. If you see a field declared without an initializer, you have to look in a different part of code to see whether the item is being initialized at all.
  2. There are circumstances (like when the initial value is based on a constructor argument) when you cannot initialize the field inline. Since you will sometimes need to initialize fields in the constructor, some people will argue that it's more consistent to always initialize them there.

You may also want to ask: Should I be requiring/allowing an initial value to be provided in the constructor?

    class Book
{
readonly List<double> grades;
public Book() : this(Array.Empty<double>())
{
}

public Book(IEnumerable<double> grades)
{
this.grades = grades.ToList();
}

public void AddGrade(double grade)
{
grades.Add(grade);
}
}

And: should my class actually just be a dumb data container without a constructor or logic? (Is book.AddGrade(...) really more sensible than book.Grades.Add(...)?)

    class Book
{
public List<double> Grades {get;} = new List<double>();
}


Related Topics



Leave a reply



Submit