Coding principles helps you to maintain good coding practice along with concrete product development. Coding principles also helps you write excellent quality of code with huge difference to overall performance and scalability of your application. Following are the most important Coding Principles which can save a lot for you when you are writing quality application for you or your client. Ensuring these coding principles you can save development time, management time and conquer lots of other bottlenecks which generally arise in later development phases. You can also use the idea of PHP Design patterns which can speed up the development process by providing tested, proven development paradigms. This article is taken from two articles at programming4scientists.com with few modifications.
Don’t Repeat Yourself (DRY)
The concept here is that anything you use in your code should have a single, unambiguous representation. This means if you are storing a number, only store it in a single place (don’t have PI stored in three different places). Not only is multiple storage wasteful, but it multiplies your effort if you want to change, especially if you have to go hunting through several files to find where the numbers are defined. Multiple representations are also a great way to generate bugs if you forget to change some of them. This also applies to code; don’t repeat chunks of code that do the same thing – have a single version and put it in a function.
Test as you write
As much as possible, test your code as you write it. These tests will often be quick and easy ones, such as checking that the value of pi you’re using is really what it should be, but if you perform these little checks while you’re working on (and thinking about) that piece of code, you’ll save yourself a lot more effort having to come back later and fix bugs. You’ll find that you can perform a lot of simple tests very quickly as you go along; once you’re in the habit, you really don’t spend a lot of time doing it. But the time you save yourself later on can be considerable. As well as informal testing, using a test harness and writing automated tests will help guarantee code you have already written keeps doing what you expect and helps prevent bugs you have already fixed from reappearing.
Reduce dependencies as much as possible
A dependency is a connection between two chunks of code, for example, using the same variable, and the more of these your code has, the more things you have to keep track of. When writing and debugging a chunk of code, the last thing you want is arbitrary other chunks being able to interact with it, because it’ll very quickly become unmanageable. Much better would be for each chunk of code to be highly de-coupled from the rest of the code, with only very specific connections to the rest of the program. This keeps things much simpler and easy to manage. In practice, this means things like compartmentalising your code into chunks (which you were doing anyway, right?), avoiding global variables (with the possible exception of explicitly fixed constants such as PI) and the like. If you’re feeling keen, writing object oriented code is excellent for this, as this has encapsulation built into the process.
Validate your data
At some point, someone will feed garbage into your carefully crafted code. In fact, part of your testing should be feed garbage input into your code to check that it recognises it! If your code is validating the data it is given then it should be able to deal intelligently with this, even if “intelligently” means “crash but tell the user what has gone wrong and why”. Assertions are an ideal way to make the program stop as soon as something is wrong. They work by ‘asserting’ that something is true and if it isn’t then the program stops.
Assert(x >= 0)
If the variable x is less than zero then the program will immediately stop at this point.
During development this kind of information is invaluable and since the program has stopped at the first point it spotted something wrong, you don’t have to work backwards from a garbage final output to find where the program failed.
Handle errors nicely
Asserts are a great way of validating data and are very useful during development, however once a program is in the hands of the users you want your error handling to be a little nicer than stopping the program immediately. There is nothing more frustrating than a program that just dies without warning or explanation. Most modern languages have support for handling problems your code encounters using Exceptions. Exceptions are generated when something goes wrong and bubble up until they are caught and dealt with. The advantage of exceptions is that they can be used without your code having to pass around error-code results from function to function. Using exceptions properly is a complex subject, because the exception handling represents a different path through the code, but a simple rule of thumb is: ‘Throw an exception when a problem is first encountered, catch it at the first point that can deal with it’. In programs with a GUI (Graphical User Interface) this usually means there is a catch-all at the user interface layer that displays a message to the user (or something similar) before attempting to save the data and then shutting down.
Keep It Simple
The simpler your code is, the easier it is to construct and maintain. So, subject to the constraints of our objectives, the simpler you can make your code the better. This has a connection to premature optimisation (see this post ), because optimised code tends to be less simple. We think a reasonable rule-of-thumb is that unless most simple way of doing something will be obviously too inefficient, it’s worth trying. you can always change it later and, because it’s simple code, this shouldn’t be too hard. One way to describe this is to paraphrase Albert Einstein: Code should be as simple as possible, but no simpler.
Tidy up after yourself
Once you start to leave one or two things unfixed, it becomes much easier to leave “just one more”, and soon your code is a wreck. There should not be a single “broken window” in the code you’re building (the phrase “broken window” comes from a study that showed that a major indicator of the state of a building was a single broken window; once one is broken, people care a lot less about maintaining the rest, it seems). The book “The Pragmatic Programmer” has a nice description of this.
Learn new tools
If all you have is a hammer, then all your problems tend to look like nails. The way to avoid this is to have more than one tool. In general, you want to have a good, broad selection of tools with which to write your code. A good way to acquire this is to try to learn the occasional new tool as you go along. These can be useful pieces of software, new techniques or whatever; the important thing is that it gives you at least one more good option for writing your code.
Maintain your flow
Flow is a psychological state that you get into when you’re absorbed in your work (sportsmen call it being “in the zone”). Have you ever gotten really into your work, so much so that suddenly an hour has passed without you noticing? That’s flow! In this state, you tend to be very productive and very focused on the task at hand. Therefore, you want to try to stay in this state for as much of the time as possible. It can take as much as 15 minutes to get into the flow, so it’s important to minimise things that will pull you out of the flow (once you’re out, that’s 15 minutes largely wasted). That means try to avoid distractions, turn off the e-mail alert beep, listen to music to block out background noise, turn off your web browser. Whatever it takes!
Make your code unsurprising
When someone glances at a chunk of code, they can often form a quick impression of what that chunk of code does. It is convenient when this impression is accurate; it can be a real problem if the impression is misleading and they makes changes to the code before they realise. The ‘principle of least surprise’ is that you should try to make your code’s actual functionality as close as possible to the typical quick impression. Or, to put it another way, you should try to write your code so that it communicates its functionality accurately in a very short (pain-free) amount of time. This means doing things like picking informative variable/function names, writing informative (and succinct) comments, and making the layout easy to read.
Don’t program by coincidence
‘Programming by coincidence’ is what happens when you “just get started coding” without thinking about what it is you actually want to achieve. You write some code and it seems to work. Great. So you write some more. That also seems to works. So you keep on doing this until one day you add some code and your software falls over. And you have no idea why. Think of this as the coding equivalent of a random walk; sure, you’re moving, but are you going to end up in the right place? To avoid this, realise that a bit of planning and careful thought (including as the project progresses) is a very good thing.
Disordered code is bad, because it’s more likely to contain bugs. Higher entropy is more disordered which is bad. So you should try to keep the entropy of your code as low as possible. This means taking care to keep things neat and tidy as you write the code. It also means fixing bugs and refactoring messy bits of code. One important aspect of code entropy is that any time you make a change to your code, the level of entropy will tend to increase (unless you’re very careful; fixing a bug, for example). If you’re constantly re-writing your code, you’ll be introducing new bugs all the time and invalidating the testing you’ve done on that code. So bear in mind that a bit of stability in your code is a good thing.
- Let’s Re-Use our code as there is no point writing code when you can use some that’s already been written? Reusing existing code can be a great way to save great big chunks of time.
- Lets Rule Out any sort of dependencies or minimize it if not possible to rule out completely.
- Test your code while you write to ensure bugs already fixed or appearing.
- Use assertion for validation of data.
- Keep error handling on top and don’t forget to throw exception until you are in staging environment. Of course you won’t show exceptions in production environment.
- Keep the code simple so it is easier to construct and maintain.
- Don’t leave anything broken and take initiative to fix yourself rather than wait for someone to figure the problem out for you.
- Learn new tools and use then frequently. Tools can help you in various needs i.e. AJAX, Testing etc.
- Maintain your flow in development.
- Plan properly before you start coding, your goal should be very clear in your mind.
- Make sure you are working for a stable code with very little bugs
All the above points don’t take much effort, once you get used to them, and the time (and headaches!) they can save you make it well worth the effort!
Please post your experiences with the above coding principles. If you like this post kindly subscribe to our RSS for free updates and articles delivered to you.