3 ms·
> For example, you probably should never use it for something that returns an array of results, or a list of results; instead return an empty array or list Thi
by chriswarbo 4y ago
> For example, you probably should never use it for something that returns an array of results, or a list of results; instead return an empty array or list
This also applies to null/Maybe as well: both would violate the principle of least surprise (e.g. the AWS DynamoDB SDK has queries return an 'Array<Item>'; but this is 'null' if there are no matches!). It also complicates the domain model, making two distinct forms of empty value ('None' versus 'Some(List())'; or '[]' versus 'null'), which may not have any semantic difference.
> You should almost never use it as a field of something
I agree, although it's often preferable to expose methods rather than fields anyway; in which case it's a return value, which seems OK.
> or a method parameter
Sure, that's what polymorphism/overloading is good for, e.g. instead of `foo(int arg1, Optional<String> arg2)` we can have separate `foo(int arg1, String arg2)` and `foo(int arg1)` definitions (where the latter will probably call the former with some default).
> I think routinely using it as a return value for getters would definitely be over-use
I agree, since that would indicate our model is too weak, and missing some domain-relevant information. For example, if many of our 'Order' methods return optional results, there's probably a finer-grained distinction to be made, like 'PendingOrder', 'FulfilledOrder', etc. which don't need the optional qualifiers.
(Personally I try to avoid the term "getter": APIs should make sense without reference to their underlying implementation; whether that happens to be "getting" a field, or calling out to some other methods/objects, etc. That's the point of encapsulation :) )