Is there a difference between (in either java or c#):
public class Foo {
Bar1 bar1;
Bar2 bar2;
public Foo(Bar1 bar1, Bar2 bar2) {
this.bar1 = bar1;
this.bar2 = bar2;
}
}
And
public class Foo {
Bar1 bar1 = null;
Bar2 bar2 = null;
public Foo(Bar1 bar1, Bar2 bar2) {
this.bar1 = bar1;
this.bar2 = bar2;
}
}
For objects, it shouldn’t matter whether you assign null or not – it’s implicit, right?
My boss is insistent on assigning each value null. For strings, I understand assigning String str = "", since there’s a big difference there, but I’m not quite sure why the huge deal over objects.
Also, is it bad practice to do the following:
public class Foo {
Bar1 bar1 = new Bar1();
Bar2 bar2 = new Bar2();
public Foo(Bar1 bar1, Bar2 bar2) {
this.bar1 = bar1;
this.bar2 = bar2;
}
}
There is no need to explicitly initialize instance variables to default values. In Java and C#, instance variables are assigned default values when the instance is created. A reference type already is null prior to the main body of the constructor running. An
intalready is 0, etc. In the first code snippet, bar1 and bar2 are already null. There’s no need to explicitly state it, as in the second snippet.In the second example (third snippet), there is absolutely no need to instantiate an instance variable to a
new Bar1();if all you are doing is overwriting with another reference in the constructor.You might want to initialize a member variable to a value when the default should be something other than the type’s default when a constructor is not already immediately overwriting it with a supplied parameter. But setting it to its default value is simply redundant. However, if it helps your boss or other members of the team understand what those default values are, then so be it.