Archive for the 'Php' Category

Back to basic with the Try Catch statement

Over the last 2 months I have been quite busy at my new job, where I`m trying to raise the quality of code (just to mention one thing) - not only with our own code, but also with 3rdparty web applications that we have bought.

I have discovered a really annoying thing lately and that is people are misusing the Try Catch statement. At first I thought that this was something only relatively new developers did but it seems like some people continue to use it wrong.

Example 1

1
2
3
4
5
6
try{
 // lines of code
}
catch(){
 // do nothing
}

When you talk with them about this form of error handling, they usually come up with an argument like “We don`t want the application to fail” and it is valid point of view, but there are issues when following Example 1.

Not only is it what you call smelly code, it can also give a serious headache when trying to look for a bug in the system, because the above example will just let the program continue and hope that it will “complete” whatever operation it is doing.

Rule 1

First of all, it says something about that you are trying to handle some sort exception that shouldn`t be raised in the first place. Determine what causes the exception and either rewrite the code inside the Try Catch statement (even removing it completely) or fix the Catch() so that it handles the exception correctly (see rule 2 and 3).

Remember: Try Catch statements are among the biggest resource eating operations you can perform.

Rule 2

If you really need to Catch an exception make sure that you log it somehow.

1
2
3
4
catch(exception ex)
{
  LogException('something went wrong');
}

Rule 3

Rule 3 is an extension to rule 2

When you want to catch an exception, you should make sure that you don’t catch it with a non-specific exception like Exception. Exceptions should be handled as unexpected events that you intend to (or can) do something specific about. It doesn’t make sense to handle many different things, at the same time, with Exception, so is you want to catch a FormatException or SqlException, then you should use one of those instead, it also gives you a more precise idea on what to expect when reading the code.

Finally, consider whether your program really needs to handle exceptions, period. As Bjarne Stroustrup points out, sometimes the best response to a serious run-time error is to release all acquired resources and abort. Let the user rerun the program with proper input

- Code Complete (second edition)

You can read more about good code practise in Code Complete by Steven McConnell.

Become a better developer

Many have talked about how one could become a better developer and some of those people are on to some of the right things, but there are also some ideas which are totally ridiculous. I remember I once read that you should learn RoR (ruby on rails) because it looked pretty… wtf.. that wont make you better!! I won`t mention any names, because you know who you are, and no, I don`t have anything against RoR.

Ok, back to the point. What does it take to become a better developer? I have listed a few pointers that can make you better, if you really want it.

Read books

Every new developer knows that they have to read a book so they can make their first “Hello world” program, but that doesn`t make you a good developer. You have to read more than just one book; you actually have to read quite a lot. The reason for this is that the most important job a developer has is too solve problems with the use of software and you won`t impress many people with your “Hello world” program and if you know more about different technologies and so on, then you will become better to combine these technologies that will solve the problems in better ways.

Books I recommend

Learn by doing

Reading will get you going, but if that is all you are doing then you wont obtain any practical experience and without that your knowledge will be kind of useless. Another great thing about trying out the stuff you read about is that it will help your brain remember better, so create something, anything, with your newfound knowledge and keep doing it. You can also learn a lot from other peoples mistakes and if you want to see some of the more ridiculous solutions that some developers comes up with, then I suggest you head over to The Daily WTF (after you finish here of cause)

Be passionate

Reading and trying out things will get you fare, but since you are reading this, then I guess you want to get further then that. So here is one of the most important things. Every great developers have one thing in common - they are passionate about making software. They want to make great software and will go that extra mile so their code will be perfect. The passion is something that is natural for them, so if a “Hello world” program doesn`t turn you on just a little bit, then I would advise you to do something else with your life. I know it sounds harsh, but there is some truth in it and you can force yourself to become passionate.

Understand the mortals

If you want to achieve greatness in this line of business, then learn to understand the customers and also make sure that the customers understand you. One of the great problems in this business is the problem with communication between customers and developers and that usually results in a lot of unnecessary work and frustrations. I don`t believe that this is something that everyone can learn, but it doesn`t hurt if you work on it anyway.

Be humble

When software fails it will in 99% of the time be your own fault, don`t blame the users for putting in stupid data or clicking on something in the wrong order. This is probably a wide spread issue among developers and I believe that everyone once in a awhile will blame someone or something else for an error that they probably made (even I do it sometimes. A man gotta have his pride).

How to write better code

This might be somewhat controversial since everybody has there own opinion on how one should write code. Everybody likes there own way of writing code and this might be ok, if you are the only one who will ever work on it, but if you are a part of a team, then it is very important to now how to write code that everybody can understand without using to much time to figure out what a function, class or something else does.

This guide might only be beneficial for people who are beginners and are open minded about learning a few guidelines on how to improve their programming skills. I won`t go into the deeper aspect of programming because then I will end up writing a book and there has already been written too many books about that.

For the course of simplicity in my examples I will use Php as programming language.

How to write High-Quality functions

What is a high quality function? That`s a good question so let`s look at a function which has been considered as a low quality function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function DoSomething( $a, $user, $color, 
$total, $type, $time, $date, $street, 
$coordX, $coordY )
{
	$newtotal = $total * 1.25 / 30;
	UpdateProfit($newtotal);
 
	$n = 100;	
	for($i = 0; $i < 10){
		if( $a == 10 )
			UpdateUser($user);			
			NewColor($color[$i]);			
			}
			if( $a == $n )
				NewColor($color[100]);
			}

Can you see what is wrong with this function? Try to think about what could be wrong and why it is wrong before you continue.

  • The functions name (DoSomething()) doesn`t give you a single clue on what it is doing.
  • The function isn`t documented.
  • The function is poorly formatted. It is hard to se what belongs to what.
  • The function contains some strange numbers like; 1.25, 10, 30 etc.
  • The function has too many parameters. To keep it understandable, it must contain around 7 or less.
  • It seems that the function does more then one thing.

Pseudocode

The purpose of using pseudocode (more about pseudocode) might seem trivial to some (especially if you are an expert programmer) but it is an excellent technique you can use when you need to get a mental orientation of what your function is going to do. Once you have written your pseudocode then back away for a moment and think of what you have just written; does the code make sense? You could also try to explain what the function is going to do and have someone review your pseudocode. When you are ready to write the actual code, you don`t necessarily have to remove the pseudocode, it can be great as documentation for what the function does.

Good routine names

This might sound easy enough, but even though you understand what the function does (because you wrote it) it doesn`t mean that everyone else will understand it, and so they will have to look through the code to figure it out. A good function name clearly describes what the function does, and don`t be shy to make it as long as necessary.

Routines tend to be more complicated then variables, and good names for them tend to be longer. On the other hand, routine names are often attached to a object name, which essentially provides part of the name for free.

- Steve McConnell

Defensive programming

It may sound like a strange term but it basically means that you should take responsibility for your code and not let anyone mess with it. Protect your code from invalid, bad and corrupted data because then you accept that programs are being modified all the time.

Localize variables

Don`t declare any variables in the beginning of your code, if you first are going to use them in the end. If you keep the variables as close to the code that are using them, it enhances the readability of your code and thereby the understanding as well.

Variables

Use each variable for only one purpose, I have seen many use the same variables for different things and that will give you a serious headache when you need to debug your code. You should also remember to give your variables meaning full names and don`t leave unused variables in your code.

Research shows that the optimum average length for a variable name is 9 – 15 characters.

- Steve McConnell

Learn more from Code Complete

Next Page »