10 Tips for Better Coding

Writing code can sometimes be the most difficult part of any software development process. If you don’t organize everything from the start – especially for big projects — the coding processes and code management afterwards may end up not just time consuming, but also a big headache.

Good code is maintainable, reusable, and testable. The following tips address how you and/or your development team can handle various coding tasks and how to keep everything as neat as possible. I will introduce you to some “best practices” that will help you write better code and help make you and your team happy and efficient.

1. Use a Coding Standard

It’s easy to write bad, unorganized code, but it’s hard to maintain such code. Good code typically follows some standard for naming conventions, formatting, etc. Such standards are nice because they make things deterministic to those who read your code afterwards, including yourself.

You can create your own coding standard, but it’s better to stick to one with wider-acceptance. Publicly maintained standards like Zend Framework Coding Standard or soon to be PSR-1 Coding Style Guide instead, it will be easier for others to adapt.

2. Write Useful Comments

Comments are crucial. You won’t appreciate them until you leave your thousand-line script for a couple of days and return to and try and make sense of it. Useful comments make life easier for yourself and those after you who have to maintain your code.

Write meaningful, single line comments for vague lines; write full parameter and functionality descriptions for functions and methods; for tricky logic blocks, describe the logic in words before it if necessary. And don’t forget, always keep your comments up to date!

3. Refactor

Code refactoring is the eighth habit of highly effective developers. Believe it or not, you should be refactoring your code on a daily bases or your code is not in good health! Refactoring keeps your code healthy, but what should you refactor and how?

You should be refactoring everything, from your architecture to your methods and functions, variables names, the number of arguments a method receives, etc.

How to refactor is more of an art more than a science, but there are a few rules of thumb that can shed some light on it:

  • If your function or method is more than 20-25 lines, it’s more likely that you are including too much logic inside it, and you can probably split it into two or more smaller functions/methods.
  • If your method/function name is more than 20 characters, you should either rethink the name, or rethink the whole function/method by reviewing the first rule.
  • If you have a lot of nested loops then you may be doing some resource-intensive processing without realizing it. In general, you should rethink the logic if you are nesting more than 2 loops. Three nested loops is just horrible!
  • Consider if there are any applicable design patterns your code can follow. You shouldn’t use patterns just for the sake of using patterns, but patterns offer tried-and-true ready-thought solutions that could be applicable.

4. Avoid Global Code

Global variables and loops are a mess and can prove problematic when your application grows to millions of lines of code (which most do!). They may influence code elsewhere that is difficult to discern, or cause noisy naming clashes. Think twice before you pollute the global namespace with variables, functions, loops, etc.

In an ideal case, you should have no blocks defined globally. That is. all switch statements, try-catch, foreach, while-loops, etc. should be written inside a method or a function. Methods should be written inside class definitions, and class and function definitions should be within namespaces.

5. Use Meaningful Names

Never use names like $k, $m, and $test for your variables. How do expect to read such code in the future? Good code should be meaningful in terms of variable names, function/method names, and class names. Some good examples of meaningful names are: $request, $dbResult, and $tempFile (depending on your coding style guidelines these may use underscores, camelCase, or PascalCase).

6. Use Meaningful Structures

Structuring your application is very important; don’t use complicated structures, always stick to simplicity. When naming directories and files, use a naming convention you agree upon with your team, or use one associated with your coding standard. Always split the four parts of any typical PHP application apart from each other – CSS, HTML Templates/Layouts, JavaScript, PHP Code – and for each try to split libraries from business logic. It’s also a good idea to keep your directory hierarchy as shallow as possible so it’s easier to navigate and find the code you’re looking for.

7. Use Version Control Software

In the old days, good development teams relied on CVS and diff patches for version control. Nowadays, though, we have a variety of solutions available. Managing changes and revisions should be easy but effective, so pick whatever version control software that will work best with the workflow of your development team. I prefer using a distributed version control tool like Git or Mercurial; both are free software/open source and very powerful.

If you don’t know what version control software is, I’d recommend reading Sean Hudgston’s series Introduction to Git.

8. Use Automated Build Tools

Try to use tools like Ant or Phing to get your source prepared, compressed, and deployed. Building your whole application with a single command is a marvelous way to prevent errors and omissions that are inherent when performing repetitive tasks, and is a generally core pre-requisite for automated testing strategies. I recommend using Phing, it’s a well-supported build tool for PHP written to mimic Ant; if you aren’t familiar with it, check out Shammer C’s article Using Phing, the PHP Build Tool and Vito Tardia’s article Deploy and Release Your Application with Phing.

9. Use Code Documenters

For large applications spanning several classes and namespaces, you should have automatically generated API documentation. This is very useful and keeps the development team aware of “what’s what.” And if you work on several projects at the same time, you will find such documentation a blessing since you may forget about structures switching back and forth between projects. One such documenter you might consider using is DocBlox.

10. Use a Testing Framework

There are a plenty of tools that I really appreciate, but by far the ones I appreciate the most are the frameworks that help automate the testing process. Testing (particularly systematic testing) is crucial to every piece of your million dollar application. Good testing tools are PHPUnit and SimpleTest for unit testing your PHP Classes. For GUI testing, I recommend SeleniumHQ tools.

Summary

In this article you saw an overview of some of the best practices for writing better code, including using a coding standard to unify code formatting across the whole team, the importance of refactoring and how to embrace it, and using professional tools like testing frameworks, code documenters, and version control to help manage your codebase. If you’re not following these tips already, it’s worth the effort to adopt them and get your team on track.

Image via DJTaylor/Shutterstock

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • ComGuo

    Hello!I’m a new Learner of PHP. After reading your article,I’ve learned more.And excuse for my poor English.Thanks~

    • Abdullah Abouzekry

      Hi,
      You are always welcome, stay tuned :)

  • http://www.php-tip-a-day.com Greg Bulmash

    Most PHP apps evolve to millions of lines of code? Really? Please cite a reference for that claim.

    And if that’s true, then where are the developers who are having to write thousands of lines of *new* code a day to generate all these multi-million-line PHP apps supposed to find time to go back and refactor old code?

  • http://www.drecomm.nl/ Hans Vos

    I would like to add that points 7, 8, 9 and 10 could be put under a single umbrella in the form of a continuous integration environment such as Jenkins CI. Such a system monitors your version control for changes and triggers a build when new code is committed.

    I have some experience with Jenkins jobs that trigger Phing builds for a bunch of tests such as code sniffing to make sure the developers adhere to the coding guidelines, unit testing and copy-paste-detection.

    The results off all these tests (usually XML files) can be interpreted by various Jenkins CI plugins to give you useful graphs of your code metric tests (e.g. failed unit test, number of code violations, etcetera). Definitely worth looking into.

    • Abdullah Abouzekry

      I agree with you about Jenkins and CI, it’s just great, but not all programming teams require a CI tool, however most require to take care of points 7, 8, 9 & 10.

  • http://www.vigsbo.com Kim Vigsbo

    @Greg: Its not uncommon to have that amount of code. I work daily on an enterprise solution with nearly 1.5M lines of code. The team has tools in place to constantly evaluate and refactor the code base. In addition, we have over 100,000 lines of CSS (and we are using Sass).

    • Abdullah Abouzekry

      Thanks Tim for the Citation :), I have myself worked on similar projects as well, and as you said this is not uncommon in enterprise applications.

  • http://www.roomallot.com Niyaz

    thanks for the tips. we were looking for a VCS and GIT could be the thing that we are looking for.

  • Sebastiaan Stok

    PSR-1 has been recently accepted, it consists of basics that anyone can follow and the advanced version that describes a more strict coding convention.

    If you want to check or even format your code to the PSR-1 standard, take a look at PHP Coding Standards Fixer at http://cs.sensiolabs.org/
    One other tip, use dependency management software where possible, this eases updating and resolving dependency of other components. The de-facto standard these days for PHP is Composer.

    • Abdullah Abouzekry

      Sebastiaan, Many thanks for your valuable tip!

  • http://www.webmentor.cr/ Marco Berrocal

    Hello,
    First of all thank you very much for your useful post. I didn’t know some of them.
    I have a question for you. I am about to embark on a mission in magnitude close to D-Day as far as coding is concerned. I am pretty novice to PHP itself but not novice to programming. I have a question, would you start with a framework or start coding by my own? Bear in mind that learning a new language can be intimidating.

    Cheers!
    Marco

    • Abdullah Abouzekry

      Hi Marco,
      If you have some time, I would recommend starting to code on your own (since you mentioned you are novice to PHP) that would give you a good opportunity to play with the language and master it, but if your mission time is critical and tight, I would recommend you go with one of the well known community heavy frameworks like cake, symfony, codeigniter…etc., so it all depends on you :)

  • Asad Iqbal

    Hi,
    This man is doing a great job on promoting development skills of php and its frame works.I like its every new tip.
    Thanks Brother
    A.I

    • Abdullah Abouzekry

      welcome bro :)

  • http://www.synocom.nl Rob

    Great topic. Thanks

    • Abdullah Abouzekry

      thanks, you are welcome :)