简体   繁体   中英

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?

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, ie 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 (eg the standard collections library), but is a good idea unless it makes the name overly verbose.

Source: Scala styleguide .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM