DEV Community

Discussion on: Turn Your Spaghetti Code into Functions, Part 2

Collapse
 
monknomo profile image
Gunnar Gissel

I'm going to lead with saying that this is an intermediate step - I'm going somewhere with the predicates that makes testing business rules really simple. The specific pain I'm trying to deal with is business rule tests that take a lot of setup and business object mutation to trigger a particular branch of business logic.

That said, your approach is good, and meshes well with OO domain driven design. I've used it myself, when starting from scratch. My big complaint is that it is hard to retrofit on something that was built without really following OO or DDD principles.

In this example, I'm assuming a fairly large body of pre-existing code. I'm loosely basing it off one of the code bases I work with. In that particular case, we have many POJOs that have getters and setters and little to nothing else. Things are not well encapsulated and data has leaked everywhere. The leakiness has made changing types or values of codes impractical. In my particular case the codes are also widely shared between several government and industry bodies and can't change without causing a riot. I recognize that's not ideal design, but the bones of it were started when I was in elementary school, so it is what it is...

We also have very large business rule utility classes that operate on these objects. Sometimes the business rules even mutate the objects they are validating! O_o

I rather like a functional approach for cleaning up that situation because the cat is already out of the bag as far as exposing types and values. We have sooo much code that hard codes something like "200" where it checks for values. If leaky abstractions were toxic waste, we'd be on a superfund site.

As a separate effort, rooting out these hard coded values is good. I like to replace them with enums, but sometimes other approaches are useful. I've been moderately happy with public static final String variables, or with new classes that encapsulate some concept that wasn't discovered when the initial class was written.

What I'm exploring here is how Java 8's Functional interface might help with refactoring code that was never very OO to begin with. Frankly, a lot of the traditional 'enterprisey' OO Java code is pretty hard to follow for me, so I don't feel like I'm losing much. I'm not completely sure where this investigation will end up, or if it will be 'better', but here's the general outline I see:

  • Basic POJOs
  • That implement a lot of small interfaces
  • Handled by functions
  • That are composed into rules

I don't really talk about the POJOs or the small interfaces thing here - that has to do with this dislike of inheritance I've developed over the years. Maybe another post on another day. I also haven't really gotten into composition of functions as rules - that's the next post.