The Greater Fool

Posts for Tag: Dev Tips

Flip your JavaScript Switch

No one likes code conditionals, right? They're difficult to read, extend, and maintain; primarily because they intermingle data with logic. They're why we put up with bloated IOC containers, just to be able to avoid using switch and nested if statements. In JavaScript, we have a better way. Here's a typical switch statement in JS:

var label = switch (dataTypeId) {
case 'revenue' : 'Thousands of USD';
case 'census' : 'Number of Customers';
case 'inventory' : 'Hundreds of Units';
default: '';

So we have to deal with ubiquitous break token, the extra case structure, and lengthy code bloat to make a simple decision. Got code smell? Here's the alternative, use object prototypal extension and JSON interpretation to create a hash instead.

var labelOptions = {
'revenue' : 'Thousands of USD',
'census' : 'Number of Customers',
'inventory' : 'Hundred of Units'
var label = labelOptions[dataTypeId] || '';

Et voila! We have separation of concerns, data and logic. We have easy extension by adding another property to our labelOptions object. We have more streamlined code without intermingled execution tokens and is easier to grok. Thanks to JavaScript's treatment of functions as data type, you could even return functions instead of simple expressions. So before you reach for that switch construct again, think about hashing instead.

Debugging Tips with Visual Studio 2010 - ScottGu's Blog

Run to Cursor (Ctrl + F10)

Often I see people debugging applications by hitting a breakpoint early in their application, and then repeatedly using F10/F11 to step through their code until they reach the actual location they really want to investigate.  In some cases they are carefully observing each statement they step over along the way (in which case using F10/F11 makes sense).  Often, though, people are just trying to quickly advance to the line of code they really care about – in which case using F10/F11 isn’t the best way to do this.

Instead, you might want to take advantage of the “run to cursor” feature that the debugger supports.  Simply position your cursor on the line in your code that you want to run the application to, and then press the Ctrl + F10 keys together.  This will run the application to that line location and then break into the debugger – saving you from having to make multiple F10/F11 keystrokes to get there.  This works even if the line of code you want to run to is in a separate method or class from the one you are currently debugging.

ScottGu has a bunch of new debugging with Visual Studio 2010 tips but this is the one that sticks out for me. I am guilty as described in pressing F10 repeatedly until I get to the code I actually want to see in action. Ctrl+F10 when the cursor is on the line you're interested in will give you the same results quickly.