开发者

Example of getters setters as a bad choice in Java

开发者 https://www.devze.com 2023-02-12 07:24 出处:网络
Could somebody please provide an example where getters and setters are not required? I still do not get the idea, I guess a very huge class with lot开发者_开发问答s of attributes must have them but i

Could somebody please provide an example where getters and setters are not required?

I still do not get the idea, I guess a very huge class with lot开发者_开发问答s of attributes must have them but in simpler cases?


I'm sorry, I really really don't agree with @Stephen C...

First of all, fields should ALWAYS be private (except for constants).

Secondly, Setters and Getters are very different. Getters can be used fairly freely, taking into consideration @MeBigFatGuy 's comments (with which I completely agree). In general though, there is usually not too much damage caused by viewing the value of a variable. As for setters - you should (almost) never use them. I am not alone in this, as you can see in Joshua Bloch's Effective Java 2nd Edition page 79 (under Minimize Mutability chapter) :

"...resist the urge to write a set method for every get method. Classes should be immutable unless there's a very good reason to make them mutable."

Setters are evil incarnate, they create a code maintenance nightmare from the second they are introduced. Everyone on the dev team will now start manipulating the data, creating horrible bugs that are very very difficult to fix. Field values should (almost) always be set at creation time and remain the same for the entire instance life cycle! The only real exceptions to this rule that I can think of are JavaBeans and TagHandlers, but those are very specific examples.

In summary - make all your fields private, populate them at creation time and never change them again. This will make your life (and that of every developer around you) much much easier.


Getters and setters have a number of related purposes:

  • They abstract the state of the class. Generally speaking, it is a good thing to hide implementation details.
  • They make it easier for the implementor to change the attribute's representation type.
  • They make it possible to override aspects in child classes. (An exposed attribute cannot be overridden.)
  • They allow the class to control access and update. For example, a setter can stop some client code from setting an attribute to a "wrong" value.
  • They allow a class to be used as a Java Bean.

All of these add up to a convincing argument for using setters and getters everywhere.

To my mind, there is only two cases where getters and setters are "optional":

  • When the attributes are only ever used by the class itself; i.e. they are private.
  • When the attributes belong to a light-weight private inner class; i.e a class whose instances will only ever exist and be visible within the encapsulation boundary of the outer class.

In these cases, the reasons for using getter and setters mostly don't apply. In particular, since the visibility of the attributes and their types are restricted to the enclosing class, the ripple effect of changing them is limited to the source code file that defines the class.

However, if there is a risk that the inner classes implementation details will leak in a revision of the code, you should immediately add getters and setters.


Let's assume you are writing a program that is modeling an auto repair garage. You need a class that represents an automobile. Further this garage wants to know whether or not the car needs an oil change. you might add getters for

public int getMiles()
     and
public Date getLastOilChange() 

-- this seems fine two getters that allow a calling program to get information about the car. Now the garage class can call these methods to figure out whether the car needs an oil change.

But this is wrong. The garage does not need or want to know anything about these two pieces of information. All the garage class needs to know about is

public boolean needsOilChange()

And so you are exposing implementation details that the garage doesn't need to know about.

Perhaps a type of car in the future doesn't use this information to determine whether an oil change is needed, maybe some other mechanism is used. The garage class would have to be rewritten if it used the two methods above. On the other hand, if it used the needsOilChange() method it wouldn't have to.


I mean if you have variables that you just know will not need to be accessed in a particular way, don't bother with the getter/setter. If you have a variable that is never going to be altered via a get, don't include it. Only use what you need to get the job done.


An example of when getters/setters are not required? How about a servlet for example or any class that is not a simple java bean? If you are creating a web application for example you might have a bunch of very simple java bean classes like "Customer" that do have getters and setters (those are your "model" classes that model the business domain entities) -- but then you'd have many more classes like servlets and dao classes and other services with business logic where it wouldn't make sense to have getters/setters.


For example if they're only accessed internally than you shouldn't need getters/setters. Or, if you want to break a coding taboo, you could set stuff to public...though you're not suppose to out of tradition and security.


Imagine you are making a chess game and it has a set of pieces and boards. You do not want to make it possible for a player to just get and set pieces. It would make no sense and break your game. In this example you also wouldn't want players to be able to just set the locations of pieces or else they would make illegal moves. You want to have a move method that checks to see whether a move is legal before just getting and setting the positions.

Another classic example: A Bank Account. You don't want to let people just get and set their balance, you want to provide deposit and withdraw methods which will do things like check to see whether the balance is going to go negative, or possibly log the transactions as well.


Where ever you dont want the api user to read or write values to the variables. Many occasions you might just want the user to view the values, meaning setting to read only then you provide them with get method alone.The bank details you dont want anyone to accidentally modify the information.So dont provide them with setter methods.


Getters and setters are required if the class in question is non-trivial or to be extended.

For classes to be used as simple states, where changing the property directly is unlikely to directly incur additional changes to other parts of the class or context in which it is used, there is little point in having getters and setters when just a simple property will suffice.

Good examples from the Java libraries are Rectangle, Dimension, and Insets.

Dimension does have getters and setters for convenience, but the properties (width, height) are still public.

0

精彩评论

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

关注公众号