Krista's Coding Corner


Hard coding, don’t do it!

I have some drawings in this site, and if you watch carefully, you can see that they hardly ever are inside boxes / rectangle shaped. Like this bunny here:

This effect is not made with painting the picture background with my page’s color but keeping the background of the drawings transparent. This way if I ever decide to change the colors in this page, I don’t need to go through all my drawings.

Same thing applies with variables and other stuff: if you don’t have to, don’t carve anything into stone. Make it easily changeable. Use variables. If you process data in steps (like step 1: remove mean value from your data, step 2: see if there is some periodicity there), make it so that you can always take one step out. Maybe the best way would be to have all these steps as subroutines that don’t have dependencies from other routines. Generally speaking: it is always a good idea to have no dependencies between subroutines. At some point you will change something minor just to notice that this minor change became huge rewriting task.

‘Magic numbers’ that are hard coded into the code are extremely bad move: later it may be hard to know why they are there, what they cause and why it is exactly 42. Don’t trust that you make comments that are always up-to-date or clear in any other way (comment “here are some magic numbers” starts to be a bit worn out...).

Path names, file names... These will change. If you are using some file name or path in many places, absolutely make it a variable that is defined in some easily found place. Otherwise you will in some point forget to change one of the names/paths and wonder where it went wrong. Also path name is quite dangerous if you move your software into other directory or even another computer: this will break your system.

Not using an algorithm but if-sentence jungle or switches. Especially if you have just begun coding, it is easy to fall into this trap: you aren’t sure how to make some algorithm, so you just replace that with something like this:

# user gives a number between 1 and 2000:
	user_input = raw_input()
# changing the input into real number, not just a string
	user_input = int( user_input )
(# here we should check that the input really is a  number and between 1 and 2000... :) )
# return true if the number is divisible with 3, and false if it isn't divisible ith 3.
# a bad way to do this:
	if ( user_input == 1 ):
		return false
	if ( user_input == 2 ):
		return false
	if ( user_input == 3 ):
		return true
	if (user_input == 4 ):
		return false
# a proper way to do this:
	if ( user_input % 3 == 0 ):
		return true
		return false

In short, you will want to change something eventually, make sure that it is easy to do so :) And trust me, it takes only little time to do it right in the first place compared to what it takes when you fix your laziness (and then you will be tired, irritated and out of time).

blog comments powered by Disqus