Pritam Banerjee
Pritam Banerjee

Reputation: 18923

What is the best way to design getters and setters and why?

I was wondering what is the best way to write getters and setters ?

Should we check for the conditions in getters or should we do it in the setters ?

Which is the standard procedure to do so and why ?

Suppose I have a class Products:(This is just an example, only asking about the approach to design getters and setters)

public class Product {
private String productName;

public String getProductName() {
    if (productName != null || !productName.equals("")){
        return productName;
    }else {
        return "Product Name Not found";
    }
}
public void setProductName(String productName) {
    String productName2 = productName;
    if (productName != null || !productName2.equals("")){
        this.productName = productName;
    }else {
        this.productName = "Product Name Not found";
    }
 }
}

Upvotes: -2

Views: 121

Answers (2)

paulsm4
paulsm4

Reputation: 121599

Suggestion:

public class Product {
  private String productName;

  public Product(String productName) {
    this.productName = productName;
  }

  public String getProductName() {
    return this.productName;
  }

  public void setProductName(String productName) {
    this.productname = productName;
  }

Rationale:

  1. In general, member data should be private (EX: "private String productName")

  2. If "outsiders" need to read a member, supply a getter method.

  3. If "outsiders" need to modify a member, supply a "setting" method. It's appropriate to add validation code to your setter. It's generally good practice to throw an exception if validation fails.

  4. In general, if you can initialize something in the constructor, you should. More specifically, the purpose of a "constructor" is to establish "invariant conditions" for the class.

Notes

  • If you're writing a Java Bean, you might need a "no args" constructor. In that case, add an"init()" method to substitute for the constructor I described above.

  • It's perfectly appropriate to initialize multiple members at once - either in your constructor, or in a custom "init()".

Upvotes: 2

user207421
user207421

Reputation: 310840

In the setter. It's too late in the getter. Catch the error as soon as you can. And make it an error, not just an 'I don't know' case: you should never allow an object to get into an invalid state.

public class Product {
  private String productName;

  public Product(String productName) {
    setProductName(productName); // for validation
  }

  public String getProductName() {
    return this.productName;
  }

  public void setProductName(String productName) {
    if (productName == null || productName.length() == 0)
        throw new IllegalArgumentException("product name cannot be null or empty");
    this.productname = productName;
  }

Upvotes: 3

Related Questions