Enforcing Rules with Java’s Accessor Methods

By Barry A. Burd

Enforcing rules is tough. Luckily for you, Java has a more elegant solution than many parents are faced with. You can use accessor methods to make your stubborn code follow your rules.

Here’s some code that hides the fields.

public class Account {

private String name;

private String address;

private double balance;

public void setName(String n) {

name = n;

}

public String getName() {

return name;

}

public void setAddress(String a) {

address = a;

}

public String getAddress() {

return address;

}

public void setBalance(double b) {

balance = b;

}

public double getBalance() {

return balance;

}

}

Go back and take a quick look at the setName method. Imagine putting the method’s assignment statement inside an if statement.

public void setName(String n) {

if (!n.equals("")) {

name = n;

}

}

Now, if the programmer in charge of the UseAccount class writes myAccount.setName(""), the call to setName doesn’t have any effect. Furthermore, because the name field is private, the following statement is illegal in the UseAccount class:

myAccount.name = "";

Of course, a call such as myAccount.setName("Joe Schmoe") still works because "Joe Schmoe" doesn’t equal the empty string "".

That’s cool. With a private field and an accessor method, you can prevent someone from assigning the empty string to an account’s name field. With more elaborate if statements, you can enforce any rules you want.