Powerful Concept: Let others do the work
So this will hopefully convey the message on how to model your code in order to have things done in a nicer way.
Let's say you are building an object, you have the materials ready to build it and at some step you have to ask another party for some information. Based on that information you will either add a piece or not to your build.
This means you have to also know the domain knowledge of what that third party knows and also how to attach it to your build. For every one of these kind of steps.
Would it not be nicer to just hand off the build sign an agreement that party is responsible the time it is in their care and have them give it back with or without modifications depending on the same information you had before.
Of course it would be nice to understand what is going on at the party in order to maintain it yourself, but let us just say that it is free forever to have the party maintain your build.
Now in code
Now in code we can do the same, even in Java where everything is passed by value. Just make sure to wrap it in something, a POJO for example or basically anything that is a class instance.
First the normal way of doing things:
var l = new ArrayList<String>();
if (l.isEmpty()) {
l.add("s");
}
if (l.contains("s")) {
l.removeAll("s");
l.add("x");
}
Is this a contrived example of course it is.
So we ask first if it is empty then add something. Then otherwise we remove and add elements if it does contain something. What if we did something like the following:
var l = new ArrayList<String>();
Consumer<List<String>> ifEmptyAddS = (l) -> { var b = l.isEmpty() && l.add("s"); };
Consumer<List<String>> removeAllSAddX = (l) -> { l.removeAll(l.stream().filter(s -> s.equalsIgnoreCase("s")).collect(Collectors.toList())); l.add("x");};
ifEmptyAddS.andThen(removeAllSAddX).accept(l);
Now we just hand over the whole list over to the party and have them operate on it. The flow is very easily managed and if the naming is chosen a bit nicely you can read it out and just see what is going on. Like for example, why is removeAllSAddX
doing it in such a complicated way? You can change that if needed, but it works and it might be better for future proofing the process according to them.
It also makes it so you are responsible for making sure the right persons in the right order get your build but they are all responsible for what they do to it. That is a nice separation of concerns.