2 min read

Object Oriented Design (series) - Encapsulation

Object Oriented Design (series) - Encapsulation
You can look but you can't touch! πŸ₯΅

Intro

This one is about exposing to the client only the info you want and in the format you want.

Most descriptions of this concept go around the lines of "add getters and setters on your fields".

❓ But why would that make a difference for the good?

What is the difference between this class with public fields

public class Book {
    public String author;
    public String title;
    public Date releaseDate;
    public Integer rentalsNo;
}
Book.java

and the same class with getters and setters?

public class Book {
    public String author;
    public String title;
    public Date releaseDate;
    public Integer rentalsNo;

    public String getAuthor() {
        return this.author;
    }
    
    public void setAuthor(String author) {
        this.author = author;
    }

    public String getTitle() {
        return this.title;
    }
    
    public void setTitle(String title) {
    	this.title = title;
    }

    public Date getReleaseDate() {
        return this.releaseDate;
    }
    
    public void setReleaseDate(Date releaseDate) {
        this.releaseDate = releaseDate;
    }

    public Integer getRentalsNo() {
        return this.rentalsNo;
    }

    public void setRentalsNo(Integer rentalsNo) {
        this.rentalsNo = rentalsNo;
    }
}

❗️ Absolutely none! More so, you have a lot more code written that doesn't really bring in any value.

Your client is still able to access and modify all of the book's inner properties, either if it's directly through the properties, either through a method.

There is a catch, though! πŸ˜‰

This post is for subscribers only