3

I just want to ask, we are having one class, in which we have two private data members say:

class Employee{ private int empid; private String empname; } 

I am declaring them private that means I can use them in Employee class only. So what is the need to create getter setter for both the data members and making them public.

Hope you got my problem.

2 Answers 2

4

This is an excellent question. Often you see code examples that make members private but exposing them via a getter/setter pair, without the getter/setter doing anything else than setting the corresponding member.

In my book this is not encapsulation at all. You are no better of than just making the members public. Although a lot of people are uneasy to do that, they would happily provide accessors automatically for all their members.

One reason to do provide accessors is the ability to do input validation. E.g. if you empIds have a checksum, you could enforce it in the setter. Something that is not possible with direct access to the member.

In my opinion it would be better to think about the role this object will play and see how it can achieve that role with a minimum of accessors. Otherwise your code will probably violate the Law of Demeter.

Sign up to request clarification or add additional context in comments.

Comments

1

You are absolutely right, that creating a setter/getter or making the fields public both violate encapsulation in the same way, therefore if you do want to encapsulate your private fields, presumably because you are working in an Object-Oriented environment, you do not want to use either of those things.

To your question why there is a need to have create setter/getters: Most projects (consciously or unconsciously) do not base their designs on Object-Orientation. There are other paradigms, where data and function are separated, thus encapsulation plays a minor role if any.

In the Java world it is common to have pure (or very close to pure) data structures (Beans), and Services/Components/EJBs/etc that work on these Beans (have access to all fields basically). Often these architectures split the function part further into topics like Presentation, Business, Persistence (3-tier architectures), or create explicit control procedures that has access to all the relevant fields (like how MVC is often done).

Whether one approach is better than the other would be a subjective discussion probably, but the short answer is: It's a different paradigm usually (not OO), that is why setters/getters get created.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.