Functional Principles - Exceptions

 

Exceptions should represent a defect in the codebase.  

If we throw exceptions for validations then it is not part of the method signature and is hidden.

Example of code that comprises readability by throwing exceptions for validations:




Should be written like this without exceptions, return a non empty string:



Exceptions are for use cases you didn't take into account.  It is not exceptional for users to enter invalid data.


Example: In this example, the validation of UpdateName is essentially part of the public contract, its preconditions.  This is acceptable, as for this to be thrown, some mistake must have been made in the domain logic for a null value in name to reach that part of the code.



Hides potential issues.  The best way to handle unexpected situations is to let the code fail.



Example: this may be an exceptional situation for the repository, but it doesn't have to be for your codebase.  Catch a specific exception and return false to fail gracefully in known exception that might happen otherwise re throw the exception.

When application fails to start.




Comments

Popular posts from this blog

Microservices and Service-Oriented Architecture

Version control and Continuous Integration/Continuous Deployment (CI/CD)

Delegates