HOME

TheInfoList



OR:

In
computer science Computer science is the study of computation, automation, and information. Computer science spans theoretical disciplines (such as algorithms, theory of computation, information theory, and automation) to Applied science, practical discipli ...
, a mutator method is a
method Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
used to control changes to a variable. They are also widely known as setter methods. Often a setter is accompanied by a getter (together also known as accessors), which returns the value of the private member variable. The mutator method is most often used in
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
, in keeping with the principle of encapsulation. According to this principle, member variables of a
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differently ...
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 In object-oriented programming, a member variable (sometimes called a member field) is a variable that is associated with a specific object, and accessible for all its methods (''member functions''). In class-based programming languages, these ...
. Mutator methods can be compared to assignment operator overloading but they typically appear at different levels of the object hierarchy. Mutator methods may also be used in non-object-oriented environments. In this case, a
reference Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a '' name'' ...
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 responsibility 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 Property is the ownership of land, resources, improvements or other tangible objects, or intellectual property. Property may also refer to: Mathematics * Property (mathematics) Philosophy and science * Property (philosophy), in philosophy an ...
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 Event may refer to: Gatherings of people * Ceremony, an event of ritual significance, performed on a special occasion * Convention (meeting), a gathering of individuals engaged in some common interest * Event management, the organization of ev ...
.


Implications

The alternative to defining mutator and accessor methods, or
property Property is a system of rights that gives people legal control of valuable things, and also refers to the valuable things themselves. Depending on the nature of the property, an owner of property may have the right to consume, alter, share, r ...
blocks, is to give the instance variable some
visibility The visibility is the measure of the distance at which an object or light can be clearly discerned. In meteorology it depends on the transparency of the surrounding air and as such, it is unchanging no matter the ambient light level or time o ...
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 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 for mutators and accessors in a single line—as for example C#'s public string Name 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 progress, 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 Data integrity is the maintenance of, and the assurance of, data accuracy and consistency over its entire life-cycle and is a critical aspect to the design, implementation, and usage of any system that stores, processes, or retrieves data. The ter ...
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 can be less efficient than directly fetching or storing data fields due to the extra steps involved, however such functions are often inlined which eliminates the overhead of a function call.


Examples


Assembly

student struct age dd ? student ends .code student_get_age proc object:DWORD mov ebx, object mov eax, student.age bx ret student_get_age endp student_set_age proc object:DWORD, age:DWORD mov ebx, object mov eax, age mov student.age bx eax ret student_set_age endp


C

In file student.h: #ifndef _STUDENT_H #define _STUDENT_H struct student; /* opaque structure */ typedef struct student student; student *student_new(int age, char *name); void student_delete(student *s); void student_set_age(student *s, int age); int student_get_age(student *s); char *student_get_name(student *s); #endif In file student.c: #include #include #include "student.h" struct student ; student *student_new(int age, char *name) void student_delete(student *s) void student_set_age(student *s, int age) int student_get_age(student *s) char *student_get_name(student *s) In file main.c: #include #include "student.h" int main(void) In file Makefile: all: out.txt; cat $< out.txt: main; ./$< > $@ main: main.o student.o main.o student.o: student.h clean: ;$(RM) *.o out.txt main


C++

In file Student.h: #ifndef STUDENT_H #define STUDENT_H #include class Student ; #endif In file Student.cpp: #include "Student.h" Student::Student(const std::string& name) : name_(name) const std::string& Student::name() const void Student::name(const std::string& name)


C#

This example illustrates the C# idea of
properties Property is the ownership of land, resources, improvements or other tangible objects, or intellectual property. Property may also refer to: Mathematics * Property (mathematics) Philosophy and science * Property (philosophy), in philosophy an ...
, which are a special type of
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differently ...
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. public class Student In later C# versions (.NET Framework 3.5 and above), this example may be abbreviated as follows, without declaring the private variable name. public class Student 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. public class Student


Common Lisp

In
Common Lisp Object System The Common Lisp Object System (CLOS) is the facility for object-oriented programming which is part of ANSI Common Lisp. CLOS is a powerful dynamic object system which differs radically from the OOP facilities found in more static languages suc ...
, 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 accessor 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 setter (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 definitions (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 *)))


D

D supports a getter and setter function syntax. In version 2 of the language getter and setter class/struct methods should have the @property attribute. class Student A Student instance can be used like this: auto student = new Student; student.name = "David"; // same effect as student.name("David") auto student_name = student.name; // same effect as student.name()


Delphi

This is a simple class in Delphi language which illustrates the concept of public property for accessing a private field. interface type TStudent = class strict private FName: string; procedure SetName(const Value: string); public /// /// Get or set the name of the student. /// property Name: string read FName write SetName; end; // ... implementation procedure TStudent.SetName(const Value: string); begin FName := Value; end; end.


Java

In this example of a simple
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differently ...
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" are public, namely the "getName()" and "setName(name)" methods. public class Student


JavaScript

In this example constructor-function Student is used to create objects representing a student with only the name stored. function Student(name) Or (using a deprecated way to define accessors in Web browsers): function Student(name) Or (using prototypes for inheritance and ES6 accessor syntax): function Student(name) Student.prototype = ; Or (without using prototypes): var Student = ; Or (using defineProperty): function Student(name) Object.defineProperty(Student.prototype, 'name', );


Actionscript 3.0

package


Objective-C

Using traditional Objective-C 1.0 syntax, with manual reference counting as the one working on
GNUstep GNUstep is a free software implementation of the Cocoa (formerly OpenStep) Objective-C frameworks, widget toolkit, and application development tools for Unix-like operating systems and Microsoft Windows. It is part of the GNU Project. GNUste ...
on Ubuntu 12.04: @interface Student : NSObject - (NSString *)name; - (void)setName:(NSString *)name; @end @implementation Student - (NSString *)name - (void)setName:(NSString *)name @end Using newer Objective-C 2.0 syntax as used in Mac OS X 10.6,
iOS 4 iOS 4 is the fourth major release of the iOS mobile operating system developed by Apple Inc., being the successor to iPhone OS 3. It was announced at the Apple Special Event on April 8, 2010, and was released on June 21, 2010. iOS 4 is the ...
and
Xcode Xcode is Apple's integrated development environment (IDE) for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, and tvOS. It was initially released in late 2003; the latest stable release is version 14.2, released on December 13, ...
3.2, generating the same code as described above: @interface Student : NSObject @property (nonatomic, retain) NSString *name; @end @implementation Student @synthesize name = _name; @end And starting with OS X 10.8 and
iOS 6 iOS 6 is the sixth major release of the iOS mobile operating system developed by Apple Inc, being the successor to iOS 5. It was announced at the company's Worldwide Developers Conference on June 11, 2012, and was released on September 19, 20 ...
, while using
Xcode Xcode is Apple's integrated development environment (IDE) for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, and tvOS. It was initially released in late 2003; the latest stable release is version 14.2, released on December 13, ...
4.4 and up, syntax can be even simplified: @interface Student : NSObject @property (nonatomic, strong) NSString *name; @end @implementation Student //Nothing goes here and it's OK. @end


Perl

package Student; sub new sub set_name sub get_name 1; Or, using Class::Accessor package Student; use base qw(Class::Accessor); __PACKAGE__->follow_best_practice; Student->mk_accessors(qw(name)); 1; Or, using the Moose Object System: package Student; use Moose; # Moose uses the attribute name as the setter and getter, the reader and writer properties # allow us to override that and provide our own names, in this case get_name and set_name has 'name' => (is => 'rw', isa => 'Str', reader => 'get_name', writer => 'set_name'); 1;


PHP

PHP defines the "magic methods" __getand__set for properties of objects. In this example of a simple
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differently ...
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 getName() and setName('name') methods. class Student


Python

This example uses a Python class with one variable, a getter, and a setter. class Student: # Initializer def __init__(self, name: str) -> None: # An instance variable to hold the student's name self._name = name # Getter method @property def name(self): return self._name # Setter method @name.setter def name(self, new_name): self._name = new_name >>> bob = Student("Bob") >>> bob.name Bob >>> bob.name = "Alice" >>> bob.name Alice >>> bob._name = "Charlie" # bypass the setter >>> bob._name # bypass the getter Charlie


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. #lang racket (define student% (class object% (init-field name) (define/public (get-name) name) (define/public (set-name! new-name) (set! name new-name)) (super-new))) (define s (new student% ame "Alice") (send s get-name) ; => "Alice" (send s set-name! "Bob") (send s get-name) ; => "Bob" Struct definitions are an alternative way to define new types of values, with mutators being present when explicitly required: #lang racket (struct student (name) #:mutable) (define s (student "Alice")) (set-student-name! s "Bob") (student-name s) ; => "Bob"


Ruby

In
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called ...
, 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 class Student def name @name end def name=(value) @name=value end end Read-only simple public access to implied @name variable class Student attr_reader :name end Read-write simple public access to implied @name variable class Student attr_accessor :name end


Smalltalk

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


Swift

class Student


Visual Basic .NET

This example illustrates the VB.NET idea of properties, which are used in classes. Similar to C#, there is an explicit use of the Get and Set methods. Public Class Student Private _name As String Public Property Name() Get Return _name End Get Set(ByVal value) _name = value End Set End Property End Class 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. Public Class Student Public Property name As String End Class


See also

*
Property (programming) A property, in some object-oriented programming languages, is a special sort of class member, intermediate in functionality between a field (or data member) and a method. The syntax for reading and writing of properties is like for fields, but pr ...
* Indexer (programming) *
Immutable object In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created.Goetz et al. ''Java Concurrency in Practice''. Addison Wesley Professional, 2006, Section 3. ...


References

{{DEFAULTSORT:Mutator Method Method (computer programming) Articles with example BASIC code Articles with example C Sharp code Articles with example C++ code Articles with example Java code Articles with example Lisp (programming language) code Articles with example Pascal code Articles with example Perl code Articles with example PHP code Articles with example Python (programming language) code Articles with example Racket code Articles with example Ruby code Articles with example Smalltalk code