开发者

When to use get/set Methods in java [duplicate]

开发者 https://www.devze.com 2023-01-25 03:47 出处:网络
This question already has answers here: 开发者_如何学PythonWhy use getters and setters/accessors?
This question already has answers here: 开发者_如何学Python Why use getters and setters/accessors? (37 answers) Closed 6 years ago.

I want to know when to use get and set methods(getName,setName ) in my class and when simple classVariable.name = "" instead а = classVariable.getName()

Here is example of class using set and get methods

public class ClassExampe {

    String name;
    String course;

    public String getName ( )
    {
        return name;
    }

    public void setName (String studentName)
    {
        name = studentName;           
    }

    public String getCourse ( )
    {
        return course;
    }

    public void setCourse (String studentCourse)
    {
        course = studentCourse;
    }
}

Thanks


Using Getters / Setters vs using Fields

As a rule of thumb:

use the variables directly from the same class (actually from the same .java file, so inner classes are ok too), use Getters / Setters from other classes.


The simple rule is: never use direct access (except, of course, when referring to them from inside the class).

  • field access can't be proxied
  • you may want to have some event notification
  • you may want to guard against race conditions
  • expression languages support setters and getters
  • theoretically this breaks encapsulation. (If we are pedantic, setter and getter for all fields also breaks encapsulation though)
  • you may want to perform some extra logic inside the setter or getter, but that is rarely advisable, since consumers expect this to follow the convention - i.e. being a simple getter/setter.
  • you can specify only a setter or only a getter, thus achieving read-only, or write-only access.

Even if this does not happen that you need any of these, it is not unlikely. And if you start with field access, it will be harder to change.


In Java, using a getter and setter is usually considered best practice.

This is because if you ever need to change your code to do something else when a property is accessed or modified, you can just change it in the existing getter or setter.

I tend to think it causes a bit of clutter for simple objects, but if you have ever had to refactor a public property to a getter and setter to add additional functionality you will see that it can be a pain.


I suspect most will say to always use getters/setters to access private members. It's not necessary, but is considered a "best practice".

One advantage is that you can have more than just simple assignment and returning. Example:

public void setLevel(int lvl)
{
    if (lvl<0)
    {
        this.level=1;
    }
    else
        this.level = lvl;
}

public int getLevel()
{
    if (this.someIndicator==4)
        return this.level*7.1;
    else
        return level;
}


Getters and Setters allow you to change the implementation later (e.g. do something more complex), allow you to implement validation rules (e.g. setName throws an exception if the name is not more than 5 characters, whatever.)

You could also choose to add a getter but not a setter so that the variable is like 'read-only'.

That's the theory, however in many cases (e.g. Hibernate using setters) you cannot throw exceptions in setters so you can't do any validation. Normally the value will just be assigned/returned. In some companies I've worked at, it's been mandatory to write getters and setters for all attributes.

In that case, if you want to access an attribute from outside an object, and you want it to be readable/writable, I just use a public attribute. It's less code, and it means you can write things like obj.var += 5 which is easier to read than obj.setVar(obj.getVar() + 5).


If you mean: when to use public accessor methods instead of making the internal, private variable public my answer is "always" unless there is a severe performance reason.

If you mean, call your own get and set methods vs direct access to the vars w/in your class I still say call your own access methods. This way, any conversion, edits or rules you implement as part of get/set get invoked automatically by your own internal calls as well as external callers.

In pure OO languages (for example, Smalltalk) there is no concept of public - all internal vars are private and so you must use accessors. In less pure OO languages, you can make things public - however exposing the internals of your data structures and implementation is an exceptionally bad idea for stability and maintenance in the long run. Look up "tight coupling" for more on this.

Simply put, if you expose internal vars publicly, people can access them directly and if you ever change name or type everything down the line breaks. This is called side effects.


Its a matter of taste, but generally speaking you always should use get/set methods for all properties that are public. But for things like Value Objects (VOs) that you probably are not going to be bothered with for some time you can use public variables without getting too much criticism I think.


In general, you'd want to use setters and getters to give the opportunity to developers reusing your code by modifying it or extending it to add layers of processing and control when accessing and modifying your internal data. This wouldn't be possible in Java when using direct accesses.

Parenthesis: However, it's perfectly possible in other languages, for instance in Scala, when the line between properties and methods can become quite fine. And it's great, as then it doesn't become a coding-problem that gets in the way and it makes usage more transparent.


You can also often consider that in your class you can feel free to access your internal (private or protected) members directly, as you're supposed to know what you're doing, and you don't need to incur the overhead of yet another method call.

In practice, multiple people working on a class might not know what everyone's doing and those lines of integrity checking in your getters and setters might be useful in most cases, while the micro-optimization may not.


Moreover, there's only one way for you to access a variable directly, whereas you can define as many accessors as you want.


Encapsulate the private fields of a class and expose them with getter/setter classes the way you want to.

0

精彩评论

暂无评论...
验证码 换一张
取 消