<< back to the main blog page

How Not To Code, for Software Engineers

Spaghetti spiralIf you have ever taken a programming class in college or been on a job interview as a prospective programmer, you have likely been subjected to intentionally confusing code segments and given the task of determining what they do. Sometimes the code segments appear simple, but have a catch to them.  For example, in C++, what is the return value of this function? #define square(a) (a*a) int TestFunction() { return square(8+2); } If you said 100, you are incorrect.  The reason is that when square is called, it expands to 8+2*8+2.  Order of operations dictates that this expression is evaluated as 8+(2*8)+2, which adds up to 26. Now, when you encounter confusing code, or, spaghetti code, in real life, that is obviously a bad thing.  So here are some of our tips on how not to code:
  1. Repeatedly query the database when one query will suffice. Sometimes, you only need data conditionally.  For example, maybe you only need to look up the state associated with a zip code if the customer is from the US.  The right way to handle that need is with an OUTER JOIN.  The wrong way to handle it is to loop through your result set and then one by one look up the state where applicable.
  2. Create an object at the top of a function and delete it at the bottom. Unfortunately, .NET gives you no choice in the matter – one of its least appealing features when compared with C++ is that it eliminates a lot of your opportunities for writing efficient and proper code.  But for those who still enter the C++ world from time to time, if you don’t plan to persist an object after the function terminates, declare it on the frame, not the heap.
  3. Don’t comment your code – if only you know how it works, it’s job security! Well, the better job security is to deliver a good product to your customers – it will make them want to come back.
  4. Create 1000-line functions. While there is no magic number on how long is too long for a function, if you are seeing 1000-line functions on a regular basis, you may need to think about dividing them up.
  5. If it compiles, ship it! Whether it is the pressure of deadlines or the arrogance that “my code is perfect”, time and again software is published with bugs that leave you wondering, “did they even try it before sending it out?”
What are some other bad coding habits you encounter?  Let us know in your comments. image credit: Paolo Piscolla

Wednesday, July 27, 2011 written by David Torbert
Tags:  .NET, bad coding habits, C#, code compilation, coding, database, function, job security, object, OUTER JOIN, proper coding, software engineer, software testing
Categories:  Technology
Visitors: 502