Is having to return multiple objects a sign of bad design?
Sometimes I encounter this situation in Java while trying to use immutable objects. In Java, a method can't return multiple objects, like return a, b, c
. Returning an array of objects of diff开发者_高级运维erent types or a wrapper object makes the code look ugly. Therefore, I have to pass mutable objects to the method and let it change the states of these objects. So talking generally, in programming, is having to return multiple objects a sign of bad design?
Not always. It's not uncommon to return some kind of "OperationResult" object that contains all of the information about the operation that was performed.
However, I would definitely argue against the pass-an-object-in-and-fill-out-its-members approach. That just smells bad.
No, I don't believe so. Being able to return tuples in Python was actually quite handy.
In situations where you can use one of the possible return values to indicate something else (like a string/null-pointer or a length/negative-number), it's fine to return just the one thing.
But in cases where you need to use the full range and possibly return errors, you have to find some way of doing it. As long as the API contracts specify what happens, I see no problems with doing it the way you suggest.
The interface is still a tight "pipe" inasmuch as there's no leakage (the caller dictates what can be changed and no other caller uses those variables). Your solution is certainly better than cowboy coders who use global variables for this sort of thing.
As stated by other people it depends on what it is your doing, although imho if you can make it return one 'value' then its better.
However you could make a full class, which contains those values which would make the code easier to understand.
In Java, returning what you call a wrapper object
seems common practice to me, especially in the Transfer Object pattern but even for local calls when it makes sense.
Modifying parameters is also a very common technique. You can see examples in the JDK itself, like Collections.sort(List list) or InputStream.read(byte[]).
It's also frequent when dealing with persistent objects, like in the code snippet below
public void updateTrackingFields(Trackable trackable, String user) {
trackable.setChangedBy(user);
trackable.setChangedTime(System.currentTimeMillis());
}
So, I believe there could be much worse design decisions than those two.
EDIT: added the persistent object example.
精彩评论