It's a Zebra Horse. Literally.

I was recently asked to implement functionality that mimic'd existing functionality in our system, but was for a different type of data.  The two types of data share a common object heirarchy, so the task was a matter of changing something that was named 'Zebra' to a 'Horse'. You could even say that the only thing that differed about the two types of data was their name and the specific database objects they interacted with.

I did the naive thing at first, and I used the Copy and Paste design pattern.  I went from zero to regret in less than three keystrokes.

Copy and Paste Design Pattern

Copy and Paste is a horrible design pattern. I used it at first because it would allow me to finish the task quickly. On the other hand, I'd have to go into hiding should anyone ever stumble across that code.  The only excuse I could muster is that the code should never need to change.

About halfway through this exercise, I couldn't shake the feeling that I still had no idea what the code actually did.  I was a monkey pulling a lever, trying to get a food pellet.

It was sickening.

The books on my shelf started to laugh at me, Clean Code, Working Effectively with Legacy Code, and Code Complete all burned in the corner of my eye not unlike the ancient Sankara stones. As I struggled to withstand their withering glare, I knew there was only one option: Roll my sleeves up and learn what the heck the code was doing, and most importantly, Refactor it.

Refactoring when you have no idea what you're doing

The trickiest part of refactoring is how long it actually takes to figure out what a piece of code actually does. Every name, every method, every property becomes a possible source of hidden problems. Just think,  If the code was well written, there'd be no need to refactor it.

To that end, I do four things when I need to refactor code:

  1. Determine what the purpose of the code was
  2. Draw UML and action diagrams of the classes involved
  3. Shop around for the right design patterns
  4. Determine clearer names for the current classes and methods

I spend most of my time on #4.  As Mark Twain said, The difference between the almost right word & the right word is really a large matter -- it's the difference between the lightning bug and the lightning.

If you don't understand code, play with it. Try to refactor it. Create a branch and monkey around with it. Try to improve it. Most importantly, rename it.


ZebraHorse Photo courtesy of ***Karen and her Flickr account.


View Comments: Comments (0) |

May 18, 2010

Ikea Job Interview
Ikea Job Interview

I interviewed at a Web development firm recently; it was a nice place. Very anti-corporate, which if you know anything about me, you know I dig that

The interview itself was a 'gang' interview, with five separate personalities in the room (not including my own):

  1. The One that Made Me Feel Comfortable
  2. The Observer
  3. The-Quiet-Yet-Perceptive-One
  4. the Alpha
  5. The I-don't-say-much-but-I-know-what-I'm-talking-about one. 

As it happens, the Observer was actually the Grand Poobah (Or Head Honcho, or Big Cheese, but I generally refrain from cliché in my posts. No. Really.), but he elected to remain quiet throughout the interview.

The interview itself ranged from questions about me and what I've done, to Questions I know the answer to, to questions I don't know off the top of my head but when not surrounded by 5 people and really nervous I could probably answer, to questions I know I don't know the answer to and said as much, and Zombies. 

I really wish Zombies had been brought up first.

P.S.: If I had known I could pick *any* weapon (real or not) to fight zombies, then I would have probably picked the Disc Launcher from Tribes.  Just hearing that whirring noise brings back memories.  As it stands, I think the Double barreled Shotgun from Doom was a good choice. If these are 28-days-later zombies, you're going to want something upclose and personal because that's where the zombies are.

Anyway, back to the interview: The Alpha asked me about CSS Selectors.  CSS-what? Keep in mind, I'm implementing a new layout for Stack Blog (that will replace this blog's current layout), I've implemented stylesheets for my work on St. Anns, and I tweaked an already existing layout for Big Spring.  Most recently (read: last week) I created the CSS For the Project dashboard.

The question specifically was, "What are CSS Selectors?" My (stupid) answer? I don't know. Or at least, I thought I didn't. I'd heard the word, but wasn't about to BS an answer.

Turns out I use them all the time, I just didn't know what they were called.

If you've ever seen this:

#main {
font-family: Helvetica, Arial, Verdana;
font-size: 0.9em;
border: 1px solid #ccc;
}

then you've used CSS selectors. That thing up top, before the curly braces? That's an 'id'; specifically a div id named 'main'. And it's a selector.  'Selector' is just a fancy word for 'that which I will apply the style to'.*  You can apply them to divs, html elements, and just about anything you want. You can even apply them to specific lines inside of Paragragh tags.

I learned an important lesson from that interview: Know your terminology. I'd been using selectors for years, but had never realized that's what they were called.

 

*That's only a smidgen of what's really out there for Selectors.  Glancing through the list on this page, there are some formats I've used, and others I haven't.  Of course, I'm not telling the full story, there is more to selectors than that. If you're interested, this site goes through the nitty-gritty of CSS selectors.


View Comments: Comments (1) |

Warning signs in a software project rarely are found in code first. Just about the time you unpack your cubicle and get your development environment up and running, you will already have received warning signs about the application. Here's what to listen for:

 

  • "The code is very complex."
  • "Be careful when you make this change, it's going to affect X."
  • "No, we don't have unit tests. Our code is too complex for that."
  • "We have a global cache that takes care of all of that."
  • "We don't fully understand what that affects, so be careful."

 

These phrases center around a theme: The code is really hard to grok and it's chock full of dependencies.

Uh oh.

If you've worked in with enough legacy codebases, you've probably gotten used to that.  Get un-used to it. It's wrong.  Code is only as complex as you make it. As Ernest Hemingway has taught us, you don't need to use big words to tell a story.

Your code is not an exception to this rule.

Before you cast aside what I'm saying, think about it this way: If a human can communicate using nothing but the most basic language, and communicate effectively, then why can't the same thing be done in code? Why is that the exception?


View Comments: Comments (1) |

May 13, 2010

 

I encountered this CAPTCHA recently. Insert your own joke here.


View Comments: Comments (0) |

I tried to install SQL Server Management Studio Express 2008 today.

Going through that install process gives me a taste of the cruel world DBAs live in. I feel bad for those guys. No wonder they're frazzled and grumpy.

I went to the SMSSE download page and was informed after downloading the program that I need to go to the Windows Installer 4.5 page and install the installer so that I could run the SQL Server Installer. My head hurts.

After reading tea leaves and conjuring up spirits with the Ouija board, I figured out how to install the Windows Installer.  At this point my morning took a turn. After dutifully restarting my computer, I ran the SMSSE installation process to have it tell me that my computer needed to be restarted before I could install SQL Server 2008.  It didn't matter how many times I restarted my PC, it still failed to install.  I summed it up in a Twitter Post:

After searching the internet, I found the answer in a Microsoft Support Forum:

  1. Click 'Start' -> Run...
  2. Type: Regedit, hit enter.
  3. Navigate to: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations
  4. Right click PendingFileRenameOperations and click Modify.
  5. Delete the value for PendingFileRenameOperations.
  6. Close the Registry Editor, the issue should be fixed.

After you're finished, it should look like this:

In my case, it did and I was able to install SMSSE, just with a little less hair.


 


View Comments: Comments (0) |

claptrap

I was enjoying downtime this weekend after a few weeks of pretty intense work and sat down to play Borderlands, and having beat the game, I was just starting my second playthrough.  Claptrap came over the radio and told me that 'Chef Sanders' had more missions for me in the Arid Badlands.

Have you ever tried to google for 'Chef Sanders Arid Badlands Borderlands'? Go ahead, try.  I didn't get many hits either.  It turns out our little mechanical friend is actually saying Shep Sanders

Here's where Shep Sanders is located:


View Comments: Comments (3) |

Recently I was cleaning up some code in a legacy application and found this little gem:


private IList entities = new List();

private IList Entities
{ get { return this.entities; } }

protected virtual CustomDataSet ExecuteIntoDataSet(
OracleCommand command, bool fillSchema)
{
DataSet dataSet = new DataSet();

try
{
OracleDataAdapter dataAdapter = new OracleDataAdapter(
command);

if (fillSchema)
{
dataAdapter.FillSchema(dataSetm, customParameter);
}

dataAdapter.Fill(dataSet);

} // try
catch (Exception ex)
{
# if DEBUG
throw ex;
#else
throw new FriendlyException(ex.Message, ex);
#endif
} // catch

DataSetEntity entity = new DataSetEntity(dataSet);

this.Entities.Add(entity);

return entity;
}

private void DisposeEntities()
{
// dipose all data entities
for (int i = this.Entities.Count - 1; i >= 0; --i)
{
BaseDataEntity entity = this.Entities[i] as BaseDataEntity;
if (entity != null)
{
entity.Dispose();
this.Entities.RemoveAt(i);
} // if
} // foreach
}

Ouch.

This code was written about 2005. C# had the 'using' block, as well as try/catch/finally.  But in this case, neither is used to clean up the dataAdapter .

That's important to know. It's really easy for me to cast judgement on this code; but what really matters is *why* this code was written the way it was.  It's not as if the people that worked on this application were stupid -- on the contrary they were probably quite smart.  There are a number of reasons why it was written this way:

 

  1. Programmer didn't understand what could happen to the open connection if something failed.
  2. Programmer didn't realize there was a 'using' or 'finally' statement in C#.
  3. Time.
  4. No Code reviews (or)
  5. No one senior enough to review the code.
There are also some other indicators in the code itself that tell us something about who wrote it: They used comments that explained what we already knew, and they used comments to close blocks of code, both distractions to understanding the code.

There's a certain amount of 'If it isn't broke, don't fix it' in legacy applications.  There's inertia against changing code, especially if the code physically works.  But the real question is, Should the code be changed? and the answer is unequivically Yes.

What happens if it bombs when calling FillSchema? What about if the connection to the database dies? What about if it throws an exception for some other reason? 

These are all questions we should be asking ourselves when working on code.  I hate to invoke Murphy, but if there's a chance that something can go wrong, it will. It's our job to make sure that when it does go wrong, we handle it gracefully.

Don't ever accept We've always done it that way as a valid reason to keep code the way it is. Code is a living document, not the Constitution. Treat it as such.

 


View Comments: Comments (0) |

April 21, 2010

During the latter part of Basic Training, when the Drill Sergeants stopped screwing with us at every conceivable opportunity, they sat down and talked to us.  During one talk, a trainee (we weren't allowed to be called 'soldiers' yet) asked for tips on how to get promoted and on how to 'get ahead'.  

I wasn't prepared for what the Drill Sergeant said next.

The key to being promoted in the Army is simple: Follow through.  

Most soldiers don't worry about perfecting the fundamentals: Shining Boots, learning their Common Tasks, or any of those other things that make a soldier a look like a soldier.  After a soldier graduates from Initial Entry Training (Basic Training + MOS (Job) Training), they are assigned to a unit.  At that point, whatever discipline they have is a combination of their supervisor's dedication and their own.  As the Drill Sergeant pointed out to us, it's that personal dedication to completing a task that separates the 'ok' soldiers from the really good ones.  The soldiers that shine their boots, keep their uniforms pressed, and look the part end up getting promoted faster in the Army.

The same holds true in Software Development.  Very little of our job is actually coding.  Most of what we do is spread among various non-coding responsibilities: Managing User expectations, taking responsibility for software failures, collaborating with the users, other development teams, and the QA team.  Most software developers are great at being programmers.  But when it comes to explaining things in a way a user can understand, we don't fare so well.  It's bad enough that almost every job posting for a developer includes:

Exceptional verbal and written communication skills. You will need to be able to communicate complex technical concepts to the US and offshore development team, and communicate status, issues, and risks to our leadership team.

We're so bad at it (collectively) that an entire industry has been spawned to bridge the gap between software developers and business users.  You may remember this clip from Office Space:

In a recession, and with the smartest minds believing this is going to turn into a depression, it's time to move out of our comfort zone and follow through with the non-coding parts of our profession.  We don't have the luxury of avoiding human contact any longer. If you want to be a successful (and employed) programmer, you must learn to follow through.  Without that follow through, you may find yourself unemployed or worse, unmarketable.


View Comments: Comments (1) |

Twitter is a neat little tool. I like it. I use it as a micro-blogging service, and it gives me a chance to get an up-to-the-minute fix on technology and programming. For instance, in the last week these are some of the items I've found on Twitter:

 

I've also read countless blog posts by people I've follow, posted pictures on twitpic, and complained about bad User experiences.

Each week is normally chock full of interesting items and fun items. If you want to learn more about twitter, I recommend reading Brent Ozar's book on Twitter: The Simple Twitter Book.  He explains twitter much more clearly than I can (just not in 140 characters).

 


View Comments: Comments (0) |

April 8, 2010

I grew up in a transition period. A period that children didn't wear bicycle helmets, we played in creeks, woods, and other 'unsafe' areas, and apart from bumps and bruises, we ended up just fine. Then something happened. Parents stopped letting children play outside, children wore more padding than a football player to 'play dates', and everyone suddenly got more paranoid about safety.  Not surprisingly, people still get hurt, maybe even moreso. So it's a surprise to learn that there is an experiment in place to go in the other direction:

For a number of years now, a number of cities in Europe have been experimenting with the removal of all traffic signs – including traffic lights, stop signs, speed limit directives – and with surprising results. Various towns in the Netherlands, Germany, Belgium, Sweden, New Zealand – even the UK! – have joined in the experiment. Contrary to the expectations of those who might expect multi-car pileups throughout the cities, traffic accidents have been dramatically reduced (in one town, dropping from about eight per year to fewer than two).

The architect of this experiment, the late Hans Monderman, is quoted to have said, "it is dangerous, which is exactly what we want":

"Unsafe is safe" was the title of a conference held on this practice. Monderman added that this effort "shifts the emphasis away from the Government taking the risk, to the driver being responsible for his or her own risk." Equally significant, drivers now focus more of their attention on other motorists – taking visual cues from one another, informally negotiating for space, turning into an intersection, etc. – instead of mechanistically responding to signs and electronic machines.

Monderman stated: "When you don’t know exactly who has right of way, you tend to seek eye contact with other road users. You automatically reduce your speed, you have contact with other people and you take greater care." He added: "The many rules strip us of the most important thing: the ability to be considerate. We’re losing our capacity for socially responsible behavior." In words so applicable to the rest of our politically-structured lives, he declared: "The greater the number of prescriptions, the more people’s sense of personal responsibility dwindles." Monderman expressed the matter more succinctly in saying: "When you treat people like idiots, they’ll behave like idiots." (emphasis mine)

It boils down to this: If you want people to act in a safe manner, remove the safety factor.

For software developers, we've heard it in the religious wars between managed languages and unmanaged languages, and in the erroneous assumption that managed languages do not have memory leaks. I don't have any solutions, although I believe the answer leans towards 'Unsafe is safe'. Take away the illusion of a safety net and programmers (and people in general) will start paying more attention to their work. You won't have any C# 'Slap this together' apps, but is that really a bad thing?

Bonus: Cracked.com has an article out today on 6 Scientific Reasons People Drive Like A-Holes. Check out reason #4.


View Comments: Comments (2) |

Recent Comments

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.