Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why declare variables private in a class? [closed]

Folks I'll start by apologising as I'm sure this has been answered elsewhere - I just can't find an answer that explains it in a way I understand! I'm doing an MSc conversion course and there are some elementary basics that I'm still struggling with this, including this one - why making a variable private is better.

Say I have a Java class called Person, with a print method. I could create it and define it as such:

public class Person
{
    public String name;
    public String telephoneNumber;

    public void print()
    {
       System.out.println(name + " " + telephoneNumber);
    }
}

Then, in a main class, I could write the following code:

class testPerson
{
  public static void main(String[] args)
  {
    Person test;
    test = new Person();

    test.name = "Mary";
    test.telephoneNumber = "01234 567890";

    test.print();
  }
}

If I did this, the test.print(); would produce the output:

mary 01234 567890

However, I know this is considered poor coding. Variables should be private inside a public class, as we don't want to allow people to see how this information is stored or to be able to edit information without authorisation.

So now, I'll edit the Person class to declare the two Strings private and add get and set methods, like so:

private String name;
private String telephoneNumber;

public void setName (String name)
{
  this.name = name;
}

public void getName()
{
  return name;
}

// same code for telephone methods.

Now, in the main class, I would change the methods of setting name and telephone to the following:

mary.setName("Mary");
mary.settelephoneNumber("01234 567890");

According to the lecture notes I'm following, this is more efficient (although could be made even more efficient by adding in a Person() method to allow for instantiation etc.)

However, I'm struggling to see why this is better.
In the former method of doing things, the user could directly access the variables. But even though by hiding the variables they can't directly access them, the user can indirectly access and modify them which produces the exact same outcome.

Why is it that this is preferred and what no doubt silly thing am I missing/overlooking?

like image 610
Andrew Martin Avatar asked Feb 04 '13 20:02

Andrew Martin


People also ask

Why is it important for instance variables to be private?

Instance variables are made private to force the users of those class to use methods to access them. In most cases there are plain getters and setters but other methods might be used as well.

Should variables always be private?

There is no hard rule as to what should be private/public or protected. It depends on the role of your class and what it offers. All the methods and members that constitute the internal workings of the class should be made private. Everything that a class offers to the outside world should be public.

Why are properties marked as public while backing variables are marked as private?

In an ideal programming scenario, properties are declared public as they are exposed outside. Fields on the other hand are private as they should not be exposed because we do not have control over them when their value changes.


2 Answers

People will give you a million regurgitated reasons why it is better, but it is only better in some cases, not in all of them unequivocally. For example, take Java's own class GridBagConstraintsit has no methods at all (if you don't count clone, which it has anyway; all Java classes inherit it from Object). Why? Because there's a case where this is in fact more practical. And GridBagConstraints is a Java Bean in the purest sense: it's all about properties, no business logic there.

Let me report on another fact from practice: no setter ever validates its input; no getter ever calculates its result. In the world of JavaBeans, any such behavior will soon get in the way of the universal assumption that setters set, and getters get. Basically, if you diverge in any way from the exact equivalent of public fields, you lose.

The modern Java APIs, like Hibernate, acknowledge this fact by accepting naked public fields on an equal footing with JavaBean-style properties. Earlier versions didn't allow that, but as experience with Java accrues, the realization is finally dawning that public fields are OK.

like image 105
Marko Topolnik Avatar answered Nov 10 '22 15:11

Marko Topolnik


Pizza Delivery Analogy

  1. You order a Pizza for delivery.
  2. Pizza boy knocks the door and expects you to pay for it.
  3. You take out the money from your purse and hand it over to the delivery boy. (You are in control of hiding the internal details (drivers license etc.)) Alternatively,
    • You could hand over the purse to the delivery boy and ask him to take the money from it. By doing this you are no longer in control. You are exposing internal details.

Read about Information Hiding and Encapsulation is not information hiding.

like image 35
Aravind Yarram Avatar answered Nov 10 '22 15:11

Aravind Yarram