Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Aren't records and init only setters in C# also a way to favor immutable types and fix setters in properties? (Not trying to criticize, I really want to know).


Kind of. It gets you close.

With the Builder pattern, you can easily define complex relationships for your class inner state. Like maybe if A & B are specified, then C shouldn't be specified. But if C is specified, then D should have a default value. Etc.

These types of initialization requirements are not easily duplicated with C# init-only construction. Instead, in C# you have to rely on the callers to know exactly how to correctly instantiate your class, including all the complex logic like in the example above.

So yes, C# init-only setters are kind of the best option you have. You can still create a C# FooBuilder for a Foo class. But generally C# programmers want to go out of their way to directly instantiate a Foo, and the number of bugs you get from this is crazy. It's a culture thing, honestly, not as much a language problem.

My two cents.


Do you have an example of how builders work in Java?


This is probably a pretty good link to start from.

https://blogs.oracle.com/javamagazine/post/exploring-joshua-...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: