Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid debugger-only variables?

I commonly place into variables values that are only used once after assignment. I do this to make debugging more convenient later, as I'm able to hover the value on the one line where it's later used.

For example, this code doesn't let you hover the value of GetFoo():

return GetFoo();

But this code does:

var foo = GetFoo();
return foo; // your hover-foo is great

This smells very YAGNI-esque, as the functionality of the foo's assignment won't ever be used until someone needs to debug its value, which may never happen. If it weren't for the merely foreseen debugging session, the first code snippet above keeps the code simpler.

How would you write the code to best compromise between simplicity and ease of debugger use?

like image 567
lance Avatar asked Aug 16 '26 16:08

lance


2 Answers

I don't know about other debuggers, but the integrated Visual Studio debugger will report what was returned from a function in the "Autos" window; once you step over the return statement, the return value shows up as "[function name] returned" with a value of whatever value was returned.

gdb supports the same functionality as well; the "finish" command executes the rest of the current function and prints the return value.

This being a very useful feature, I'd be surprised if most other debuggers didn't support this capability.

As for the more general "problem" of "debugger-only variables," are they really debugger-only? I tend to think that the use of well-named temporary variables can significantly improve code readability as well.

like image 66
James McNellis Avatar answered Aug 19 '26 07:08

James McNellis


Another possibility is to learn enough assembly programming that you can read the code your compiler generates. With that skill, you can figure out where the value is being held (in a register, in memory) and see the value without having to store it in a variable.

This skill is very useful if you are ever need to debug an optimized executable. The optimizer can generate code that is significantly different from how you wrote it such that symbolic debugging is not helpful.

like image 32
R Samuel Klatchko Avatar answered Aug 19 '26 08:08

R Samuel Klatchko