Is it wrong to use "extra" variables because it is easier to debug?

I was just debugging code that looked like this:

string someValue = _snuh.FindItem(id).Value; 

I wanted to check the return value of FindItem() (it returns Foo ), so I split the code into two lines:

 Foo foo = _snuh.FindItem(id); string someValue = foo.Value; 

This allowed me to look at foo in the debugger; which I could not do when the code was on the same line.

Now that I have finished debugging, should I return the code as it was, or leave it as two lines?

+4
source share
6 answers

Instead of having one liner like this

 string someValue = _snuh.FindItem(id).Value; 

I would prefer refactoring so that you

 string someValue = _snuh.FindItemValue(id); 

and encapsulate the FindItem() and subsequent Value in the function.

Why? Your first solution provides an implementation of the object returned by FindItem (i.e., Has a Value field). The law of Demeter offers the second option. In addition, it avoids repetition if you need to do this in many places. If you need to perform a null check, you only need to do this once.

+3
source

Two lines are better than one liner:

  • You can debug them
  • If you have a null pointer, you will see the line number in your error logs (and see what is wrong)
  • It is more readable.
  • No additional comments are needed to explain what one liner does.
  • There is no difference in performance (the compiler will be optimized for the same IL)
  • If you rewrite the code after debugging it, you can enter new typos
+5
source

You read your code more than you write it.

Leave it as you see it as the most readable. JIT will optimize your code anyway.

+4
source

At our workplace, our code style rules require that the result of a method call be stored in a variable. The idea behind this is that if an exception using a NULL reference is thrown, the line number will tell you which variable is null, which would not be possible if you acted directly on the result of the method.

In practice, this rule is ignored to some extent - especially when executing Linq queries, because Linq methods do not return null values ​​(recommendations precede the widespread use of Linq).

+3
source

In Visual Studio, you can use the "immediate window " or "add hours" to debug parts of the instruction and view their values ​​without using additional variables.

+3
source

I personally would go with the second approach, along with a "NULL" check on the returned object, before accessing its "Value" property, since it is subject to a Null Reference Exception; which will look something like this.

 string someValue = string.Empty; Foo foo = _snuh.FindItem(id); if (foo != null) { someValue = foo.Value; } 

Hope this helps!

+2
source

All Articles