Reputation: 720
I have method that takes a Map of [Int, MyClass] as an argument. Something like this:
myMethod(someMap : Map[Int, MyClass])
However, the someMap might be not always be present (null in Java world and None in Scala). Which of the following is a better design of this method from an API point of view:
Wrapping it in an Option: myMethod(someMap : Option[Map[Int, MyClass]] = None)
Defining an default empty map: myMethod(someMap : Map[Int, MyClass] = Maps.empty)
The first option looks elegant, however it has the added complexity that one has to wrap a Map (if not None) in Some() and in the implementor has to do a getOrElse to unwrap it. The first option also makes it clear to the consumer of the api, that the map object might not actually exist (None)
In the second option, one does not have to do the wrapping (in Some) or unwrapping, but an empty container has to be instantiated every time there is no existing Map object.
Also, the arguments agains 1: Option is itself a container of 0 or 1 item and Map is also a container (collection). Is it good design to wrap a container in another container ?
From an API design point of view, which one is the better approach?
Upvotes: 1
Views: 208
Reputation: 67330
Map.empty
is a cheap operation, a result of it being immutable. So there is virtually no overhead in using it. Therefore, keep it simple, ask for a Map
without any wrapping.
Upvotes: 3
Reputation: 53869
The right question is: does it make sense for myMethod
to work with an Option
?
From the point of view of myMethod
, maybe it only works with Map
in which case it is the responsability of the caller not to call myMethod
if there is no map to work with.
On the other hand, maybe myMethod
does something special if there no Map
or if it is empty and that is the responsability of the method to handle this case.
So there is no right answer but the correct argument is the one so that the responsabilities of the methods are respected. The aim is to have high cohesion and low coupling between your functions and classes.
Upvotes: 4