Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why StreamReader Constructor (String) does not conform to constructor guidelines?

Tags:

c#

constructor

Constructor design guidelines (https://msdn.microsoft.com/en-us/library/ms229060(v=vs.110).aspx) specifies:

✓ DO minimal work in the constructor. Constructors should not do much work other than capture the constructor parameters. The cost of any other processing should be delayed until required.

Constructor "public StreamReader(string path)" open the file. Is this a design error?

like image 247
Marc Habib Avatar asked Dec 14 '22 06:12

Marc Habib


1 Answers

Is this a design error?

No, it's a design choice. The guidelines are called guidelines because they are guidelines, not rules. Design is the process of making choices amongst many alternatives, each of which has pros and cons.

Consider what happens if the file open is delayed until the reader is used.

  • You can pass a bad argument to the constructor, and the exception happens elsewhere, making it harder to debug the problem.

  • The file might be one that exists and is accessible when the constructor is called. Consider what happens if the constructor does not take a lock on the file, and the file is then made inaccessible by an operation after the constructor but before the first read.

Developers reasonably expect that constructing a reader has the semantics of opening the file; it would be surprising to delay that. This consideration is probably more important than following the guideline to not have complex logic in a constructor.

Now, you could make the argument that a better design would have been to have a static factory method rather than a constructor. Then we both fulfill the user's expectation, and avoid creating a public constructor that does work. Sure, in hindsight, that probably would have been a marginally better design. But really, this is a hairsplitting difference. Just hiding a constructor behind a method to satisfy the letter of a guideline doesn't add much value to the world.

Rather, think about the purpose of the guideline. The purpose of the guideline is to remind you that a constructor's job is to make ready the object to do work, and not to do work. I think we can reasonably make the argument that opening the file is getting ready to do work, and not doing work.

like image 134
Eric Lippert Avatar answered May 31 '23 20:05

Eric Lippert