Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use `()` or not for the method `getClients` when the return value can be changed?

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:

  1. getClients
  2. clients
  3. getClients()
  4. clients()

The return value of this method changes over time, when new clients connect or disconnect.

Which one should I choose?

like image 305
Freewind Avatar asked Dec 04 '22 03:12

Freewind


2 Answers

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.

like image 178
Matias Saarinen Avatar answered Jan 06 '23 07:01

Matias Saarinen


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.

like image 40
Daniel Olszewski Avatar answered Jan 06 '23 06:01

Daniel Olszewski