When I first started working with object-oriented programming languages, I was offered the following rule:
When declaring a field in a class, do not initialize it yet. Do it in the constructor.
Example in C #:
public class Test { private List<String> l; public Test() { l = new List<String>(); } }
But when someone recently asked me why to do this, I could not think of a reason. I am not very familiar with the internal workings of C # (or other programming languages, since, in my opinion, this can be done in all OO languages).
So why is this done? Is it safety? Properties?
,
, , . , , , .
# , , . :
class Test { Object o = new Object(); }
:
class Test { Object o; public Test() { this.o = new Object(); } }
, , #, , , . , -: .
, , , . , . (1) TDD/Unit . , , , . (2) # 3.0 . , , . , . , #.
Ex. ( 2)
var foo = new Foo { Bar = "baz" }; public class Foo { public string Bar { get; set; } public Foo() { } }
, . ,
. , . C-, 75% . , , , . Michael comment , , , , . , , .
factory , - . , , , , , ... , - , , ( , ).
, , .