How to avoid getters and setters - oop

I have read in many places that "getters and setters are evil". And I understood why so. But I don't know how to avoid them completely. Say Item is a class that has information about item name, qty, price etc...
and ItemList is a class, which has a list of Items. To find the grand total:
int grandTotal()
{
int total = 0;
for (Item item: itemList)
total += item.getPrice();
return total;
}
In the above case, how does one avoid getPrice()? The Item class provides getName, setName, etc....
How do I avoid them?

When should you use getters and setters?
Getters and setters are great for configuring or determining the configuration of a class, or retrieving data from a model
Getting the price of an item is an entirely reasonable use of a getter. That is data that needs to be available and may involve special considerations to protect the data by adding validation or sanitization to the setter.
You can also provide getters without setters. They do not have to come in pairs.
When shouldn't you use getters and setters?
Sometimes objects rely on internal properties that will never be exposed. For example, Iterators and internal collections. Exposing the internal collection could have dramatically negative and unexpected consequences.
Also, for example, let's say you are communicating via some HttpURLConnection. Exposing the setter for your HttpURLConnection means that you could end up with a very odd state should the connection be changed while waiting to receive data. This connection is something that should be created on instantiation or entirely managed internally.
Summary
If you have data that is for all intents and purposes public, but needs to be managed: use getters and setters.
If you have data that needs to be retrieved but under no circumstances should ever be changed: use a getter but not a setter.
If you have data that needs to be set for internal purposes and should never be publicly exposed (and cannot be set at instantiation): use a setter but not a getter (setter presumably prevents a second call affecting the internal property)
If you have something that is entirely internal and no other class needs to access it or change it directly, then use neither.
Don't forget that setters and getters can be private and even for internally managed properties, having a setter that manages the property may be desirable. For example, taking a connection string and passing it to the setter for HttpURLConnection.
Also note:
Allen Holub's article Why getter and setter methods are evil seems to be the source of OP's reasoning but, in my opinion, the article does a poor job of explaining its point.
Edit: Added summary
Edit 2: spelling corrections

It's a shame to see a small, vocal minority take a back lash against the whole "Getters and Setters" are evil debate. Firstly the article title is purposely provocative to draw you in, as should any blog post. I've in turn blogged about this before and several years later updated my opinions and ideas about this question. I'll summarise the best I can here.
Getters and setters (accessors) are not evil
They are "evil" (unnecessary) most of the time however
Encapsulation is not just adding accessors around private fields to control change, after all there is no benefit to added get/set methods that just modify a private field
You should write as much code as possible with the principle of "Tell, Don't Ask"
You need to use accessors for framework code, DTOs, serialisation and so forth. Don't try to fight this.
You want your core domain logic (business objects) to be as property free as possible however. You should tell objects to do stuff, not check their internal state at will.
If you have a load of accessors you essentially violate encapsulation. For example:
class Employee
{
public decimal Salary { get; set; }
// Methods with behaviour...
}
This is a crap domain object, because I can do this:
me.Salary = 100000000.00;
This may be a simple example, but as anyone who works in a professional environment can attest to, if there is some code that is public people will make use of it. It would not be wrong for a developer to see this and start adding loads of checks around the codebase using the Salary to decide what do with the Employee.
A better object would be:
class Employee
{
private decimal salary;
public void GivePayRise()
{
// Should this employee get a pay rise.
// Apply business logic - get value etc...
// Give raise
}
// More methods with behaviour
}
Now we cannot rely on Salary being public knowledge. Anyone wanting to give a pay rise to employees must do this via this method. This is great because the business logic for this is contained in one place. We can change this one place and effect everywhere the Employee is used.

The following sample is a brilliant example of boilerplate setters and getters.
class Item{
private double price;
public void setPrice(final double price){
this.price = price;
}
public double getPrice(){
return this.price;
}
}
Some coders think that this is called encapsulation, but in fact this code is exact equivalent of
class Item{
public double price;
}
In both classes price is not protected or encapsulated, but the second class reads easier.
class Item{
private double price;
public void setPrice(final double price){
if(isValidPrice(price))
this.price = price;
else throw new IllegalArgumentException(price+" is not valid!");
}
public double getPrice(){
return this.price;
}
}
This is a real encapsulation, the invariant of the class is guarded by the setPrice. My advice - don't write dummy getters and setters, use getters and setters only if they guard the invariant of your class

I have read in many places that "getters and setters are evil".
Really? That sounds crazy to me. Many? Show us one. We'll tear it to shreds.
And I understood why so.
I don't. It seems crazy to me. Either your misunderstood but think you did understand, or the original source is just crazy.
But I don't know how to avoid them completely.
You shouldn't.
how to avoid getPrice?
See, why would you want to avoid that? How else are you suppose to get data out of your objects?
how to avoid them???
Don't. Stop reading crazy talk.

When someone tells you that getters and setters are evil, think about why they are saying that.
Getters
Are they evil? There is no such thing as evil in code. Code is code and is neither good nor bad. It's just a matter of how hard it is to read and debug.
In your case, I think it is perfectly fine to use a getter to calculate the final price.
The "evil"
Usecase: you think you want the price of an item when buying something.
People sometimes use getters like this:
if(item.getPrice() <= my_balance) {
myBank.buyItem(item);
}
There is nothing wrong with this code, but it isn't as straight-forward as it could be. Look at this (more pragmatic approach):
myBank.buyItem(item); //throws NotEnoughBalanceException
It's not the buyers or the cashiers job to check the price of an item when buying something. It's the actually the bank's job. Imagine that customer A has a SimpleBank.java
public class SimpleBank implements Transaction {
public void buyItem(Item item){
if(getCustomer().getBalance() >= item.getPrice()){
transactionId = doTransaction(item.getPrice());
sendTransactionOK(transactionId);
}
}
}
The first approach seems fine here. But what if customer B has a NewAndImprovedBank.java?
public class NewAndImprovedBank implements Transaction {
public void buyItem(Item item){
int difference = getCustomer().getBalance() - item.getPrice();
if (difference >= 0) {
transactionId = doTransaction(item.getPrice());
sendTransactionOK(transactionId);
} else if (difference <= getCustomer().getCreditLimit()){
transactionId = doTransactionWithCredit(item.getPrice());
sendTransactionOK(transactionId);
}
}
}
You might think that you are being defensive when using the first approach, but actually you are limiting the capabilities of your system.
Conclusion
Don't ask for permission aka item.getPrice() , ask for forgiveness aka NotEnoughBalanceException instead.

getPrice() is accessing a private variable I'm assuming.
To answer your question directly, make the price variable public, and code something like (syntax may differ depending on language, use of pointers etc):
total += item.price;
However this is generally considered bad style. Class variables should generally remain private.
Please see my comment on the question.

How to avoid getters and setters? Design classes that actually act upon the data they hold.
Getters lie about the data anyway. In the Item.getPrice() example, I can see I'm getting an int. But is the price in dollars or cents? Does it include tax(es)? What if I want to know the price in a different country or state, can I still use getPrice()?
Yes, this might be beyond the scope of what the system is designed to do, and yes, you might just end up returning a variable's value from your method, but advertising that implementation detail by using a getter weakens your API.

'Evil' as .getAttention()
This has been discussed often, and even perhaps went a bit viral, as a result of the pejorative term "Evil" used in the dialog. There are times when you need them, of course. But the problem is using them correctly. You see, Professor Holub's rant isn't about what your code is doing now, but about boxing yourself in so that change in the future is painful and error prone.
In fact, all I have read by him carries this as its theme.
How does that theme apply to the class Item?
A look at the future of Item
Here is fictions's item class:
class Item{
private double price;
public void setPrice(final double price){
if(isValidPrice(price))
this.price = price;
else throw new IllegalArgumentException(price+" is not valid!");
}
public double getPrice(){
return this.price;
}
}
This is all well and good- but it is still 'Evil' in the sense that it could cause you a lot of grief in the future.
The grief is apt to come from the fact that one day 'price' may have to take different currencies into account (and perhaps even more complex barter schemes). By setting price to be a double, any code that is written between now and the 'apocalypse' (we're talking evil, after all) will be wiring price to a double.
It is much better (even Good, perhaps) to pass in a Price object instead of a double. By doing so you can easily implement changes to what you mean by 'price' without breaking the existing interfaces.
The takeaway on getters and setters
If you find yourself using getters and setters on simple types, make sure you consider possible future changes to the interface. There is a very good chance you shouldn't be. Are you using setName(String name)? You should consider setName(IdentityObject id) or even setIdentity(IdentityObject id) in case other identification models show up (avatars, keys, whatever). Sure you can always go around and setAvatar and setKey on everything, but by using an object in your method signature you make it easier to extend in the future to the objects that can use the new identity properties and not break the legacy objects.

A different perspective that is missing here so far: getters and setters invite to violate the Tell Don't Ask principle!
Imagine you go shopping in the supermarket. In the end, the cashier wants money from you. The getter/setter approach is: you hand over your purse to the cashier, the cashier counts the money in your purse, takes the money you owe, and gives back the purse.
Is that how you do things in reality? Not at all. In the real world, you typically don't care about the internal state of "autonomous" other "objects". The cashier tells you: "your bill is 5,85 USD". Then you pay. How you do that is up to you, the only thing the cashier wants/needs is he receives that amount of money from your side.
Thus: you avoid getters and setters by thinking in terms of behavior, not in terms of state. Getters/setters manipulate state, from the "outside" (by doing avail = purse.getAvailableMoney() and purse.setAvailableMoney(avail - 5.85). Instead, you want to call person.makePayment(5.85).

How to avoid getters and setters in Java?
Use Project Lombok

Cloudanger answer is is one, but you must also realize that the item list will likely contain many item objects with quantity ordered on it.
Solution : create another class in between them that stores your item in the item list and the qty ordered for that item (Let's say the class is called OrderLine).
OrderLine will have Item and qty as fields.
After that, code something like calculateTotal(int qty) in Item which return price*qty.
Create a method in OrderLine that call calculateTotal(qtyOrdered)
Pass the return value to the itemList.
This way, you avoid getters.
The ItemList will only know the total price.
Your code should live with your data.
Ask the Object who has the data to calculate the totalPrice instead of asking that object for raw data to calculate your totalPrice.

Really?
I don't think that. on the contrary the getters and setters help you to protect the consistense of the variables.
The importance of getters and setters is to provide protection to private attributes so that they can not be accessed directly for this it is best that you create a class with the attribute item in which you include the corresponding get and set.

Use a helper class ShoppingCart. Item's method item.addTo(ShoppingCart cart) would add the price to the totalSum of the cart using shoppingCart.addItem(Item item, int price)
Dependency from Item to ShoppingCart isn't disadvantageous if the Items are meant to be items of ShoppingCarts.
In the case where Items live solely for the ShoppingCart and the Item class is small, I would more likely have the Item as an inner class of the ShoppingCart, so that the ShoppingCart would have access to the private variables of the items.
Other thoughts
It would also be possible, although quite unintuitive design, to have the Item class count the sum (item.calculateSum(List<Item> items)), since it can access the private parts of other items without breaking encapsulation.
To others wondering why the getters are bad. Consider the given example where the getPrice() returns integer. If you would want to change that to something better like BigDecimal at least or a custom money type with currency, then it wouldn't be possible since the return type int exposes the internal type.

Getters and setters are evil because they break encapsulation and can unnecessarily expose an objects internal state and allow it to be modified in way it should not be. The following article elaborates on this problem:
http://programmer.97things.oreilly.com/wiki/index.php/Encapsulate_Behavior,_not_Just_State

You can avoid getter and setter at places by using _classname__attributename because that's the changed new name once you declare private to any attribute.
So if Item is the class with a private attribute declared as __price
then instead of item.getPrice() you can write _Item__price.
It will work fine.

Related

Is public variable all that bad?

I've read a lot of articles about "public vs getter/setter", but I still wonder if there is any good part about public variable.
Or the question is:
If you're going to make a new awesome programming languange, are you still going to support public variable and why??
I agree with almost everything that's been said by everyone else, but wanted to add this:
Public isn't automatically bad. Public is bad if you're writing an Object Class. Data Classes are just fine. There's nothing wrong with this class:
public class CommentRecord
{
public int id;
public string comment;
}
... why? Because the class isn't using the variables for anything. It's just a data object - it's meant to be just a simple data repository.
But there's absolutely something wrong with this class:
public class CommentRecord
{
public int id;
public string comment;
public void UpdateInSQL()
{
// code to update the SQL table for the row with commentID = this.id
// and set its UserComment column to this.comment
}
}
... why is this bad? Because it's not a data class. It's a class that actually does stuff with its variables - and because of that, making them public forces the person using the class to know the internals of the class. The person using it needs to know "If I want to update the comment, I have to change the public variable, but not change the id, then call the UpdateInSQL() method." Worse, if they screw up, they use the class in a way it wasn't intended and in a way that'll cause unforseen consequences down the line!
If you want to get some more info on this, take a look at Clean Code by Robert Martin, Chapter 6, on "Data/Object Anti-Symmetry"
A public variable essentially means you have a global accessible/changeable variable within the scope of an object. Is there really a use case for this?
Take this example: you have a class DatabaseQueryHandler which has a variable databaseAccessor. Under what circumstances would you want this variable to be:
Publicly accessible (i.e. gettable)
Publicly settable
Option #1 I can think of a few - you may want to get the last insert ID after an insert operation, you may want to check any errors the last query generated, commit or rollback transactions, etc., and it might make more logical sense to have these methods written in the class DatabaseAccessor than DatabaseQueryHandler.
Option #2 is less desirable, especially if you are doing OOP and abiding by SOLID principles, in particular regards to the ISP and DIP principles. In that case, when would you want to set the variable databaseAccessor in DatabaseQueryHandler? Probably on construction only, and never at any time after that. You probably also want it type-hinted at the interface level as well, so that you can code to interfaces. Also, why would you need an arbitrary object to be able to alter the database accessor? What happens if Foo changes the variable DatabaseQueryHandler->databaseAccessor to be NULL and then Bar tries to call DatabaseQueryHandler->databaseAccessor->beginTransaction()?
I'm just giving one example here, and it is by no means bullet proof. I program in PHP (dodges the hurled rotten fruit) and take OOP and SOLID very seriously given the looseness of the language. I'm sure there will be arguments on both sides of the fence, but I would say that if you're considering using a public class variable, instead consider what actually needs to access it, and how that variable is to be used. In most cases the functionality can be exposed via public methods without allowing unexpected alteration of the variable type.
Simple answer is: yes, they are bad. There are many reasons to that like coupling and unmaintanable code. In practice you should not use them. In OOP the public variable alternative is Singleton, which is considered a bad pracitce. Check out here.
It has a lot to do with encapsulation. You don't want your variable to be accessed anyhow. Other languages like iOS (objective-c) use properties:
#property (nonatomic, strong) NSArray* array;
then the compiler will generate the instance variable with it's getter and setter implicitly. In this case there is no need to use a variable (though other developers still prefer to use variables). You can then make this property public by declaring it in the .h file or private by declaring it in the .m file.

When is it considered good design to directly set property values on an object without the use of a setter?

This may not be the best kind of question suited to stackoverflow, but I'm only after an answer that best describes why programmers sometimes don't use setters/getters for properties, e.g. in the case of property injection (DI).
Consider this example...
class Test
{
public propertyA;
protected propertyB;
public function setPropertyB(val)
{
// do some logic to validate 'val'
this.propertyB = val;
}
public function getPropertyB()
{
return this.propertyB;
}
}
Why would you choose the style of directly setting propertyA:
var Test = new Test();
Test.propertyA = 1;
Over the setter option for propertyB:
var Test = new Test();
Test.setPropertyB(1);
I always use the setter/getter approach, but I have seen some pretty established frameworks using the propertyA approach interspersed with the propertyB approach. What benefits do we have using this method?
Why you might not care about encapsulation:
You might be throwing away the project 15 minutes later.
You might have found getters/setters to be bottlenecks for your CPU-bound code, causing you to optimize for performance instead of design.
The instance field might be immutable and read-only, so there might be no danger in exposing it.
You're too lazy to write getters/setters.
You should use getters and setters because they allow you to control the interface to your objects.
For example, let's say I have a bank account class in a Java application:
class BankAccount {
private int balance;
BankAccount() {
balance = 0;
}
public void deposit(int amount) {
balance = balance + amount;
}
public void withdraw(int amount) {
balance = balance - amount;
}
}
When my software needs to alter a bank account's balance through deposits and withdrawals, it calls the appropriate methods.
Now, along comes some sneaky individual who manages to figure out that they can increase their bank balance by telling their internet banking software to withdraw negative amounts of money. I can fix this bug by adding a precondition to the withdraw method, and the bug goes away.
If the balance field was instead public, and a whole bunch of classes were just manipulating it's value arbitrarily, those classes would now need to be changed. If some of those external classes were written by third parties, then we're looking at a whole lot of pain to get the bug fixed.
Why would you use public fields? In the general case, you probably shouldn't. Some languages allow you to have a field scoped as public, then if you need to add a getter/setter later on you can do so without changing your object's interface (I believe C# does this, but correct me if I'm wrong).

datastructure inside object

I have a simple question about object oriented design but I have some difficulties figuring out what is the best solution. Say that I have an object with some methods and a fairly large amount of properties, perhaps an Employee object. Properties, like FirstName, Address and so on, which indicates a data structure. Then there could be methods on the Employee object, like IsDueForPromotion(), that is more of OO nature.
Mixing this does not feel right to me, I would like to separate the two but I do not know how to do it in a good way. I have been thinking about putting all property data in a struct and have an internal struct object inside the employee object, private EmployeeStruct employeData ...
I am not sure this is a really good idea however, maybe I should just have all methods and proerties in the same class and go with that. Am I making things to complicated if I separate data from methods?
I would very much appreciate if someone have any ideas about this.
J
Wasn't the idea of OO-design to encapsulate data and the corresponding methods together?
The question here is how the Employee object could possibly know about begin due for promotion. I guess that method belongs somewhere else to a class which has the informations to decicde that. really stupid example Manager m = new Manager(); manager.IsDueForPromotion(employeeobject);
But other methods to access the fields of Employee belong to this class.
The question I raised about IsDueForPromotion depends on you application and if your Employee is a POJO or DTO only or if it can have more "intelligent" methods associated too.
if your data evolves slower than behaviour you may want to give a try to Visitor pattern:
class Employee {
String name;
String surName;
int age;
// blah blah
// ...getters
// ...setters
// other boilerplate
void accept(EmployeeVisitor visitor) {
visitor.visitName(name);
visitor.visitAge(age);
// ...
}
}
interface EmployeeVisitor {
void visitName(String name);
void visitAge(int age);
}
with this design you can add new operations without changing the Employee class.
Check also use the specification pattern.
Object operations (methods) are supposed to use the properties. So I feel its better to leave them together.
If it does not require properties, its a kind of utility method and should be defined else ware, may in some helper class.
Well, OO is a way of grouping data and functionality that belong together in the same location. I don't really see why you would make an exception 'when there is a lot of data'. The only reason I can think of is legibility.
Personally I think you would be making things needlessly complex by coming up with a separate struct to hold your data. I'm also conflicted as to wether this would be good practice. On the one hand, how a class implements it's functionality, or stores it's data is supposed to be hidden from the outside world. On the other hand, if data belongs to a class, it feels unnatural to store it in something like a struct.
It may be interesting to look at the data you have and see if it can be modeled into smaller domain objects. For example, have an Address object that holds a street, housenumber, state, zip, country, etc value. That way, your Employee object will just hold an Address object. The Address object could then be reused for your Company objects etc.
The basic principle of Object Oriented programming is grouping data such as FirstName and Address with the functionality that goes with it, such as IsDueForPromotion(). It doesn't matter how much data the object is holding, it will still hold that data. The only time you want to remove data from an object is if it has nothing to do with that object, like storing the company name in the Employee object when it should be stored in a company object.

Is there a commonly used OO Pattern for holding "constant variables"?

I am working on a little pinball-game project for a hobby and am looking for a pattern to encapsulate constant variables.
I have a model, within which there are values which will be constant over the life of that model e.g. maximum speed/maximum gravity etc. Throughout the GUI and other areas these values are required in order to correctly validate input. Currently they are included either as references to a public static final, or just plain hard-coded. I'd like to encapsulate these "constant variables" in an object which can be injected into the model, and retrieved by the view/controller.
To clarify, the value of the "constant variables" may not necessarily be defined at compile-time, they could come from reading in a file; user input etc. What is known at compile time is which ones are needed. A way which may be easier to explain it is that whatever this encapsulation is, the values it provides are immutable.
I'm looking for a way to achieve this which:
has compile time type-safety (i.e. not mapping a string to variable at runtime)
avoids anything static (including enums, which can't be extended)
I know I could define an interface which has the methods such as:
public int getMaximumSpeed();
public int getMaximumGravity();
... and inject an instance of that into the model, and make it accessible in some way. However, this results in a lot of boilerplate code, which is pretty tedious to write/test etc (I am doing this for funsies :-)).
I am looking for a better way to do this, preferably something which has the benefits of being part of a shared vocabulary, as with design patterns.
Is there a better way to do this?
P.S. I've thought some more about this, and the best trade-off I could find would be to have something like:
public class Variables {
enum Variable {
MaxSpeed(100),
MaxGravity(10)
Variable(Object variableValue) {
// assign value to field, provide getter etc.
}
}
public Object getVariable(Variable v) { // look up enum and get member }
} // end of MyVariables
I could then do something like:
Model m = new Model(new Variables());
Advantages: the lookup of a variable is protected by having to be a member of the enum in order to compile, variables can be added with little extra code
Disadvantages: enums cannot be extended, brittleness (a recompile is needed to add a variable), variable values would have to be cast from Object (to Integer in this example), which again isn't type safe, though generics may be an option for that... somehow
Are you looking for the Singleton or, a variant, the Monostate? If not, how does that pattern fail your needs?
Of course, here's the mandatory disclaimer that Anything Global Is Evil.
UPDATE: I did some looking, because I've been having similar debates/issues. I stumbled across a list of "alternatives" to classic global/scope solutions. Thought I'd share.
Thanks for all the time spent by you guys trying to decipher what is a pretty weird question.
I think, in terms of design patterns, the closest that comes to what I'm describing is the factory pattern, where I have a factory of pseudo-constants. Technically it's not creating an instance each call, but rather always providing the same instance (in the sense of a Guice provider). But I can create several factories, which each can provide different psuedo-constants, and inject each into a different model, so the model's UI can validate input a lot more flexibly.
If anyone's interested I've came to the conclusion that an interface providing a method for each psuedo-constant is the way to go:
public interface IVariableProvider {
public int maxGravity();
public int maxSpeed();
// and everything else...
}
public class VariableProvider {
private final int maxGravity, maxSpeed...;
public VariableProvider(int maxGravity, int maxSpeed) {
// assign final fields
}
}
Then I can do:
Model firstModel = new Model(new VariableProvider(2, 10));
Model secondModel = new Model(new VariableProvider(10, 100));
I think as long as the interface doesn't provide a prohibitively large number of variable getters, it wins over some parameterised lookup (which will either be vulnerable at run-time, or will prohibit extension/polymorphism).
P.S. I realise some have been questioning what my problem is with static final values. I made the statement (with tongue in cheek) to a colleague that anything static is an inherently not object-oriented. So in my hobby I used that as the basis for a thought exercise where I try to remove anything static from the project (next I'll be trying to remove all 'if' statements ;-D). If I was on a deadline and I was satisfied public static final values wouldn't hamstring testing, I would have used them pretty quickly.
If you're just using java/IOC, why not just dependency-inject the values?
e.g. Spring inject the values via a map, specify the object as a singleton -
<property name="values">
<map>
<entry> <key><value>a1</value></key><value>b1</value></entry>
<entry> <key><value>a2</value></key><value>b3</value></entry>
</map>
</property>
your class is a singleton that holds an immutable copy of the map set in spring -
private Map<String, String> m;
public String getValue(String s)
{
return m.containsKey(s)?m.get(s):null;
}
public void setValues(Map m)
{
this.m=Collections.unmodifiableMap(m):
}
From what I can tell, you probably don't need to implement a pattern here -- you just need access to a set of constants, and it seems to me that's handled pretty well through the use of a publicly accessible static interface to them. Unless I'm missing something. :)
If you simply want to "objectify" the constants though, for some reason, than the Singleton pattern would probably be called for, if any; I know you mentioned in a comment that you don't mind creating multiple instances of this wrapper object, but in response I'd ask, then why even introduce the sort of confusion that could arise from having multiple instances at all? What practical benefit are you looking for that'd be satisfied with having the data in object form?
Now, if the values aren't constants, then that's different -- in that case, you probably do want a Singleton or Monostate. But if they really are constants, just wrap a set of enums or static constants in a class and be done! Keep-it-simple is as good a "pattern" as any.

Is this setter 'evil'

There's alot of talk about getters and setters being 'evil' and what not.
My question is: is the following setter evil? (rest of class omitted for brevity's sake)
int balance
public void deposit(int amount)
{
this.balance += amount;
}
This class is emulating an ATM. In the UK there are a few ATM's that lets you deposit as well as withdraw therefore this object needs a way of changing its state (the balance). Is this setter 'evil'?
Except for the fact that there is no handling of exceptional conditions, it looks like a perfectly good OO method - it's called what it does, and it does what you'd expect.
I don't believe that that is what is meant when people talk about getters and setters, because this is not simply setting a member to the given value.
I don't care for setters and getters, but mostly because I think of my "objects" as higher-level entities in the codebase. E.g. (IMO) it would be "more wrong" to do the operation outside of the class:
account.SetBalance(account.GetBalance() + depositAmount)
Instead, you've implemented higher-level functionality in your object; you make a deposit and let the object figure out the right way of dealing with it. This allows much more centralized handling of exceptional conditions than the getter/setter example I gave above.
Is that a trick question? I ask because the provided method isn't even a "setter" method. It's an operation, not a property. Setters and Getters are generally accessor methods for private variables (properties). So i guess the answer to your question is:
That's not a setter, but as a general method that performs an operation on an object, it's not evil at all.
For a class, there's nothing evil about setting a value via a setter, but that's more of a function than a direct setter. Yes, it sets the value of a property, but it does it via addition rather than replacing the previous value and the names don't line up.
A real 'setter' would look more like this:
int balance
private void setBalance(int amount)
{
this.balance = amount;
}
public void deposit(int amount)
{
setBalance(this.balance + amount);
}
For your specific ATM problem, though, I very much doubt that an ATM adds a deposit to your balance immediately. It likely needs to be collected and posted via a separate mechanism.
Personally, I would call that a method, not a setter. The stereotypical setter would be
public void deposit(int new_balance)
{
this.balance = new_balance;
}
All it does is give you direct access to the internals of the class, thus defeating any value gained by encapsulating them and restricting access. Which is why people don't like them.
Well you would want to check for negative amounts, a zero amount, etc... but give the requirement it is ok.
Follow this rule of thumb, every variable you make should be final unless it has to change and never make set methods for instance variables unless you really want them to be changed outside of the class.
Not necessarily; you mention that you want to emulate the behaviour of an ATM (cash machine). And you're concerned that ATMs let you deposit as well as withdraw. But those operations, the deposit and withdrawl, would have to be serialized. You need all of your actions to be atomic, so this sort of method is better than one where you try to do more things.
One issue that I see is that you are using an integral type when dealing with money. Not an issue if this is a fixed-point number but there is no indication that it is so.
IMO, the ATM should not have 'balance' as a field.
(additionally, your 'deposit' method is not a setter)
You should probably have an Account object with a 'balance' field and possibly a convenience method 'modifyBalance' on it that takes a positive value to increment or a negative value to decrement the balance.
Then your ATM methods would call 'modifyBalance' on the Account object when performing those types of transactions.
You can't tell whether a single method is evil or not, it depends on the context and who has access to the object.
If you have getters and setters for all fields and everybody and his dog have access to the object, then that is very bad, as there is essentially no encapsulation of the data.
If on the other hand you have setters only for the fields which need it and the object is only known to a select few other objects which need to communicate with it, then that would be quite OK.
That's not a setter. That's a normal method (or member function, or whatever).
A setter is a function that sets a given variable to a given value, and is usually a bad idea. A method is a function that performs a given class operation. It's meaningful in terms of the class.
If you have a weird data structure, you may not actually have a "balance" variable. No matter what your data structure, you're going to have to have a "deposit" function. There's part of the difference.
that's not a setter, its a normal method
even if it was a setter, it's not evil
this is an evil setter
int _balance = 0;
public int Balance()
{
get { return _balance; }
set { } //now that's evil!
}