2 ms·
This would be awesome. I tend to do a lot of work in the constructor, this would definitely help clean up different kinds of constructors.
by RedShift1 4y ago
This would be awesome. I tend to do a lot of work in the constructor, this would definitely help clean up different kinds of constructors.
- lbriner 4y agoBut that in itself is an anti-pattern isn't it? A Constructor should be the minimal amount of work to create a valid set of object data. Other work should not be hidden in the Constructor otherwise it fails the principle of surprising functionality. As an example of where I have seen this used, your File object could open the file and truncate it in the constructor but this is non-obvious, it would be better to have another method like Init() or perhaps a factory method where calling e.g. File.OpenForWriting() is obvious. I know not everyone has the same requirements but I can't remember a single time where this restriction was a problem for me in C#, the feature sounds like it will encourage worse behaviour.
- RedShift1 4y agoThe work done in the constructor is to ensure you have a working object, so that calls to any of its methods can never end with a null pointer exception or any other exception that can reasonably be prevented/thrown in the constructor. Opening a file and truncating it sounds totally unexpected and I never do such things like touching the filesystem or running queries in a constructor.