I have a static private java method that has been used in many places in the containing class.
It is something like:
private static ColoredItem createItem(Object obj, Color background, Color foreground) {
ColoredItem item = new ColoredItem();
//Some logic goes here to paint the item
//Some other logic to apply the background and foreground colors
return item;
}
My question is, from a good design perspective, is it appropriate to ignore the colors passed as parameters to the method in case the first parameter implements a specific interface?
So the method will be modified to be something like:
private static ColoredItem createItem(Object obj, Color background, Color foreground) {
ColoredItem item = new ColoredItem();
//Some logic goes here to paint the item
//Some other logic to apply the background and foreground colors
if(obj instanceof SOME_INTERFACE) {
item.setBackgroundColor(some other color);
item.setForegroundColor(some other color);
}
return item;
}
No, it is not. A good design option is to use overloading:
private static ColoredItem createItem(Interface1 obj, Color background, Color foreground){
// do something here that require the two parameters
}
private static ColoredItem createItem(Interface2 obj) {
/// do something for the object that do not require the two other parameters
}
This way, you avoid checking the type of your first parameter. The runtime will do this for you. Also, the code will be cleaner, since now the users of this method will know exactly what to pass to it.
I hope this helps, -Caius
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