You would probably not say this when you look at the state of my desk,
but I enjoy working in a clean environment. For me, this translates into a desire to have a clean codebase.
In a previous post I have talked about the redesign I am doing on my pet project “TraMBU”.
Other that entire reworks of projects, I really enjoy the feeling of figuring out a clean way of implementing something.
As a developer, I am often amazed by how elegant and well-designed some libraries I commonly work with are. A prime example of this is the Spring Framework. The Lady Java parody song claims “I want to program like they do at Oracle”. This desire holds true for me in some way. I’d like to arrive at the point where I am able to write code that is just as elegant as most of the code that the guys over at spring.io write.
In order to one day get to that point of mastery, I tend to think about design and code style a lot. Recently at work, we were tasked with writing a validator that checks whether the internal state of a domain object is sane. In the past, I have usually done this by writing a big validate method that in turn calls a bunch of private methods, each validating a certain aspect of the state of the object.
| |
The validators I have written before all look something like the code snippet above. In general, I like validators to return a List of error messages explaining what is wrong with the object under test. Since sometimes you just want to know whether or not it is valid, there is also a isValid() method that just checks if the error message List is empty. You could save the error messages as a class variable in the Validator class, to avoid recalculating the error messages multiple time. However, my experience teaches me that when other people use your code, they tend to not create new objects for every new validation run. This could result in some weird state-issues, if not handled correctly internally in the Validator class. Obviously, this adds more clutter to the code.
Making use of some of the nice functional options we have gotten in Java 8, I was able to rewrite these validators to be a lot more concise and readable. You can find the result below:
| |
This class extends the abstract superclass Validator.
| |
The validators can make use of the internal ValidationResult class, that is used to be able to chain different method lambda’s together. This way the code in the concrete validator is concise, readable, and just the right amount of expressive. I have also decided that I want to express when an object is valid, in stead of when it is invalid. You can see this in the chaining validationsteps in the concrete class. When you read it top to bottom, you get a pretty good idea of what a String must adhere to, in order to pass our validation process.
I am actually pretty proud of my solution, so I wanted to share it with you guys. I hope you enjoyed it, or at least picked up a few ideas that you could use.