Is an If branch that does nothing code smell or good practice?

I answered the threads here (or at least commented ) with answers containing code like this, but I wonder if this is a good or bad form for writing a series of branches iffrom one (or more) branches without doing anything in them , usually to exclude checks for nullin each branch.

Example (C # code):

if (str == null) { /* Do nothing */ }
else if (str == "SomeSpecialValue")
{
    // ...
}
else if (str.Length > 1)
{
    // ...
}

instead:

if (str != null && str == "SomeSpecialValue")
{
    // ...
}
else if (str != null && str.Length > 1)
{
    // ...
}

And of course, this is just an example, as I tend to use them with larger and more complex classes. And in most of these cases, meaning nullmeans doing nothing.

For me, this reduces the complexity of my code and makes sense when I see it. So, is this good or bad form (even the smell of code)?

+5
8

, ( , , - , ):

if (str != null && str == "SomeSpecialValue")
{
    // ...
}
else if (str != null && str.Length > 1)
{
    // ...
}

, , :

if (str == null) { /* Do nothing */ }
else if (str == "SomeSpecialValue")
{
    // ...
}
else if (str.Length > 1)
{
    // ...
}

, , . , , - , , . , , , , , , . , , , (non-null input), , . , , , , , .

- Oren A - null, :

if (str != null) 
{
 if (str == "SomeSpecialValue")
 {
    // ...
 }
 else if (str.Length > 1)
 {
    // ...
 }
}

, , .

EDIT. , do-nothing, , " ". , .

+5

:

if (str != null) 
{
 if (str == "[NULL]")
 {
    // ...
 }
 else if (str.Length > 1)
 {
    // ...
 }
}  

, "" if , .

+21

return - if:

void Foo()
{
  if (str == null) { return; }
  if (str == "SomeSpecialValue")
  {
      // ...
  }
  else if (str.Length > 1)
  {
      // ...
  }
}

, - if/else, , if/else , .

+6

,

if (string.IsNullOrEmpty(str)) { return; }  

return.

+4

, .

, .

, - - . , .

, , /​​// /.

user359996 :

, , .

+3

- .

+2

. if, , .

+2

, , , - "" if . , : string.IsNullOrEmpty() string.IsNullOrWhiteSpace().

if (str == null) { /* Do nothing */ } , : , , long if/else if ,

if (str != null) 
{ 
    /* carry on with the rest of the tests */
}
+2

All Articles