U
U
Urukhayy2015-05-26 16:52:18
Programming
Urukhayy, 2015-05-26 16:52:18

What is the best way to do it in such cases?

I'll give you an example. In some section of the code, the Nth amount needs to be withdrawn from the user account. Naturally, before withdrawing, you need to check if this amount is in his variable. So. In this situation, a couple more checks are added: is there an account, when did the account appear, etc. And most importantly, after any negative check of the score, you need to inform the user about it, and interrupt the code section.
And this section when (with checking the account and withdrawing the amount) needs to be duplicated in many places in the code, only the amounts are different.
If everything is entered into a function that takes the sum as an argument, then it is also an exit. But there is one BUT. If in the code section, before withdrawing the amount, we inform the user that they have withdrawn, and the next line will be a call to this function, which will find out that the user does not have such an amount, then it will not be entirely correct. In this case, using this approach, you should always consider calling this function in the first place in the code section.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
Vladimir Martyanov, 2015-05-26
@vilgeforce

And what is the problem? Take out to a function, the function returns true if the removal was definitely successful. All checks are in it ... And if true is returned, report that it has been removed.

O
Oleg, 2015-05-26
@ollisso

$result = takeMoney(100);

if($result==='ok')
      echo "Удачно сняли деньги";
}elseif($result=='account_closed'){
      echo "Аккаунт закрыт";
}elseif($result=='money_wrong'){
      echo "Вы указали неправильную сумму";
}else{
 echo "Непредвиденная ошибка";
}

This is a head-on solution, no problem if.
takeMoney respectively returns error codes or 'ok' if ok
Example in php, but similar is written in any language.

V
Vladislav Tankov, 2015-05-26
@TanVD

To solve similar problems, the approach of Aspect-Oriented Programming (AOP) is used. You can read it
Here (wiki)
Here (habr)
Here (almost a book)
Support is provided using frameworks like AspectJ, Aspect#, Aspect.NET and a bunch of others.

M
Maxim Moseychuk, 2015-05-26
@fshp

You can use monads. And error logging will be security.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question