TechHui

Hawaiʻi's Technology and New Media Community

I'm just starting to play with some of the new features in .NET, especially LINQ and the language features that were added to support it. I was wondering what other people think about object intializers. They seem quite handy but I'm concerned that encapsulation may suffer...

Views: 20

Reply to This

Replies to This Discussion

How do they violate encapsulation? I really like object initializers. They exist in other languages like Python and Groovy.

C#:
new Student { Name="Tim" };

Groovey:
new Student(name:"Tim");
They don't, per se, but you must be careful that your default constructor behaves in a manner that object initializers will not compromise. Part of the reason for overloaded constructors is to allow an object to be initialized differently with different input scenarios. A ctor like Foo() may initialize differently than Foo(bar). Under the object initializers, you must ensure that new Foo() { prop=bar } initializes the same as

Foo foo = new Foo();
foo.prop=bar;

In other words, the object has to be initialized to the same state regardless of the constructor.

I'm not necessarily down on the concept; I just believe that it requires a little more diligence on the programmer's behalf.

Reply to Discussion

RSS

Sponsors

web design, web development, localization

© 2014   Created by Daniel Leuck.

Badges  |  Report an Issue  |  Terms of Service