Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation in setters: What approach is better?

I have dispute with my friend.

He said me that this code:

method SetBalance(balance) {
    if (balance > 0) {
        this.balance = balance;
        return true;
    }
    return false;
}

is better then this:

method SetBalance(balance) {
    if (balance < 0) {
        throw new InvalidArgumentException("Balance couldn't be negative")
    }
    this.balance = balance; 
}

My question is: "Which approach is better for validation?" and why?

Thank you.

like image 342
Dmytro Krasun Avatar asked Feb 19 '23 13:02

Dmytro Krasun


2 Answers

Ah. Return status versus exception.

I prefer throwing exceptions, because you can't really ignore an exception. The program either crashes, or you have to explicitly catch and handle it.

You can just ignore a return status.

Besides, isn't this the reason exceptions exist in modern programming? To deal with, well... exceptions (balance <= 0, something that shouldn't happen).

like image 158
Luchian Grigore Avatar answered Feb 22 '23 05:02

Luchian Grigore


In case of setters, developers will never expect the return value from those methods since they feel that this will anyway will take care of setting the value.
In case, if there is an exception, then this will help then to understand that something is really wrong and look after the code again.
Instead of runtime exception, you better define your own exception like InvalidBalanceException and specify that this method will throw this exception in the signature itself. This avoids surprises at testing phase and decide the business logic in development phase itself.

like image 38
sundar Avatar answered Feb 22 '23 04:02

sundar