Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

private String or public static String?

At my internship one of my colleagues gave me a hint. I want to know if this is good practice.

What I was doing was creating classes that are used only for the values they contain and don't have any functions that actually do something (apart from having getters, setters and a constructor). I declared my variables like this:

public class ObjectIUse{
  Private String name;

  public ObjectIUse(String name){
    this.name = name;
  }

  public String getName(){
    return name;
  }
}

So I'm not using a setter because it should always stay the same. My colleague said that I can also do it this way:

public class ObjectIUse{
  public final String name;

  public ObjectIUse(String name){
    this.name = name;
  }
}

Because now we don't need to have any getters or setters because it is public, however it can also never be changed because it is final.

Which would be better? Or would it maybe be preferable to still make it private but also final? I mean all of the options work, obviously. I just want to know which is better and why.

like image 892
WereWolfBoy Avatar asked Mar 28 '13 12:03

WereWolfBoy


2 Answers

Make the variable private, because by doing so you'll be encapsulating the variable in your class. This has many benefits, information hiding is among one, which you'll learn if you go to the above link.

If you want it to never change after creation, then make it final too.

like image 124
MD Sayem Ahmed Avatar answered Sep 29 '22 01:09

MD Sayem Ahmed


This works now because a String is immutable. But what happens when you expose the reference to a mutable class and that class is not thread safe ?. You cant even return a defensive copy if you want to.

Not to mention this also breaks encapsulation. Use a private variable and getters.

like image 29
Deepak Bala Avatar answered Sep 29 '22 01:09

Deepak Bala