Archive for May, 2010
10 Ways To NOT Suck At Programming
14Recently I wrote a therapeutic rant for myself, called “10 Ways To Suck At Programming“. The article got syndicated to some link sharing sites and picked up quite a bit of traffic and comments. The comments here on my site were, for the most part, nice. Comments elsewhere were a mixed bag with many people saying the sarcastic nature of the post wasn’t helpful. While I didn’t see it as sarcastic (after all, it was quite literally telling you how to suck), and even though I’ve written many, many helpful technical articles that did nothing but collect dust, I figured I would take a shot at offsetting my previous rant with real steps programmers can follow to make themselves better.
Obviously, this is not a comprehensive list and most experienced programmers should already be well versed in what’s here, but it’s a decent start for newbies and probably a worthwhile reminder to some of the more experienced.
… and it will be interesting to see if an article intended to be helpful gets as much traffic as a 20 minute rant. ;)
#10 Store settings in a configuration file
Configuration files are a necessity in today’s programming world. With most applications connecting to databases, e-mail servers, file shares and other outside resources it’s imperative that a good programmer store any information that has a possibility to change outside of the release cycle of the application in a configuration file. This will allow the application’s settings to be changed without having to recompile (retest, redeploy) the application.
It is important, however, not to overuse configuration files. Some things belong, some things don’t; and experience is really the best way to know which is which. You can ask yourself, “Is this something that will likely change in the future?” If the answer is yes, consider putting it in a configuration file. The more often you can change the behavior of your application without having to recompile it, the more often you’ll look like a hero.
Examples of good information to store in a configuration file:
- Database connection strings
- SMTP server information
- Any standard to / from e-mail addresses
- File upload / download / archive paths
#9 Scope and store your variables
Databases are awesome tools and nowadays pretty much any application you’ll be asked to develop will use one of some sort. However, when thinking of application performance database access and transactions are very expensive operations. With that in mind a good programmer will access the database as few times as possible in order to fill the needs of the current application request.
One way to facilitate this noble goal is to store any information that your application needs in memory once it has been retrieved from the database. A “get once, use often” approach can go a long way towards helping with performance (and to a lesser degree code readability). Some information that is used so often that is even worth storing as a session variable in order to eliminate a request (database, disk, whatever) altogether. Be careful with those, though, as they are often targeted for hacks and should never be solely depended on for functionality and should never contain any private information.
#8 Never use arcane plugins
Plugins and third-party code can make development go much, much faster. Often times you can get more complete functionality by using them but there are trade-offs for this convenience.
- You have to learn to think like the person who wrote the plugin in order to use it
- You usually don’t know how the internals work
- They’re almost never meant for the exact situation you’re in
With all that said, the right add-on or plugin can be a life saver and you must, must, must be careful when evaluating whether or not to use one. Here are some questions to ask to help decide whether a plugin is right for your app:
- Does it do everything I need exactly as I need it right out of the box?
- Is it well documented?
- Does it have an active user and support community?
- Has it been updated to coincide with major platform releases?
- Is the documentation in your native language (yes, seriously)?
- Will it take longer to write the functionality myself than learn to work with this plugin?
- When I (or someone else) inevitably has to maintain or change this app in the future will it be easy to work with or around this plugin?
If the answer to any of these questions is “no” you should be wary.
#7 Always remove unneeded functionality
This one kind of comes with a caveat: every programmer should know to use a good and dependable source control tool. Even if you are the only person working on the code, a good source control tool can (and likely will) prove to be a life saver at some point. You’ll cruise along not even knowing you need it and then BAM – you implement sweeping code changes that break everything. If you’re using a source control tool correctly, undoing your changes should be fairly quick and painless. If not, you may have just lost a client or a job.
With that in mind, try to never, ever leave unneeded functionality in your code base. If you have written a great piece of functionality that is no longer needed delete it immediately.
When you’re actually making changes that steer you away from existing functionality you understand why you no longer need the functionality and you likely have an idea of what else it touches. When you come back in six months, after seeing two or three other projects, you will likely have NO idea why that functionality wasn’t previously removed. You’ll think, “Boy, I didn’t remove this, something somewhere must be using it.” This problem compounds itself when you’re forced to start writing code around undeleted, unnecessary functionality. So in the end it’s easier to just remove code and keep your code base clean.
#6 Always consider performance
What makes a good programmer? The ability to effectively juggle the following points and still deliver timely, effective solutions:
- Performance – is the code minimal and fast?
- Scalability – is the code able to be expanded upon easily?
- Manageability – how quickly can modifications be evaluated, estimated and made?
The preference for which of these to focus on first differs from programmer to programmer and often from project to project. This is part of what gives each programmer their individual style. But good programmers always consider all three, no matter the situation. Readability falls under manageability, abstraction falls under scalability and everything falls under performance. So no matter what your programming personality and style is, you should be considering performance.
I’m not (necessarily) referring to spending hours pouring over 10 lines of code to make sure it executes as quickly as possible. I’m talking about taking a solid fundamental approach to gathering and manipulating data that doesn’t do any one piece of functionality more times than absolutely necessary. #9 above eludes to this, but to go a little further:
- Get your data once and use it in as many places as possible before disposing of it.
- Have the absolute minimum amount of functionality inside loops.
- Never perform accesses (disk, database, service) from within a loop unless absolutely necessary.
- (In strongly typed languages) Know and use appropriate data types.
- (In web apps) Perform as few server requests as possible.
If you think of things like this from the beginning of your project you are less likely to have performance issues in the end. If you don’t agree with me now that it’s worth the initial extra effort you will after you spend 4 weekends straight rewriting poor performing code because you tried to save 10 minutes on the front end.
#5 Never nest major logic / functionality in loops
I mentioned this one under heading #6 above, but it bears repeating. Loops are often the heart of any application, but they will absolutely kill your app if used improperly. So you must be wary of anything that falls into a loop.
Loops are something we have to use often, so every good programmer should know how to abstract functionality out of a loop (see #1 below for a simple example). Besides the performance hits, tracing through functionality that is inside of a loop can be much more difficult because of all of the variables that come into play while looping. Modern debuggers help tremendously with this task, but better tools shouldn’t excuse poor programming practices.
When you have time to review your code, start by reviewing loops and seeing if anything can be moved outside of them.
#4 Document effectively
There is a school of thought among some programmers that says, “Either you can read code or you can’t, why should I document it for you?” And while this is true in theory, in practice adding appropriate documentation inside code makes it far, far easier to maintain.
Proper documentation is a skill and overdoing it is almost as big of an annoyance to those trying to maintain code as not doing it all. Consider the following:
- DO – denote reason and logic
- DO NOT – denote functionality or process
What that means is: tell the future programmer looking at this code why you did something, not necessarily how. The “how” is the stuff they should usually be able to read on their own (unless you have to do some crazy, non-standard stuff). More often when looking at the code they need to know “why” you did things a certain way. Consider the following simple example:
1 2 3 | for (int i = 0; i < var.length; i++) { doSomething(var[i]); } |
Now let’s consider two commenting options:
1 2 3 4 | // iterate over each var for (int i = 0; i < var.length; i++) { // increment i if it's less than vars.length doSomething(var[i]); // do something with the var at position i } // finish the loop |
- or -
1 2 3 | for (int i = 0; i < var.length; i++) { doSomething(var[i]); // mark inactive vars for deletion } |
Now the first one tells you what is happening, about as pointlessly as a voice-over in a movie saying exactly what the characters on screen are doing. The second one assumes that you know what is happening functionally and instead just tells you what’s going on logically, which is far more valuable information when you’re in “put out the fire of the forest variety” mode. In the first case, the future programmer would need to look up doSomething(var) and figure out what it was accomplishing. In the second version that information is at hand and valuable.
Which would you prefer if you got a call from an executive at 4:45PM on Friday that forced you to review this code?
#3 Use effective and logical variable names
There are a LOT of thoughts on this one and almost every programmer has a slightly different way of doing it. So I’ll try to be ambiguous so we don’t start a war over it.
It is important to consider your variable names carefully. Sometimes having the data type as part of the name is appropriate (intId) and sometimes that sort of thing can be inferred (id). Either way, the name of the variable should hint towards the usage of the variable (note that “id” was in both). Names like (vulSpok) and (humKirk) are not useful.
Now possibly just as important as choosing your style of naming variables carefully is being consistent. As a programmer your code will have a certain “style” that others who inherit your code will have to learn in order to quickly and easily maintain your code. That “style” may not be the same as theirs, but as long as it is consistent (and logical) you’ve done what you can do.
#2 Catch errors, or don’t
Let me start by saying that I know, academically, all errors should be caught and handled gracefully. Let me also say that realistically, that almost never happens when deadlines are looming.
Hopefully the days of “Dr. Watson encountered an error” are behind us for good. Most modern platforms will let applications die with a pretty decent error message. So while it may not be ideal, letting errors fall through to the default error handling is better than manually mishandling the errors. On internal or limited usage applications this can actually provide a pretty good idea of what the actual error is and where to start looking to fix it.
Now in an ideal world, programmers would have time to code a catch for anything that went wrong and do something cool, super-ninja style. So if you have time and budget you should catch all possible errors and handle them. If not, don’t catch them at all.
Just never, ever catch errors and do nothing.
#1 Never duplicate functionality
Reusable code is the holy grail of good programmers. A good programmer should always be on the lookout for a way to write functionality once and then use it all over the place. The benefits to this are too numerous to count.
So what is reusable code?
Let’s say, using our example above that you need to loop through your vars and doSomething() with them. You could do it this way:
1 2 3 4 5 6 7 8 | for (int i = 0; i < var.length; i++) { // mark inactive vars for deletion if (!var[i].isActive) { var[i].readyToDelete = true; } else { var[i].readyToDelete = false; } } |
- or -
1 2 3 4 5 6 7 8 9 10 11 | private void doSomething(var) { if (!var.isActive) { var.readyToDelete = true; } else { var.readyToDelete = false; } } for (int i = 0; i < var.length; i++) { doSomething(var[i]); // mark inactive vars for deletion } |
It ends up being 3 extra lines of code in this example that will save you 4 lines of code each time you use it somewhere else. So the first time you re-use the code in this rudimentary example you’ve saved yourself 75% effort across the board (coding, debugging, refactoring, etc). Pretty nifty, huh?
Additionally, if you ever need to change the evaluation logic to, say, make sure that there weren’t any records that may be orphaned by deletion, you could change that logic in a single place and it would work everywhere throughout your code.
If you have any major items to add, feel free to do so in the comments. If I get enough good ones perhaps I’ll update this article to include them.
10 Ways To Suck At Programming
122I recently inherited a web app from a dirty, nasty, stinking contractor that claimed to be a competent enough programmer to be left alone to get things done. Unfortunately, we took him at his word. Functionally, most of the web app seemed to work at first glance. However, once the client took over the reins and actually started using it things went downhill fast. The contractor disappeared after payment (die reputation DIE!) and I was left to try and get things working properly and performing up to snuff while the client limped along with what they had been given.
I decided to document a few of the things that I found wrong along the way. These are really just things that every good programmer should already know to avoid… but obviously some people need to be reminded (or taught).
Update – 05.18.2010 – Some people thought that this article was too sarcastic. While I thought it wasn’t sarcastic at all, it does exactly what the title promises and teaches people to suck, I’m always game for being constructive. So I wrote an offset to this article – 10 Ways To NOT Suck At Programming.
#10 – Don’t store settings in a configuration file
When you’re writing a sizable application, things like database connections and SMTP server information will be used throughout the app. The best way to make sure your app is entirely immune to maintenance is to redefine those little bits of information every time you need them. So instead of putting them in the configuration file (Web.config or whatever) just leave them in your compiled code. Whoever inherits the app will thank you for sending them on a hunt through thousands of lines of code to change which SMTP server is being used. What’s even more fun is when the next programmer only finds 14 of the 15 places where you’ve used this code and a single instance somewhere deep in the app silently breaks hundreds of times without anyone knowing. Sometimes it’s helpful to build the variables in inconsistently concatenated strings. The repeated and more frequent interaction between the new developer and the disgruntled client will help strengthen their relationship. And if you don’t hook up that love connection, who will?
#9 – Don’t store variables in [any] memory scope
One of the great things about databases is they store your bits of information and allow you to access them whenever you need them. To make sure your app is as terrible as possible, you’ll want to be sure and access the database every time you need a bit of that information. The more common the information is that’s needed, the bigger win you’ll have by making a new database connection to get that information. Non-sensitive user information is a great use of this prinicple. Don’t worry about defining a user’s information, such as “isAdmin” to a variable and using it throughout the current request. Just query the database each time you need to know anything about the user. After all, the client paid for that database, we’d better get as much spin out of it as possible!
#8 – Use arcane plugins
If the client has a non-standard request, such as formatting a table in a way that is outside the abilities of your WYSIWYG editor (colspan are hard). You should definitely hit up the interwebs and search for random unsupported closed source plugins to do the work for you. If you would spend almost an entire hour writing it yourself, you should spend at least 3 hours searching for and getting a plugin that does roughly but not exactly the same thing. Bonus points if you can get a plugin that doesn’t do what you need, but offers 15MB+ of functionality you have no use for and include it without getting caught. Bonus bonus points if the documentation for that plugin is in a language not native to your market (for example, if you’re working in an English speaking shop look for plugins that are documented only in Spanish or German).
#7 – Never, ever remove functionality
Over the course of developing a large application there are bound to be times when functionality you were working on proves itself to not be needed. Now, to be sure to leave plenty of dead ends for those who come behind you to get lost in, never delete that functionality. Maybe even comment out random parts of it, or even hundreds of lines of it at a time, but don’t delete it. Imagine the hours of fun the future-crew for this app will have while they trace through this functionality only to find that it isn’t needed! If you can make it seem needed, without actually needing it, it will even keep them from deleting it themselves… This way the fun is exponential! Oh, a bonus on this one… if your project uses source control and multiple server environments, be sure to have a different version of your files (both code and compiled) on each server and source control. This way no one will know which one is live in production and who doesn’t love a good round of Code Russian Roulette?
#6 – Screw performance
Large applications, you know, the ones that pay the bills, are generally needed because they deal with large amounts of data. Sure, during your development process you’ll create 20 or so test records. Take my word for it, there’s no need to even worry about what happens once you get to 25 records, or even 1,000! Obviously, all pagination will work just fine and performance will never take a hit. So if it compiles, ship it!
#5 – Nest major logic/functionality in loops
Now obviously, we’ve already covered #6 so we know that we’re working with large amounts of data. And inevitably, there will be plenty of looping through that data to do work with it. If you want to make sure your application is really difficult to maintain and completely unusable to the client, you should embed major functionality and/or logic inside of these loops. For example, instead of running a query against the database to get ALL the data you need, storing the data in memory and working with the variables in memory during your loop, just get all the data except one field up front and loop through it… then on each loop you should get all the data again, and now include your extra field. This will guarantee that your app will never survive more than 5 concurrent users (re: #6). So for review: Get data > create loop > get data > work with data. I’m sure you see some room for added idiocy in that process, so feel free to nest this idea as many times as you want.
#4 – Document NOTHING
Look, documentation is for morons. I mean either you can read the code or you can’t, right (this was actually said to me at one point)? Of COURSE the next programmer will be able to read the code. What’s really fun though, is when you document absolutely nothing, especially not your intent. It pays to keep them guessing. You’re mysterious, like a ninja. No need to let someone get all up in your grill, knowing everything about what you were trying to do. Because if you document what you’re trying to do and then don’t end up doing it… well… that’s just embarrassing.
#3 – Use and reuse illogical variable names
There’s going to be a LOT of variables needed to work on this app, so you’d better choose a movie or television show with enough characters to use all the names. Lord of The Rings, Star Wars and Family Guy are all good choices for this. Maybe you can even form relationships with the variables. That way, you never have to kill them! You can have variables that are chameleons, changing their usage and values throughout processing and you can recycle them for something new each time you need a variable for new functionality. It’s like they’re growing up, evolving, right before your eyes! After all, you’re trying to be green and reduce your carbon footprint so recycling variables just seems like the responsible thing to do!
#2 – Catch all errors — and do nothing with them
Most languages / platforms nowadays have really good error handling built in. They’ll die somewhat gracefully and give enough details through the default error output to be helpful. You must not allow this to happen! Start off by wrapping nearly every tiny piece of functionality in a try / catch phrase. Then… inside the catch… put a comment, like “// It borked lawl.” This will ensure that if anyone wants to work on this app, they’d better spend the time getting to know the app and it’s adorable character variables before they start wrecking the app altogether.
#1 – Duplicate functionality
If the client tells you that they need two pages: One for an administrator that has all of the details on an item along with a button to delete it; and one for a regular user which has all of the details on an item without a button, you should create multiple pages to accomplish this. In fact, if you can make pages for each user group that would even be better. Making a separate page for each user is the ultimate success. So ninja up and get serious on this one, because it’s your last line of defense against the teeming hordes of qualified individuals who will inevitably be bewildered while trying to update your carefully constructed Pandora’s box of an app.
This is by no means a comprehensive list. On this project alone I could name 10 more things that could make you suck. But I’ll leave it at 10 for now. Anyone have more to add?