Created
April 29, 2020 21:44
-
-
Save joshiraez/fac8f3573618b07c3334dd271a11f850 to your computer and use it in GitHub Desktop.
Code sample for an article about Business Logic and Configuration Logic - https://medium.com/@joshiraez/make-your-business-logic-readable-and-your-configuration-logic-extendable-ea151d478423
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.function.UnaryOperator; | |
public class Main { | |
//Top level layer | |
public static void main(String[] args) { | |
sayHi(SHOUTING, "joshi"); | |
sayGoodbye(AFABLE, "readers"); | |
} | |
//Intermediate layer. This interfaces our main with the core logic. | |
private static void sayHi(final Mood howTo, final String otherPerson) { | |
sayItOutLoud( | |
moody(howTo) | |
.apply( | |
greet(otherPerson) | |
)); | |
} | |
private static void sayGoodbye(final Mood howTo, final String otherPerson) { | |
sayItOutLoud( | |
moody(howTo) | |
.apply( | |
partFrom(otherPerson) | |
)); | |
} | |
//One layer below. We have three distinct cores: | |
//What to talk | |
private static String partFrom(final String otherPerson) { | |
return "Bye bye "+otherPerson+"!"; | |
} | |
private static String greet(final String otherPerson) { | |
return "Hi "+otherPerson+"!"; | |
} | |
//How to output it. | |
private static void sayItOutLoud(final String greetings) { | |
System.out.println(greetings); | |
} | |
//And how to tell it. Notice this is the business logic of even another layer | |
private static UnaryOperator<String> moody(final Mood howTo){ | |
return SHOUTING.equals(howTo) | |
? Main::shouting | |
: Main::calmly; | |
} | |
//Yep, THIS ONE which tells us HOW to do it. | |
private static String calmly(final String greetings) { | |
return greetings.toLowerCase(); | |
} | |
private static String shouting(final String greetings) { | |
return greetings.toUpperCase(); | |
} | |
//And finally THERE IS ANOTHER LAYER AT THE BOTTOM, FOR TYPE CONFIGURATION! (Which is the core of the language) | |
//Please dont put constants in the end of the file. Just showing layers. | |
private static final Mood SHOUTING = Mood.SHOUTING; | |
private static final Mood AFABLE = Mood.AFABLE; | |
private enum Mood { | |
AFABLE, | |
SHOUTING | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment