Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Mutator method
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Examples== [[File:UML mutator method.svg]] ===Assembly=== <syntaxhighlight lang="nasm"> student struct age dd ? student ends </syntaxhighlight> <syntaxhighlight lang="nasm"> .code student_get_age proc object:DWORD mov ebx, object mov eax, student.age[ebx] ret student_get_age endp student_set_age proc object:DWORD, age:DWORD mov ebx, object mov eax, age mov student.age[ebx], eax ret student_set_age endp </syntaxhighlight> ===C=== In file student.h: <syntaxhighlight lang="C"> #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 </syntaxhighlight> In file student.c: <syntaxhighlight lang="C"> #include <stdlib.h> #include <string.h> #include "student.h" struct student { int age; char *name; }; student *student_new(int age, char *name) { student *s = malloc(sizeof(student)); s->name = strdup(name); s->age = age; return s; } void student_delete(student *s) { free(s->name); free(s); } void student_set_age(student *s, int age) { s->age = age; } int student_get_age(student *s) { return s->age; } char *student_get_name(student *s) { return s->name; } </syntaxhighlight> In file main.c: <syntaxhighlight lang="C"> #include <stdio.h> #include "student.h" int main(void) { student *s = student_new(19, "Maurice"); char *name = student_get_name(s); int old_age = student_get_age(s); printf("%s's old age = %i\n", name, old_age); student_set_age(s, 21); int new_age = student_get_age(s); printf("%s's new age = %i\n", name, new_age); student_delete(s); return 0; } </syntaxhighlight> In file Makefile: <syntaxhighlight lang="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 </syntaxhighlight> ===C++=== In file Student.h: <syntaxhighlight lang="cpp"> #ifndef STUDENT_H #define STUDENT_H #include <string> class Student { public: Student(const std::string& name); const std::string& name() const; void name(const std::string& name); private: std::string name_; }; #endif </syntaxhighlight> In file Student.cpp: <syntaxhighlight lang="cpp"> #include "Student.h" Student::Student(const std::string& name) : name_(name) { } const std::string& Student::name() const { return name_; } void Student::name(const std::string& name) { name_ = name; } </syntaxhighlight> ===C#=== This example illustrates the [[C Sharp (programming language)|C#]] idea of [[Property (programming)#C#|properties]], which are a special type of [[Class (computer science)|class]] 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 <code>value</code>. <syntaxhighlight lang="csharp"> public class Student { private string name; /// <summary> /// Gets or sets student's name /// </summary> public string Name { get { return name; } set { name = value; } } } </syntaxhighlight> In later C# versions (.NET Framework 3.5 and above), this example may be abbreviated as follows, without declaring the private variable <code>name</code>. <syntaxhighlight lang="csharp"> public class Student { public string Name { get; set; } } </syntaxhighlight> Using the abbreviated syntax means that the underlying variable is no longer available from inside the class. As a result, the <code>set</code> portion of the property must be present for assignment. Access can be restricted with a <code>set</code>-specific access modifier. <syntaxhighlight lang="csharp"> public class Student { public string Name { get; private set; } } </syntaxhighlight> ===Common Lisp=== In [[Common Lisp Object System]], slot specifications within class definitions may specify any of the <code>:reader</code>, <code>:writer</code> and <code>:accessor</code> options (even multiple times) to define reader methods, setter methods and accessor methods (a reader method and the respective <code>setf</code> method).<ref name="defclass">{{cite web |url=http://www.lispworks.com/documentation/HyperSpec/Body/m_defcla.htm |title=CLHS: Macro DEFCLASS |accessdate=2011-03-29}}</ref> Slots are always directly accessible through their names with the use of <code>with-slots</code> and <code>slot-value</code>, and the slot accessor options define specialized methods that use <code>slot-value</code>.<ref name="defclass-accessors">{{cite web |url=http://www.lispworks.com/documentation/HyperSpec/Body/07_eb.htm |title=CLHS: 7.5.2 Accessing Slots |accessdate=2011-03-29}}</ref> CLOS itself has no notion of properties, although the [[Common Lisp Object System#Metaobject Protocol|MetaObject Protocol]] extension specifies means to access a slot's reader and writer function names, including the ones generated with the <code>:accessor</code> option.<ref name="mop-slot-definitions">{{cite web |url=http://www.lisp.org/mop/concepts.html#slot-definitions |title=MOP: Slot Definitions |accessdate=2011-03-29}}</ref> The following example shows a definition of a student class using these slot options and direct slot access: <syntaxhighlight lang="lisp"> (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 *))) </syntaxhighlight> ===D=== [[D (programming language)|D]] supports a getter and setter function syntax. In version 2 of the language getter and setter class/struct methods should have the <code>@property</code> attribute.<ref>{{cite web |url=http://dlang.org/function.html |title=Functions - D Programming Language |accessdate=2013-01-13}}</ref><ref>{{cite web|url=http://dlang.org/dstyle.html |title=The D Style |accessdate=2013-02-01}}</ref> <syntaxhighlight lang="d"> class Student { private char[] name_; // Getter @property char[] name() { return this.name_; } // Setter @property char[] name(char[] name_in) { return this.name_ = name_in; } } </syntaxhighlight> A <code>Student</code> instance can be used like this: <syntaxhighlight lang="d"> auto student = new Student; student.name = "David"; // same effect as student.name("David") auto student_name = student.name; // same effect as student.name() </syntaxhighlight> ===Delphi=== This is a simple class in Delphi language which illustrates the concept of public property for accessing a private field. <syntaxhighlight lang="delphi"> interface type TStudent = class strict private FName: string; procedure SetName(const Value: string); public /// <summary> /// Get or set the name of the student. /// </summary> property Name: string read FName write SetName; end; // ... implementation procedure TStudent.SetName(const Value: string); begin FName := Value; end; end. </syntaxhighlight> ===Java=== In this example of a simple [[Class (computer science)|class]] representing a student with only the name stored, one can see the [[Variable (programming)|variable]] ''name'' is private, i.e. only visible from the Student class, and the "setter" and "getter" are public, namely the "<code>getName()</code>" and "<code>setName(name)</code>" methods. <syntaxhighlight lang="java"> public class Student { private String name; public String getName() { return name; } public void setName(String newName) { name = newName; } }</syntaxhighlight> ===JavaScript=== In this example constructor-function <code>Student</code> is used to create objects representing a student with only the name stored. <syntaxhighlight lang="javascript"> function Student(name) { var _name = name; this.getName = function() { return _name; }; this.setName = function(value) { _name = value; }; } </syntaxhighlight> Or (using a deprecated way to define accessors in Web browsers):<ref>{{Cite web|title=Object.prototype.__defineGetter__() - JavaScript {{!}} MDN|url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__|access-date=2021-07-06|website=developer.mozilla.org|language=en-US}}</ref> <syntaxhighlight lang="javascript"> function Student(name){ var _name = name; this.__defineGetter__('name', function() { return _name; }); this.__defineSetter__('name', function(value) { _name = value; }); } </syntaxhighlight> Or (using prototypes for inheritance and [[ES6]] accessor syntax): <syntaxhighlight lang="javascript"> function Student(name){ this._name = name; } Student.prototype = { get name() { return this._name; }, set name(value) { this._name = value; } }; </syntaxhighlight> Or (without using prototypes): <syntaxhighlight lang="javascript"> var Student = { get name() { return this._name; }, set name(value) { this._name = value; } }; </syntaxhighlight> Or (using defineProperty): <syntaxhighlight lang="javascript"> function Student(name){ this._name = name; } Object.defineProperty(Student.prototype, 'name', { get: function() { return this._name; }, set: function(value) { this._name = value; } }); </syntaxhighlight> ===ActionScript 3.0=== <syntaxhighlight lang="actionscript"> package { public class Student { private var _name : String; public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } } } </syntaxhighlight> ===Objective-C=== Using traditional Objective-C 1.0 syntax, with manual reference counting as the one working on [[GNUstep]] on [[Ubuntu version history#1204|Ubuntu 12.04]]: <syntaxhighlight lang="objc"> @interface Student : NSObject { NSString *_name; } - (NSString *)name; - (void)setName:(NSString *)name; @end @implementation Student - (NSString *)name { return _name; } - (void)setName:(NSString *)name { [_name release]; _name = [name retain]; } @end </syntaxhighlight> Using newer Objective-C 2.0 syntax as used in [[Mac OS X 10.6]], [[iOS 4]] and [[Xcode]] 3.2, generating the same code as described above: <syntaxhighlight lang="objc"> @interface Student : NSObject @property (nonatomic, retain) NSString *name; @end @implementation Student @synthesize name = _name; @end </syntaxhighlight> And starting with [[OS X 10.8]] and [[iOS 6]], while using [[Xcode]] 4.4 and up, syntax can be even simplified: <syntaxhighlight lang="objc"> @interface Student : NSObject @property (nonatomic, strong) NSString *name; @end @implementation Student //Nothing goes here and it's OK. @end </syntaxhighlight> ===Perl=== <syntaxhighlight lang="perl"> package Student; sub new { bless {}, shift; } sub set_name { my $self = shift; $self->{name} = $_[0]; } sub get_name { my $self = shift; return $self->{name}; } 1; </syntaxhighlight> Or, using Class::Accessor <syntaxhighlight lang="perl"> package Student; use base qw(Class::Accessor); __PACKAGE__->follow_best_practice; Student->mk_accessors(qw(name)); 1; </syntaxhighlight> Or, using the [[Moose (Perl)|Moose Object System]]: <syntaxhighlight lang="perl"> 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; </syntaxhighlight> ===PHP=== PHP defines the "magic methods" <code>__get</code>and<code>__set</code> for properties of objects.<ref>{{Cite web|title=PHP: Overloading - Manual|url=https://www.php.net/manual/en/language.oop5.overloading.php|access-date=2021-07-06|website=www.php.net}}</ref> In this example of a simple [[Class (computer science)|class]] representing a student with only the name stored, one can see the [[Variable (programming)|variable]] ''name'' is private, i.e. only visible from the Student class, and the "setter" and "getter" is public, namely the <code>getName()</code> and <code>setName('name')</code> methods. <syntaxhighlight lang="php"> class Student { private string $name; /** * @return string The name. */ public function getName(): string { return $this->name; } /** * @param string $newName The name to set. */ public function setName(string $newName): void { $this->name = $newName; } }</syntaxhighlight> ===Python=== This example uses a Python class with one variable, a getter, and a setter. <syntaxhighlight lang="python"> 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 </syntaxhighlight> <syntaxhighlight lang="pycon"> >>> bob = Student("Bob") >>> bob.name Bob >>> bob.name = "Alice" >>> bob.name Alice >>> bob._name = "Charlie" # bypass the setter >>> bob._name # bypass the getter Charlie </syntaxhighlight> ===Racket=== In [[Racket (programming language)|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. <syntaxhighlight lang="racket"> #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% [name "Alice"])) (send s get-name) ; => "Alice" (send s set-name! "Bob") (send s get-name) ; => "Bob" </syntaxhighlight> Struct definitions are an alternative way to define new types of values, with mutators being present when explicitly required: <syntaxhighlight lang="racket"> #lang racket (struct student (name) #:mutable) (define s (student "Alice")) (set-student-name! s "Bob") (student-name s) ; => "Bob" </syntaxhighlight> ===Ruby=== In [[Ruby (programming language)|Ruby]], individual accessor and mutator methods may be defined, or the metaprogramming constructs <code>attr_reader</code> or <code>attr_accessor</code> 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 <syntaxhighlight lang="ruby"> class Student def name @name end def name=(value) @name=value end end </syntaxhighlight> Read-only simple public access to implied <code>@name</code> variable <syntaxhighlight lang="ruby"> class Student attr_reader :name end </syntaxhighlight> Read-write simple public access to implied <code>@name</code> variable <syntaxhighlight lang="ruby"> class Student attr_accessor :name end </syntaxhighlight> ===Rust=== <syntaxhighlight lang="rust"> struct Student { name: String, } impl Student { fn name(&self) -> &String { &self.name } fn name_mut(&mut self) -> &mut String { &mut self.name } } </syntaxhighlight> ===Smalltalk=== <syntaxhighlight lang="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 ] </syntaxhighlight> ===Swift=== <syntaxhighlight lang="swift"> class Student { private var _name: String = "" var name: String { get { return self._name } set { self._name = newValue } } } </syntaxhighlight> ===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 <code>Get</code> and <code>Set</code> methods. <syntaxhighlight lang="vbnet"> 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 </syntaxhighlight> 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 <code>_name</code>, to correspond with the Property <code>name</code>. Using another variable within the class named <code>_name</code> would result in an error. Privileged access to the underlying variable is available from within the class. <syntaxhighlight lang="vbnet"> Public Class Student Public Property name As String End Class </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)