Functional Principles - Primitive Obsession

 


In the below example, we see dishonest signatures as part of a primitive obsession.  The method signature suggests that you input a string and it returns a user, when in fact, only strings formatted in a particular way (ie. in email format) will return a user.  It makes the programmer think that the method works with primitive strings when in reality this string represents a domain concept with its own invariants.  

In this example, primitive obsession encourages you to repeat code when more than email is added to the organisation.  If a variable requires validation, maybe it is better off as a class.


To fix this issue we can create an Email class that holds all validation.  It returns the Result class which means we expect there may be failures.



























It's a good idea to have an abstract base class for all such classes






















When inherited by the email class it would look like this:



































































With above pattern this can be simplified to this:


























Email is definitely complex enough to create a type for and so is username, just about.  MoneyAmount with just one simple check probably isn't worth it.








Comments

Popular posts from this blog

Scalability and high availability

Microservices and Service-Oriented Architecture

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