Is this setter "evil"

There is a lot of talk about what getters and setters are “evil” and what is not.

My question is: the next evil setter? (the rest of the class is omitted for brevity)

int balance

public void deposit(int amount)  
{  
    this.balance += amount;  
}

This class emulates ATM. In the UK there are several ATMs that allow you to make deposits and also withdraw, so this object needs to change its state (balance). Is this setter evil?

+3
source share
12 answers

Except for the fact that there is no handling of exceptional conditions, it looks like an absolutely good OO method - he called what he does and does what you expect.

+8
source

, , , .

, , "" . . (IMO) " " :

account.SetBalance(account.GetBalance() + depositAmount)

; . , getter/setter.

+8

? , "". , . Setters Getters (). , :

, , , .

+4

, , . , , , .

"" :

int balance

private void setBalance(int amount)
{
    this.balance = amount;
}

public void deposit(int amount)  
{  
    setBalance(this.balance + amount);  
}

ATM , . , .

+3

, .

public void deposit(int new_balance)
{
    this.balance = new_balance;
}

, , , , , . .

+2

, , ..... , .

, , , , , , .

+1

; , (). , , . , . , , , , .

0

, , , . , , , .

0

IMO, "" .

( , "" )

, Account "balance" , , "modifyBalance", .

ATM "modifyBalance" Account .

0

, , .

, , , .

, , , , , , .

0

. ( -, - ).

Setter - , . - , . .

If you have a strange data structure, you may not have a “balance” variable. Regardless of the data structure, you will have to have a “deposit” function. There is part of the difference.

0
source

that is not a setter, its normal method

even if it was a setter, it is not evil

This is an evil setter

int _balance = 0;  
public int Balance()  
{  
    get { return _balance; }  
    set { }    //now that evil!  
}
0
source

Source: https://habr.com/ru/post/1703840/


All Articles