3/16/2023 0 Comments Scala option![]() Whenever possible, document the intent of the code in the code itself, mainly in the API. But documentation is inferior to code, it isn’t compiled, tested, can be out of date, nothing can guarantee that the user will read it, etc. Therefore, the clients can only guess, look at the implementation (not always possible and/or desirable) or rely on documentation stating what the functions are supposed to do in those cases. We’re not forcing our clients to handle the possibility for null, so anything can happen when it appears given that we hadn’t warned them.We can’t express the possibility for the absence of value in the interface, just in the implementation.In the old days, we’ve used null, but as we discussed, null has the basically the following flaws: So the client can be aware of this fact and forced to handle it properly according to its goal. Simply put, we need to make the interface states that it may not return a meaningful value. ![]() I mentioned, “valid scenario” to emphasize that it’s not an exceptional situation, hence throwing an Exception is completely ruled out. Our interface doesn’t express the possibility for the absence of a value, which is a perfectly valid scenario in our application. To tackle the problem, first we need to understand its root cause: How can we fix the NPE without adding unnecessary complexity to the code, keeping it simple and focused solely on the business requirements? The right Option for the right semantic The NPE is fixed, but now a simple and elegant one-line function has 7 lines and a higher cyclomatic complexity, mostly because of the checks against null values, a lot of noise! Suppose that both can return null, so what should we do? You can say: we should handle the possibilities of null! Our interface is violating the Principle of Least Astonishment because it doesn’t make this kind of situation explicit, so in theory, “anything could happen”. And accessing null will lead us to the tragic NullPointerException(NPE).
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |