In Scala, I have a server
class, which has a method, say, getClients
, which returns the current connected clients.
I'm not sure how should I define it:
getClients
clients
getClients()
clients()
The return value of this method changes over time, when new clients connect or disconnect.
Which one should I choose?
When it comes to parentheses the important matter is if the method has side effects or not:
From Scala styleguide (http://docs.scala-lang.org/style/naming-conventions.html#parentheses)
Methods which act as accessors of any sort (either encapsulating a field or a logical property) should be declared without parentheses except if they have side effects.
It is true that the function is not pure if it depends on some changing value. However that is quite clear for the caller since the method is named like an accessor and it's arity-0 (arity-0 is an accessor or has side effect - otherwise it's useless!). The bigger issue is the side effect which should be communicated with using or not using the parentheses.
The difference between clients
and getClients
is - in my opinion - not so great since both can be seen as basic accessors. Leaving the get
out is kind of a convention in Scala so I would use clients
.
In accordance with the Scala style guide which addresses your issue as follows:
Methods which act as accessors of any sort (either encapsulating a field or a logical property) should be declared without parentheses except if they have side effects.
you should define your method without parenthesis (either getClients
or clients
, it's rather a matter of taste, yet, the guide suggest the second option) since it acts as an accessor and no side effects are presented. With reference to collection changes, I would say that it's a feature of a mutable collection and not the method itself.
In addition, if your intention is not to modified the collection outside the aggregate, perhaps you should consider changing returning result into the immutable variant and provide some way to notify a client about changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With