patternjavaMinor
Returning a list of objects
Viewed 0 times
listreturningobjects
Problem
Please review the following code. Methods
getFirsts and getSeconds, both of which are private, return a list of objects which implement CommonInterface. Is this a good or bad design?@Override
public final List getObjects(final CommonEnum type) {
if (type == null) {
return new ArrayList();
}
switch (type) {
case FIRST:
return getFirsts();
case SECOND:
return getSeconds();
default:
return null;
}
}Solution
It's hard to say anything since it seems rather a pseudo-code. Anyway, two notes which you might find useful:
-
I guess you could replace the switch-case structure with polymorphism. Two useful reading:
-
Are you sure that returning
-
I guess you could replace the switch-case structure with polymorphism. Two useful reading:
- Refactoring: Improving the Design of Existing Code by Martin Fowler: Replacing the Conditional Logic on Price Code with Polymorphism
- Replace Conditional with Polymorphism
-
Are you sure that returning
null in the default is fine? I'd consider returning an empty list (as it returns when type == null) or throwing an exception (IllegalStateException, for example) if it's a programming error. (See: The Pragmatic Programmer: From Journeyman to Master by Andrew Hunt and David Thomas: Dead Programs Tell No Lies)Context
StackExchange Code Review Q#17734, answer score: 7
Revisions (0)
No revisions yet.