Vikas Rajput
Vikas Rajput

@vikasrajputin

13 تغريدة 1 قراءة Dec 06, 2022
More than 97% of candidates fail to answer this question in a Java interview
What's the logic of using public getter/setter methods to access private fields in Java POJO?
Can't we remove getter/setter methods by making fields public?
Here's the best way to answer this:🧵👇
1. Understand the Trick Behind
- There's no logic(from a security point of view) in accessing private fields via the public getter/setter method
- Here, the interview wants to know the significance of using the getter and setter method in a Java POJO Class
2. Use this Example
- A POJO Class called Account, with two fields:
1) accountName (to show name)
2) accountBalance (to show the remaining balance in the account)
- As usual, both fields are private & the public getter and setter method are being defined to access them
Eg:
3. Why not remove getters & setters and make the field private?
- If we do this, then we will lose control over who reads or writes our field
- In such cases, anyone can do anything which can lead to unavoidable bugs
- By having the getters & setters, we will have a single door to access our fields
- Hence we can write any important business logic inside it to avoid unnecessary access, updates to our field
- Let's see various use cases of using getter/setter methods
4. Validation Logic
- Write validation logic inside the setter method to prevent it from having invalid data
Eg:
5. Security Logic
- You can also add any security-related code (inside the getter and setter) to secure the data
- For eg:
Check if a user has access to the field based on any complex security logic and then allow the user to either read or update the value
6. ReadOnly or WriteOnly Fields
- To allow only write permission, we can only keep setter methods
- To allow only read permission to fields, we can remove the setter method and only keep the getter method as shown below
Eg:
7. Create an Immutable Class
- By only keeping the getter method we can also create an Immutability class if required
- In getter methods, we can return a new copy instead of returning the original object to protect it from getting modified
8. Final Conclusion
- In all the above cases, we've encapsulated the fields in a POJO at different levels
- This is why many times while explaining encapsulation in Java we use POJO and getters/setter method examples
That's a wrap!
Every Mon, Wed & Friday - I tweet a thread on Java & Backend Development.
Follow me
@vikasrajputin
to read all my future threads.
Before you go, do you know?
I've already started writing on LinkedIn
I share some exclusive content there, which I never share here.
Follow me on Linkedin to stay updated with Backend content:
linkedin.com
Correction***
Title of 3rd point should be:
3. Why not remove getters & setters and make the field public?

جاري تحميل الاقتراحات...