In object-oriented programming languages, a method on an object that sets a property of that object. Mutators are the simplest example of a setter method, which explicitly assign the value of the parameter to a given field or data member.

However, other types of setter method are possible. One example is a setter method that performs validation before assignment. If the parameter passed is not a legal value for the particular property, the method may choose to log an error or throw an exception. In circumstances where fail fast behavior is inappropriate, parameters that are out of bounds may alternatively be clipped to a valid range.

Setter methods can also be written to incorporate side effects. An application with a database back-end may wish to maintain data integrity by updating the corresponding record whenever a setter method is called. One common application of AOP is to intercept every setter and wrap the call within a database transaction.

Another common variant of the setter method uses synthesis. Systems such as JavaBeans or scripting languages use the existence of getter and setter methods to deduce the existence of a property. An interface specification may require a particular setter, but the underlying object has no such data member. In these cases, the property is synthesized by calculating and assigning to different members of the object.

In many ways, setter methods are among the triumphs of coding standards over common sense. Their implementation ranges from tediously trivial automatic code generation of mutators by an IDE, to fiddly database update statements or thread-safe structure manipulation. There's surely something wrong when the right thing to do is to write

public void setBalance(double balance)
{
    this.balance = balance;
}
so an ECMAScript writer can use
account.balance = 0.0;
even though that's probably what you'd rather have written in the first place? However, setter methods do have some advantages, particularly in newer paradigms such as dependency injection.

Log in or register to write something here or to contact authors.