Mutator method
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), which returns the 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 compiler cannot restrict code from bypassing the mutator method and changing the variable directly. The onus falls to the developers
to ensure the variable is only modified through the mutator method and not modified directly.
In programming languages that support them,
properties
offer a convenient alternative without giving up the utility of encapsulation.
In the examples below, a fully implemented mutator method can also validate
the input data or take further action such as triggering an event
.
blocks, is to give the instance variable
some visibility
other than private and access it directly from outside the objects. Much finer control of access rights can be defined using mutators and accessors. For example, a parameter may be made read-only simply by defining an accessor but not a mutator. The visibility of the two methods may be different; it is often useful for the accessor to be public while the mutator remains protected, package-private or internal.
The block where the mutator is defined provides an opportunity for validation
or preprocessing of incoming data. If all external access is guaranteed to come through the mutator, then these steps cannot be bypassed. For example, if a date is represented by separate private
Accessors conversely allow for synthesis of useful data representations from internal variables while keeping their structure encapsulated and hidden from outside modules. A monetary
Modern programming languages often offer the ability to generate the boilerplate
for mutators and accessors in a single line—as for example C#'s
, the software is maintained
and requirements change, the demands on the data
become more sophisticated. Many automatic mutators and accessors eventually get replaced by separate blocks of code. The benefit of automatically creating them in the early days of the implementation is that the public interface of the class remains identical whether or not greater sophistication is added, requiring no extensive refactoring if it is.
Manipulation of parameters that have mutators and accessors from inside the class where they are defined often requires some additional thought. In the early days of an implementation, when there is little or no additional code in these blocks, it makes no difference if the private instance variable is accessed directly or not. As validation, cross-validation
, data integrity
checks, preprocessing or other sophistication is added, subtle bugs
may appear where some internal access makes use of the newer code while in other places it is bypassed.
Accessor functions are always less efficient than directly fetching or storing data fields due to the extra steps involved.
In file student.h:
In file student.c:
In file main.c:
In file Student.cpp:
member. Unlike Java, no explicit methods are defined; a public 'property' contains the logic to handle the actions. Note use of the built-in (undeclared) variable
In later C# versions (.NET Framework 3.5 and above), this example may be abbreviated as follows, without declaring the private variable
Using the abbreviated syntax means that the underlying variable is no longer available from inside the class. As a result, the
CLOS itself has no notion of properties, although the MetaObject Protocol extension specifies means to access a slot's reader and writer function names, including the ones generated with the
The following example shows a definition of a student class using these slot options and direct slot access:
(defclass student
((name :initarg :name :initform "" :accessor student-name) ; student-name is setf'able
(birthdate :initarg :birthdate :initform 0 :reader student-birthdate)
(number :initarg :number :initform 0 :reader student-number :writer set-student-number)))
(defmethod student-age ((self student))
(- (get-universal-time) (student-birthdate self)))
(defmethod (setf student-age) (new-age (self student))
(with-slots (birthdate) self
(setf birthdate (- (get-universal-time) new-age))
new-age))
(defmethod set-student-number :before (new-number (self student))
;; You could also check if a student with the new-number already exists.
(check-type new-number (integer 1 *)))
representing a student with only the name stored, one can see the variable
name is private, i.e. only visible from the Student class, and the "setter" and "getter" is public, namely the "
Or:
Or, using Class::Accessor
Or, using Moose Object System:
representing a student with only the name stored, one can see the variable
name is private, i.e. only visible from the Student class, and the "setter" and "getter" is public, namely the "
Struct definitions are an alternative way to define new types of values, with mutators being present when explicitly required:
, individual accessor and mutator methods may be defined, or the metaprogramming constructs
Defining individual accessor and mutator methods creates space for pre-processing or validation of the data
Read-only simple public access to implied
Read-write simple public access to implied
In VB.NET 2010, Auto Implemented properties can be utilized to create a property without having to use the Get and Set syntax. Note that a hidden variable is created by the compiler, called
Computer science
Computer science or computing science is the study of the theoretical foundations of information and computation and of practical techniques for their implementation and application in computer systems...
, a mutator method is a method
Method (computer science)
In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...
used to control changes to a variable.
The mutator method, sometimes called a "setter", is most often used in object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...
, in keeping with the principle of encapsulation. According to this principle, member variables
Variable (programming)
In computer programming, a variable is a symbolic name given to some known or unknown quantity or information, for the purpose of allowing the name to be used independently of the information it represents...
of a class
Class (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...
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), which returns the 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 compiler cannot restrict code from bypassing the mutator method and changing the variable directly. The onus falls to the developers
Software developer
A software developer is a person concerned with facets of the software development process. Their work includes researching, designing, developing, and testing software. A software developer may take part in design, computer programming, or software project management...
to ensure the variable is only modified through the mutator method and not modified directly.
In programming languages that support them,
properties
Property (programming)
A property, in some object-oriented programming languages, is a special sort of class member, intermediate between a field and a method. Properties are read and written like fields, but property reads and writes are translated to get and set method calls...
offer a convenient alternative without giving up the utility of encapsulation.
In the examples below, a fully implemented mutator method can also validate
Data validation
In computer science, data validation is the process of ensuring that a program operates on clean, correct and useful data. It uses routines, often called "validation rules" or "check routines", that check for correctness, meaningfulness, and security of data that are input to the system...
the input data or take further action such as triggering an event
Event (computing)
In computing an event is an action that is usually initiated outside the scope of a program and that is handled by a piece of code inside the program. Typically events are handled synchronous with the program flow, that is, the program has one or more dedicated places where events are handled...
.
Implications
The alternative to defining mutator and accessor methods, or propertyProperty (programming)
A property, in some object-oriented programming languages, is a special sort of class member, intermediate between a field and a method. Properties are read and written like fields, but property reads and writes are translated to get and set method calls...
blocks, is to give the instance variable
Instance variable
In object-oriented programming with classes, an instance variable is a variable defined in a class , for which each object of the class has a separate copy. They live in memory for the life of the object....
some visibility
Information hiding
In computer science, information hiding is the principle of segregation of the design decisions in a computer program that are most likely to change, thus protecting other parts of the program from extensive modification if the design decision is changed...
other than private and access it directly from outside the objects. Much finer control of access rights can be defined using mutators and accessors. For example, a parameter may be made read-only simply by defining an accessor but not a mutator. The visibility of the two methods may be different; it is often useful for the accessor to be public while the mutator remains protected, package-private or internal.
The block where the mutator is defined provides an opportunity for validation
Data validation
In computer science, data validation is the process of ensuring that a program operates on clean, correct and useful data. It uses routines, often called "validation rules" or "check routines", that check for correctness, meaningfulness, and security of data that are input to the system...
or preprocessing of incoming data. If all external access is guaranteed to come through the mutator, then these steps cannot be bypassed. For example, if a date is represented by separate private
year
, month
and day
variables, then incoming dates can be split by the setDate
mutator while for consistency the same private instance variables are accessed by setYear
and setMonth
. In all cases month values outside of 1 - 12 can be rejected by the same code.Accessors conversely allow for synthesis of useful data representations from internal variables while keeping their structure encapsulated and hidden from outside modules. A monetary
getAmount
accessor may build a string from a numeric variable with the number of decimal places defined by a hidden currency
parameter.Modern programming languages often offer the ability to generate the boilerplate
Boilerplate code
In computer programming, boilerplate is the term used to describe sections of code that have to be included in many places with little or no alteration. It is more often used when referring to languages which are considered verbose, i.e. the programmer must write a lot of code to do minimal jobs...
for mutators and accessors in a single line—as for example C#'s
public string Name { get; set; }
and Ruby's attr_accessor :name
. In these cases, no code blocks are created for validation, preprocessing or synthesis. These simplified accessors still retain the advantage of encapsulation over simple public instance variables, but it is common that, as system designs progressAgile software development
Agile software development is a group of software development methodologies based on iterative and incremental development, where requirements and solutions evolve through collaboration between self-organizing, cross-functional teams...
, the software is maintained
Software maintenance
Software Maintenance in software engineering is the modification of a software product after delivery to correct faults, to improve performance or other attributes....
and requirements change, the demands on the data
Data integrity
Data Integrity in its broadest meaning refers to the trustworthiness of system resources over their entire life cycle. In more analytic terms, it is "the representational faithfulness of information to the true state of the object that the information represents, where representational faithfulness...
become more sophisticated. Many automatic mutators and accessors eventually get replaced by separate blocks of code. The benefit of automatically creating them in the early days of the implementation is that the public interface of the class remains identical whether or not greater sophistication is added, requiring no extensive refactoring if it is.
Manipulation of parameters that have mutators and accessors from inside the class where they are defined often requires some additional thought. In the early days of an implementation, when there is little or no additional code in these blocks, it makes no difference if the private instance variable is accessed directly or not. As validation, cross-validation
Cross-validation
Cross-validation, sometimes called rotation estimation, is a technique for assessing how the results of a statistical analysis will generalize to an independent data set. It is mainly used in settings where the goal is prediction, and one wants to estimate how accurately a predictive model will...
, data integrity
Data integrity
Data Integrity in its broadest meaning refers to the trustworthiness of system resources over their entire life cycle. In more analytic terms, it is "the representational faithfulness of information to the true state of the object that the information represents, where representational faithfulness...
checks, preprocessing or other sophistication is added, subtle bugs
Software bug
A software bug is the common term used to describe an error, flaw, mistake, failure, or fault in a computer program or system that produces an incorrect or unexpected result, or causes it to behave in unintended ways. Most bugs arise from mistakes and errors made by people in either a program's...
may appear where some internal access makes use of the newer code while in other places it is bypassed.
Accessor functions are always less efficient than directly fetching or storing data fields due to the extra steps involved.
C example
Note that it is perfectly possible to do object-oriented programming with guaranteed encapsulation in pure C.In file student.h:
In file student.c:
In file main.c:
C++ example
In file Student.h:In file Student.cpp:
C# example
This example illustrates the C# idea of properties, which are a special type of classClass (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...
member. Unlike Java, no explicit methods are defined; a public 'property' contains the logic to handle the actions. Note use of the built-in (undeclared) variable
value
.In later C# versions (.NET Framework 3.5 and above), this example may be abbreviated as follows, without declaring the private variable
name
.Using the abbreviated syntax means that the underlying variable is no longer available from inside the class. As a result, the
set
portion of the property must be present for assignment. Access can be restricted with a set
-specific access modifier.Common Lisp example
In Common Lisp Object System, slot specifications within class definitions may specify any of the:reader
, :writer
and :accessor
options (even multiple times) to define reader methods, setter methods and acessor methods (a reader method and the respective setf
method). Slots are always directly accessible through their names with the use of with-slots
and slot-value
, and the slot accessor options define specialized methods that use slot-value
.CLOS itself has no notion of properties, although the MetaObject Protocol extension specifies means to access a slot's reader and writer function names, including the ones generated with the
:accessor
option.The following example shows a definition of a student class using these slot options and direct slot access:
(defclass student
((name :initarg :name :initform "" :accessor student-name) ; student-name is setf'able
(birthdate :initarg :birthdate :initform 0 :reader student-birthdate)
(number :initarg :number :initform 0 :reader student-number :writer set-student-number)))
- Example of a calculated property getter (this is simply a method
(defmethod student-age ((self student))
(- (get-universal-time) (student-birthdate self)))
- Example of direct slot access within a calculated property sette
(defmethod (setf student-age) (new-age (self student))
(with-slots (birthdate) self
(setf birthdate (- (get-universal-time) new-age))
new-age))
- The slot accessing options generate methods, thus allowing further method definition
(defmethod set-student-number :before (new-number (self student))
;; You could also check if a student with the new-number already exists.
(check-type new-number (integer 1 *)))
Delphi example
This is a simple class in Delphi language that illustrates the concept of public property that access a private field.Java example
In this example of a simple classClass (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...
representing a student with only the name stored, one can see the variable
Variable (programming)
In computer programming, a variable is a symbolic name given to some known or unknown quantity or information, for the purpose of allowing the name to be used independently of the information it represents...
name is private, i.e. only visible from the Student class, and the "setter" and "getter" is public, namely the "
getName
" and "setName(name)
" methods.JavaScript example
In this example constructor-functionStudent
is used to create objects representing a student with only the name stored.Or:
Actionscript 3.0 example
Perl example
Or, using Class::Accessor
Or, using Moose Object System:
PHP example
It this example of a simple classClass (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...
representing a student with only the name stored, one can see the variable
Variable (programming)
In computer programming, a variable is a symbolic name given to some known or unknown quantity or information, for the purpose of allowing the name to be used independently of the information it represents...
name is private, i.e. only visible from the Student class, and the "setter" and "getter" is public, namely the "
getName
" and "setName('name')
" methods.Python example
This example uses a Python class with one variable, a getter, and a setter.Racket
In Racket, the object system is a way to organize code that comes in addition to modules and units. As in the rest of the language, the object system has first-class values and lexical scope is used to control access to objects and methods.Struct definitions are an alternative way to define new types of values, with mutators being present when explicitly required:
Ruby example
In RubyRuby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...
, individual accessor and mutator methods may be defined, or the metaprogramming constructs
attr_reader
or attr_accessor
may be used both to declare a private variable in a class and to provide either read-only or read-write public access to it respectively.Defining individual accessor and mutator methods creates space for pre-processing or validation of the data
Read-only simple public access to implied
@name
variableRead-write simple public access to implied
@name
variableSmalltalk example
Visual Basic .NET example
This example illustrates the VB.NET idea of properties, which are used in classes. Similar to C#, there is an explicit use of theGet
and Set
methods.In VB.NET 2010, Auto Implemented properties can be utilized to create a property without having to use the Get and Set syntax. Note that a hidden variable is created by the compiler, called
_name
, to correspond with the Property name
. Using another variable within the class named _name
would result in an error. Privileged access to the underlying variable is available from within the class.