Should the code prevent a logically invalid call, even if no harm was done?

This question puzzled me several times.

Imagine a class representing a resource, and in order to be able to use this resource, you must first call the Open method on it, otherwise an InvalidOperationException will be thrown.

Should my code also check if someone is trying to open an open resource or close an already closed one?

Should the code prevent a logically invalid call, even if no harm was done?

I think that programming in this way will help to write better code on the other side, but I feel that I can take on too much responsibility and affect reuse.

What do you guys think?

Edit:

I do not think that this could be called defensive programming, because it would not allow possible misuse to slip through, and another InvalidOperationException will be thrown.

+3
source share
7 answers

This is called defensive programming . This is a good programming practice, because you guarantee that your application will not crash if it is misbehaved.

For a method to be called first before calling another method, this is not good programming practice. This adds a lot of complexity, which is better handled by the class itself.

. , , , . , .

+6

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

, , . , . , .

+3

, Open , , .

iostream ++ ( ), , , . , . , , .

, , . , strlen()

int strlen( const char * s )
{
   if ( s == 0 )
   {
      return 0;     // bad
   }
   else
   {
      // calculate length not shown
   }
} 

, - assert(), .

+2

, , .

, API .

. - . , .

+1

SDK, , API . "" () , , .

. , , . , , , . , , . ? , , .

+1

, , , reset , .

, , , . , , . , - , , , , , / /.

, .

"" , . ? ( ) , , "" , .

+1

.

When compiling in release mode, your code should not throw unnecessary exceptions or do anything else that could threaten the entire application. Personally, I prefer to have some kind of log file, and registering such logically invalid calls will certainly not hurt (at least when performance is not important)

+1
source

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


All Articles