Wednesday, February 8, 2017

Why should we use getters and setters in POJOs?

There are quite a few reasons to use getters and setters in POJO.

Let's first take a look at a simple POJO and then we will discuss the uses of getter and setter:



package com.prinavtech.types;

public class Employee {

    private String firstName;
    private String middleName;
    private String lastName;

    public String getFirstName() {
      return firstName;
    }
    public void setFirstName(String firstName) {
       this.firstName = firstName;
    }
    public String getMiddleName() {
        return middleName;
    }
    public void setMiddleName(String middleName) {
         this.middleName = middleName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFullName(){
        return this.getFirstName() + this.getMiddleName() +  this.getLastName();
    }
 }

Getters and Setters are primarily used for two main purposes of Object Oriented Programming:

1. Abstraction
2. Encapsulation

The advantages of using these are:

1. You can restrict the accessibility of an attribute by using access modifiers.
   Eg: We can make FirstName readable only by making the getter private

2. Can validate a field directly inside a pojo.
Eg: we can make sure that the age of a Person can be between 0<100.

3. The above two points are in support of Encapsulation and Abstraction.

4. In Java if you declare the variables as instance variables, it will make your code slower. Run a test and you will see that accessing and setting variables via setters and getters are faster than setting them directly as instance variables.

For more read this stackoverflow post.


No comments:

Post a Comment