Many Java methods in the JDK, such as List.set()
and Map.put()
both change an object and return a result instead of keeping mutator and accessor separate.
It seems to me that for most of these methods, the return value is more of a side effect, and it wouldn't make sense to have a separate method to retrieve it.
But apart from this, are there other benefits and drawbacks of each approach? How do I decide which way is more appropriate?
For example, I'm creating a simulator object, calling the runSimulation()
method, and I need the boolean
result. I could store it in the simulator object and return it in a separate accessor method called after, or return it in the mutator itself, as I'm doing now.
Unless runSimulation() is a blocking method and you want to run it asynchronously so it doesn't block your main thread, theres no harm in returning the result with the same method you create the simulation with, as long as returning it can be done cheaply.
Sometimes it is a matter of convenience: is the design of your object such that users will almost always be requesting the result after creating/running the simulation? It might be a good idea, then, to return the result in the mutating method (maybe you could name the method "runSimulationForResult()").
Sometimes it's a matter of efficiency: for some kinds of List implementations (LinkedList, etc.), calling get() followed by set() means the list is traversed twice instead of once, and even though it might not be a super common pattern, the designers decided there wasn't any harm in returning the previous value, since it could be achieved practically for free, and would make certain idioms twice as fast.