Let’s say that I have two interfaces and a behavior class:
public interface Creable {
public boolean belongsToSystem();
public List<Creable> getCreatedItems();
}
public interface HasDependencies {
public void createDependencies();
public void generateDependents();
}
public class CreableBehavior {
private Creable creableObject;
public CreableBehavior(Creable creableObject) {
this.creableObject = creableObject;
}
public boolean hasBeenCreated() {
return !creableObject.belongsToSystem() && !creableObject.getCreatedItems().contains(createdObject);
}
And this piece of code:
Creable includedTab = new AdempiereTab(getIncluded_Tab_ID(),
creableElements);
if (!new CreableBehavior(includedTab).hasBeenCreated) {
includedTab.createDependencies();
includedTab.getCreatedItems().add(includedTab);
includedTab.generateDependents();
}
AdempiereTab implements both Creable and HasDependencies. The problem is that I need to use both interfaces Creable and HasDependencies.
Should I cast it like this:
if (!new CreableBehavior(includedTab).hasBeenCreated) {
((AdempiereTab)includedTab).createDependencies();
includedTab.getCreatedItems().add(includedTab);
((AdempiereTab)includedTab).generateDependents();
}
Or should should I create a new interface CreableWithDependencies that extends both interfaces and use that one instead?
Thanks.
EDIT: Answered, I should extend the interface since I don’t want to depend on the implementing type. Combining them would allow me to use many types with the same code.
There are two design forces at work: Keeping your interfaces as small as possible and minimizing the number of interfaces. In general, large interfaces are more problematic to refactor later.
If your interfaces are already used throughout the system, you could split your client code into separate methods or classes, create an interface
CreableHasDependenciesthat extends both interfaces, or just use the class type directly.If this is the first time you are using the interfaces then combine them because interfaces belong to the client code.