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

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).

Related

How do accessors prevent hackers from accessing your private data?

Whenever a tutorial first introduces accessors, they always start off with a public variable initialized in the class or object. There is then a method to print that public value. Then they make it private to show that it is hidden to outside users.
For example:
int _dayOfWeek;
public int dayOfWeek
{
get
{
return _dayOfWeek;
}
set
{
if (value > 0 && value < 8) _dayOfWeek = value;
}
}
What's stopping hackers from just using these accessors to get and change your values?
Encapsulation doesn't help against hackers. It helps against mistaken use of your code. See the wiki article for more information on the uses of encapsulation.
By making your private data accessible to programmers who use your code it is very hard to make sure that they use it properly. If you control all access to your data then you can ensure that it is indeed used as you intended it to be used.
Providing accessors to your private data is usually a code smell that indicates improper encapsulation. It is only slightly better than exposing your data. You want to expose to the users functionality and not raw data.

How to avoid getters and setters

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.

Are there adverse effects of passing around objects rather than assigning them as members of a class

I have a habit of creating classes that tend to pass objects around to perform operations on them rather than assigning them to a member variable and having operations refer to the member variable. It feels much more procedural to me than OO.
Is this a terrible practice? If so, what are the adverse effects (performance, memory consumption, more error-prone)? Is it simply easier and more closely aligned to OO principles like encapsulation to favour member variables?
A contrived example of what I mean is below. I tend to do the following;
public class MyObj()
{
public MyObj() {}
public void DoVariousThings(OtherObj oo)
{
if (Validate(oo))
{
Save(oo);
}
}
private bool Validate(OtherObj oo)
{
// Do stuff related to validation
}
private bool Save(OtherObj oo)
{
// Do stuff related to saving
}
}
whereas I suspect I should be doing the following;
public class MyObj()
{
private OtherObj _oo;
public MyObj(OtherObj oo)
{
_oo = oo;
}
public void DoVariousThings()
{
if (Validate())
{
Save();
}
}
private bool Validate()
{
// Do stuff related to validation with _oo
}
private bool Save()
{
// Do stuff related to saving with _oo
}
}
If you write your programs in an object oriented language, people will expect object oriented code. As such, in your first example, they would probably expect that the reason for making oo a parameter is that you will use different objects for it all the time. In your second example, they would know that you always use the same instance (as initialized in the constructor).
Now, if you use the same object all the time, but still write your code like in your first example, you will have them thoroughly confused. When an interface is well designed, it should be obvious how to use it. This is not the case in your first example.
I think you already answered your question yourself, you seem to be aware of the fact that the 2nd approach is more favorable in general and should be used (unless there are serious reasons for the first approach).
Advantages that come to my mind immediately:
Simplified readability and maintainability, both for you and for others
Only one entry point, therefore only needing to checking for != null etc.
In case you want to put that class under test, it's way easier, i.e., getting something like this (extracting interface IOtherObj from OtherObj and working with that):
public MyObj (IOtherObj oo)
{
if (oo == null) throw...
_oo = oo;
}
Talking of the adverse effects of your way, there are none, but only if you are keeping the programs and the code to yourself,, what are you doing is NOT a standard thing, say, if after some time, you start to work making libraries and code that may be used by others also, then it is a big problem. The may pass any foo object and hope that it would work.
you have to validate the object before passing it and if the validation fails do things accordingly, but if u use the standard OOP way, there is no need for validation or taking up the cases where an inappropriate type object is pass,
In a nutshell, your way is bad for :
1. code re-usability.
2. you have to handle more exceptions.
3. okay, if u r keeping things to urself, otherwise, not a good practice.
hope, it cleared some doubt.

Encapsulation. Well-designed class

Today I read a book and the author wrote that in a well-designed class the only way to access attributes is through one of that class methods. Is it a widely accepted thought? Why is it so important to encapsulate the attributes? What could be the consequences of not doing it? I read somewhere earlier that this improves security or something like that. Any example in PHP or Java would be very helpful.
Is it a widely accepted thought?
In the object-oriented world, yes.
Why is it so important to encapsulate the attributes? What could be the consequences of not doing it?
Objects are intended to be cohesive entities containing data and behavior that other objects can access in a controlled way through a public interface. If an class does not encapsulate its data and behavior, it no longer has control over the data being accessed and cannot fulfill its contracts with other objects implied by the public interface.
One of the big problems with this is that if a class has to change internally, the public interface shouldn't have to change. That way it doesn't break any code and other classes can continue using it as before.
Any example in PHP or Java would be very helpful.
Here's a Java example:
public class MyClass {
// Should not be < 0
public int importantValue;
...
public void setImportantValue(int newValue) {
if (newValue < 0) {
throw new IllegalArgumentException("value cannot be < 0");
}
}
...
}
The problem here is that because I haven't encapsulated importantValue by making it private rather than public, anyone can come along and circumvent the check I put in the setter to prevent the object from having an invalid state. importantValue should never be less than 0, but the lack of encapsulation makes it impossible to prevent it from being so.
What could be the consequences of not
doing it?
The whole idea behind encapsulation is that all knowledge of anything related to the class (other than its interface) is within the class itself. For example, allowing direct access to attributes puts the onus of making sure any assignments are valid on the code doing the assigning. If the definition of what's valid changes, you have to go through and audit everything using the class to make sure they conform. Encapsulating the rule in a "setter" method means you only have to change it in one place, and any caller trying anything funny can get an exception thrown at it in return. There are lots of other things you might want to do when an attribute changes, and a setter is the place to do it.
Whether or not allowing direct access for attributes that don't have any rules to bind them (e.g., anything that fits in an integer is okay) is good practice is debatable. I suppose that using getters and setters is a good idea for the sake of consistency, i.e., you always know that you can call setFoo() to alter the foo attribute without having to look up whether or not you can do it directly. They also allow you to future-proof your class so that if you have additional code to execute, the place to put it is already there.
Personally, I think having to use getters and setters is clumsy-looking. I'd much rather write x.foo = 34 than x.setFoo(34) and look forward to the day when some language comes up with the equivalent of database triggers for members that allow you to define code that fires before, after or instead of a assignments.
Opinions on how "good OOD" is achieved are dime a dozen, and also very experienced programmers and designers tend to disagree about design choices and philosophies. This could be a flame-war starter, if you ask people across a wide varieties of language background and paradigms.
And yes, in theory are theory and practice the same, so language choice shouldn't influence high level design very much. But in practice they do, and good and bad things happen because of that.
Let me add this:
It depends. Encapsulation (in a supporting language) gives you some control over how you classes are used, so you can tell people: this is the API, and you have to use this. In other languages (e.g. python) the difference between official API and informal (subject to change) interfaces is by naming convention only (after all, we're all consenting adults here)
Encapsulation is not a security feature.
Another thought to ponder
Encapsulation with accessors also provides much better maintainability in the future. In Feanor's answer above, it works great to enforce security checks (assuming your instvar is private), but it can have much further reaching benifits.
Consider the following scenario:
1) you complete your application, and distribute it to some set of users (internal, external, whatever).
2) BigCustomerA approaches your team and wants an audit trail added to the product.
If everyone is using the accessor methods in their code, this becomes almost trivial to implement. Something like so:
MyAPI Version 1.0
public class MyClass {
private int importantValue;
...
public void setImportantValue(int newValue) {
if (newValue < 0) {
throw new IllegalArgumentException("value cannot be < 0");
}
importantValue = newValue;
}
...
}
MyAPI V1.1 (now with audit trails)
public class MyClass {
private int importantValue;
...
public void setImportantValue(int newValue) {
if (newValue < 0) {
throw new IllegalArgumentException("value cannot be < 0");
}
this.addAuditTrail("importantValue", importantValue, newValue);
importantValue = newValue;
}
...
}
Existing users of the API make no changes to their code and the new feature (audit trail) is now available.
Without encapsulation using accessors your faced with a huge migration effort.
When coding for the first time, it will seem like a lot of work. Its much faster to type: class.varName = something vs class.setVarName(something); but if everyone took the easy way out, getting paid for BigCustomerA's feature request would be a huge effort.
In Object Oriente Programming there is a principle that is known as (http://en.wikipedia.org/wiki/Open/closed_principle):
POC --> Principle of Open and Closed. This principle stays for: a well class design should be opened for extensibility (inheritance) but closed for modification of internal members (encapsulation). It means that you could not be able to modify the state of an object without taking care about it.
So, new languages only modify internal variables (fields) through properties (getters and setters methods in C++ or Java). In C# properties compile to methods in MSIL.
C#:
int _myproperty = 0;
public int MyProperty
{
get { return _myproperty; }
set { if (_someVarieble = someConstantValue) { _myproperty = value; } else { _myproperty = _someOtherValue; } }
}
C++/Java:
int _myproperty = 0;
public void setMyProperty(int value)
{
if (value = someConstantValue) { _myproperty = value; } else { _myproperty = _someOtherValue; }
}
public int getMyProperty()
{
return _myproperty;
}
Take theses ideas (from Head First C#):
Think about ways the fields can misused. What can go wrong if they're not set properly.
Is everything in your class public? Spend some time thinking about encapsulation.
What fields require processing or calculation? They are prime candidates.
Only make fields and methods public if you need to. If you don't have a reason to declare something public, don't.

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!
}