Mutator method

From Wikipedia, the free encyclopedia

In computer science, a mutator method is a method used to control changes to a variable.

The mutator method, sometimes called a "setter", is most often used in object-oriented programming, in keeping with the principle of encapsulation. According to this principle, member variables of a class are made private to hide and protect them from other code, and can only be modified by a public member function (the mutator method), which takes the desired new value as a parameter, optionally validates it, and modifies the private member variable.

Often a "setter" is accompanied by a "getter" (also known as an accessor method), which simply returns the current value of the private member variable.

Mutator methods may also be used in non-object-oriented environments. In this case, a reference to the variable to be modified is passed to the mutator, along with the new value. In this scenario, the data is not protected from changes that bypass the mutator method, whose role becomes simply to validate the input, and the onus falls to the developer to ensure the variable isn't modified directly.

[edit] Smalltalk example

age: aNumber
     " Set the receiver age to be aNumber if is greater than 0 and less than 150 "
    (aNumber between: 0 and: 150)
       ifTrue: [ age := aNumber ]