Search code examples
javaoopgetter-setter

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";
    }
 }
}

Solution

  • 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;
      }