

With a public library, you aren't guaranteed to be able to educate users of the fact that your class will throw (other than in documentation, them finding out "the hard way", etc.) This also depends on whether your code is a publically accessible library or custom/internal business logic for a company. That can lead to developers potentially using your class wrong. The caller (and developer using your class) has to have implicit knowledge up-front that your class will throw when used incorrectly. Mainly: You have to throw an exception to notify the caller that they did something wrong. That being said, there are trade-offs to using constructor validation: I've written about using constructor validation here and I agree that there are some contexts when using this technique is the best choice.

The fact is that any solution you choose is going to have trade-offs. I disagree with the notion that "just adding a null check in the constructor" is always the best solution. Imagine you work for a company that writes software for dealing with legal cases.Īs you are working on a feature, you discover some code: Again, this allows us to make sure the system still behaves the same and avoids introducing a large amount of risk when making these improvements. This article (taken from my book) teaches you about solutions that can be applied to other languages - which may not have this option available.Įither way, it's always safer to apply smaller more targeted improvements to our code. Without testing the code well, and carefully avoiding assumptions, we could still potentially cause run-time errors by these changes. Most of us are dealing with existing codebases that would take tons of work and time to fix these compilation errors. This allows you to add a special flag to your compilation options and will prevent, by default, any variables to allow null as a value. Especially when this kind of code is inside the important and critical parts of your application!Ī Side-Note About Non-Nullable Types In TypeScriptĪs a relevant side note, someone might raise the fact that TypeScript supports non-nullable types. I think we can agree that having code like this scattered in your app is not ideal. Therefore, it's very prone to bugs when changed. This code is hard to read and understand. Let's look at why this code is unhealthy and considered a "code smell" before we look at some techniques to fix it. Is that even real code someone would write?

Enter fullscreen mode Exit fullscreen mode
