We currently have two customer codes "CUSTA" and "CUSTB". CUSTA can perform operations A1, A2, A3, A4, A5, A6. CUSTB can perform operations B1, B2, B3, B4, B5, B6 based on some conditions. Currently they are not expecting any more customer codes but I would like the design to be flexible. These can be stored in database but as I mentioned because it is not likely for a long time to have another customer code, it needs to be represented in code.
The application logic basic algorithm looks like
if ConditionX is true
then if customerCode is "CUSTA"
then applicableOperation = 'A1'
else
if customerCode is "CUSTB"
then applicableOperation = 'B1'
end
else
if ConditionY is true
then
if customerCode is "CUSTA"
then applicableOperation = 'A2'
else
if customerCode is "CUSTB"
then applicableOperation = 'B2'
end
else
............... .................
I can write switch statements etc..to clean up the algorithm but my main concern is how to represent "CUSTA", "CUSTB", "A1","A2","A3","A4"..."A6","B1","B2"..."B6". Does the customer code be enum like
public enum CustomerCode { CUSTA, CUSTB }
public enum OperationsForA{ A1, A2, A3,...A6 }
public enum OperationsForB{ B1, B2, B3...B6}
Shall I create a Map
where key is CustomerCode and add respective operations as values.
What would be the best solution to address this problem. Also it should be flexible to add "CUSTC" , for example, in the future.
Thanks
If A1 corresponds to B1, A2 corresponds to B2, and so on, then you need polymorphism.
This means that you will have a generic CustomerOperations
interface. Each customer code would create a concrete implementation of the CustomerOperations
interface and return the correct operation corresopnding to Condition X
, Condition Y
, etc.
Set up your interfaces:
interface CustomerOperations {
Operation operationForX();
Operation operationForY();
}
interface Operation {
Result someMethod();
}
Set up your enums and implement the interfaces:
enum OperationsForA implements Operation {
A1, A2, A3;
// Implement someMethod
}
enum OperationsForB implements Operation {
B1, B2, B3;
// Implement someMethod
}
enum CustomerCode implements CustomerOperations {
CUSTA {
Operation operationForX() {
return OperationsForA.A1;
}
Operation operationForY() {
return OperationsForA.A2;
}
},
CUSTB {
Operation operationForX() {
return OperationsForB.B1;
}
Operation operationForY() {
return OperationsForB.B2;
}
}
;
}
Example usage: (this is where the polymorphism happens)
public class Main {
public static void main(String... args) {
CustomerOperations operator = CustomerOperations.CUSTA;
if (conditionX) {
// Could be inlined, but I've separated it for type readability:
// Get the appropriate operation from the operator.
Operation thingToDoForX = operator.operationForX();
// Run the operation and get the result
Result result = thingToDoForX.someMethod();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With