Search code examples
scalanaming-conventionsmethod-names

Method naming convention in Scala -- mutable and not version?


This example is trivial just to show the point.

Let's say I use matrix library, but is lacks some power, let's say doubling every element in matrix is so crucial for me, I decide to write a method doubleIt. However, I could write 2 versions of this method

  1. mutable -- doubleItInPlace
  2. non mutable -- doubleItByCreatingNewOne

This is a bit lengthy, so one could think of naming convention, adding to mutable version _! suffix, or prefixing it with word "mut".

Is there any establishing naming convention for making such difference?


Solution

  • The convention is to name the mutable (in general, side-effecting) version with a verb in imperative form. Additionally, and more importantly, use the empty parameter list () at the end:

    def double()
    def doubleIt()
    

    The immutable version, i.e. one producing a new object, you should name via verb in the passive form. More importantly, do not use the empty parameter list () at the end:

    def doubled
    def doubledMatrix
    

    Note that naming the non-side-effecting method in the passive form is not always adhered (e.g. the standard collections library), but is a good idea unless it makes the name overly verbose.

    Source: Scala styleguide.