Approve against return false?

bool fn()
{
  if(something bad happen)
     return false;
  ..
}


void gn()
{
  assert(something == true);
  ..

}

When I write a function in production code, how should I choose?

+5
source share
12 answers

Assert, at least in .NET, is used for testing in the first place. Its specific use is presented briefly here :

An assertion is best used to verify a condition only if the following conditions are true:

* the condition should never be false if the code is correct,
* the condition is not so trivial so as to obviously be always true, and
* the condition is in some sense internal to a body of software.

In production code, I would recommend the first method; or try/catchif "something bad" is never expected; if this is an exceptional condition.

, ( ), Assert .

; . .

+5

, , " - " = - ...

+3

assert , , ( , ). - , , .

-, ( ), (, invaid , , ), / (, ,...).

+3

"return false" GuardClause - :

... [G] uard , . , , , . "" EwDijkstra .

, BouncerPattern.

, , . assert, .

, . . unit test. ( ...), , , .

" ", , , . , " " .

+2

IMHO, assert , - (). , .

false , , .

+1

assert, - , . :

int div( int a, int b ) {
  assert( b != 0 );
  return a / b;
}

, div() . , .

if()... return, , . , - .

+1

. (.. , - ). , - , , - . . , , .

+1

- , - . , fn() , . . , , , . , gn , - , , eithers if , . , , , .

.

0

/ .

(.. ). , .

, , , , , .

" " ( b/c ), , , .

0

, . , , , , , - . false , .

0

, - . : . , . . Eiffel.

() , StrinToIntegerDef (, ), , Integer.

false , .

, , assert (condition, message), .

Also, if there are several possibilities for rejection, return some enumeration values ​​instead of false.

0
source

Use the statements for the function mandate preconditions (conditions that must be true if the function must have any value).

0
source

All Articles