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.
In programming languages that support them, Properties offer a convenient alternative without giving up the utility of encapsulation.
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
Java example
It this example of a simple class representing a student with only the name stored, one can see the variable name being private, i.e. only visible from the Student class, and the "setter" and "getter" being public, namely the "getName()" and "setName(name)" methods.
public class Student {
private String name;
public Student(String newName) {
name = newName;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param newName
* the name to set
*/
public void setName(String newName) {
name = newName;
}
}
C# example
This example illustrates the C# idea of properties, which are a special type of class member. Unlike Java, no explicit methods are defined that handle the "getting" and "setting" of the private member variable. Rather, a public property is exposed for the private variable which defines logic to handle such actions.
public class Student {
private string name;
/// <summary>
/// gets or sets student's name
/// </summary>
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
/// <summary>
/// public constructor
/// </summary>
/// <param name="newName">
/// the name to set
/// </param>
public Student(string newName) {
Name = newName;
}
}
|