DEV Community

Md Faiz
Md Faiz

Posted on

Why Encapsulation Matters: Writing Defensive Code in Core Java

When learning Object-Oriented Programming, many developers think encapsulation is just about making variables private and generating getters and setters.

In reality, encapsulation is about defensive coding and data protection.

  1. The Problem with Blind Setters:
    If a BankAccount class has a simple setter like setBalance(double balance), anyone can pass a negative value like -5000. This corrupts the data because the class did not validate the input.

  2. Using Domain Logic Instead:
    A better approach is to remove generic setters and use specific business methods like deposit(double amount) and withdraw(double amount). These methods check if the amount is positive and verify that the account has enough balance before updating.

  3. Key Rules for Good Design:

  4. Avoid generic setters that directly expose private fields.

  5. Make the object responsible for validating its own data.

  6. Only provide getters when external code truly needs to read the value.

Currently diving deeper into Core Java and backend architecture as part of my full-stack learning journey.

Top comments (0)