Reputation: 619
I have 3 classes that implement the following interface:
public interface PolicyType {
public boolean isValid();
public void displayTemplate();
}
And in my main I have created and initialized 1 instance of each class:
//the same method exists for MedicalPolicy and MotorPolicy
private static void displaySucMsg(TravelPolicy travelPolicy,List<TravelPolicy> travelPolicyList){
if(travelPolicy.isValid()) {
System.out.println("Policy: " + travelPolicy.getPolicyNo() + " was added successfully");
travelPolicyList.add(travelPolicy);
}
}
public static void main(String[] args){
List<TravelPolicy> travelPolicyList = new ArrayList<TravelPolicy>(2);
List<MotorPolicy> motorPolicyList = new ArrayList<MotorPolicy>(2);
List<MedicalPolicy> medicalPolicyList = new ArrayList<MedicalPolicy>(2);
TravelPolicy travelPolicy1 = new TravelPolicy(policyNo,param2,etc...);
displaySucMsg(travelPolicy1,travelPolicyList);
MotorPolicy motorPolicy = new MotorPolicy(policyNo,param2,etc...);
displaySucMsg(motorPolicy,motorPolicyList);
MedicalPolicy medicalPolicy = new MedicalPolicy(policyNo,param2,etc...);
displaySucMsg(medicalPolicy,medicalPolicyList);
}
As you can see I've created 3 List
s each one for a class
but I want to have 1 List
so that at the end I can use a for loop
on it, my problem is that the displaySucMsg
uses a getter method for the policyNo
field (and then add the instance to the appropriate List) so I can't create a List
of PolicyType
and add all instances to it.
My question is should I create a List
of Object
(which I assume would be a bad practice) and add all 3 List
s to it, or should I add public String getPolicyNo()
to my interface since all my 3 classes have that method (which I assume is also a bad practice since if I ever created a new class that implement PolicyType
but doesn't need a getPolicyNo()
method would be very bad), or should I just leave my code as it is and run 1 for loop
on each List
or is there another solution?
Upvotes: 0
Views: 72
Reputation: 2178
The class design should reflect the real life business scenario. So define what is a "policy" and what are its mandatory properties and behavior of this object. If policyNo and policyType are important properties then don't worry about they being empty ever.
If it ever happens that a property was thought to be mandatory but with changing business scenario it is no longer that case then you can always implement it and return a default value or actually have a default implementation on the interface. You can even bring in 2 interfaces - OldPolicy and NewPolicy to accommodate the change in definition of "policy".
In your example add getPolicyNo()
to interface PolicyType
and build a List which can hold objects of 3 policy types.
Upvotes: 1