Code readability is a universal subject in the world of computer programming. It's one of the first things we learn as developers. This article will detail the fifteen most important best practices when writing readable code.
Diomidis Spinellis, author of Code Quality: The Open Source Perspective, lists the most important rules for writing sparkling code. Follow them, and your code will look professional, live long, grow smoothly, and earn your colleagues’ love (rather than swearing).
Diomidis Spinellis, author of Code Quality: The Open Source Perspective, lists the most important rules for writing sparkling code. Follow them, and your code will look professional, live long, grow smoothly, and earn your colleagues’ love (rather than swearing).
Best Practice List
- Use Naming Conventions
- Create Descriptive Names: Use long descriptive names, like complementSpanLength, to help yourself, now and in the future, as well as your colleagues to understand what the code does. The only exception to this rule concerns the few key variables used within a method's body, such as a loop index, a parameter, an intermediate result, or a return value.
- Use Commenting Conventions
- Commenting & Documentation: IDE's (Integrated Development Environment) have come a long way in the past few years.
- Use Coding Conventions
- Consistent Indentation: I assume you already know that you should indent your code. However, it's also worth noting that it is a good idea to keep your indentation style consistent.
- Avoid Obvious Comments: Commenting your code is fantastic; however, it can be overdone or just be plain redundant.
- Code Grouping: More often than not, certain tasks require a few lines of code. It is a good idea to keep these tasks within separate blocks of code, with some spaces between them.
- Consistent Naming Scheme: PHP itself is sometimes guilty of not following consistent naming schemes. First of all, the names should have word boundaries like camelCase (First letter of each word is capitalized, except the first word) or underscores (Underscores between words, mysql_real_escape_string).
- Be Consistent: Do similar things in similar ways. If you're developing a routine whose functionality resembles that of an existing routine, use a similar name, the same parameter order, and a comparable structure for the code body.
- Don't Overdesign: Keep your design focused on today's needs. Your code can be general to accommodate future evolution, but only if that doesn't make it more complex. Don't create parameterized classes, factory methods, deep inheritance hierarchies, and arcane interfaces to solve problems that don't yet exist—you can't guess what tomorrow will bring.
- Split Your Code into Short, Focused Units: Every method, function, or logical code block should fit on a reasonably-sized screen window (25–50 lines long). If it's longer, split it into shorter pieces. An exception can be made for simple repetitive code sequences.
- Use Efficient Data Structures and Algorithms: Simple code is often more maintainable than equivalent code hand-tuned for efficiency. Fortunately, you can combine maintainability with efficiency by utilizing the data structures and algorithms provided by your programming framework. Use maps, sets, vectors, and the algorithms that work on them, and your code will be clearer, more scalable, faster, and memory-frugal.
- Use Framework APIs and Third-Party Libraries: Learn what functionality is available through an API in your programming framework, and also what's commonly available through mature, widely adopted third-party libraries. Libraries supported by your system's package manager are often a good bet. Use that code, resisting the temptation to reinvent the wheel.
- DRY Principle: DRY stands for Don't Repeat Yourself. Also known as DIE: Duplication is Evil.
- Avoid Deep Nesting: Too many levels of nesting can make code harder to read and follow.
- Limit Line Length: Our eyes are more comfortable when reading tall and narrow columns of text.
- Check for Errors and Respond to Them: Routines can return with an error indication, or they can raise an exception. Deal with it. Don't assume that a disk will never fill up, your configuration file will always be there, your application will run with the required permissions, memory-allocation requests will always succeed, or that a connection will never time out.
- Include Unit Tests: The complexity of modern software makes it expensive to deploy a system and difficult to test it as a black box. A more productive approach is to accompany every small part of your code with tests that verify its correct function. This approach simplifies debugging by allowing you to catch errors early, close to their source. Unit testing is indispensable when you program with dynamically typed languages such as Python and JavaScript, because they'll only catch at run-time any errors that that a statically typed language such as Java, C#, or C++ would catch at compile time. Unit testing also allows you to refactor the code with confidence.
- Keep Your Code Portable: Unless you have some compelling reason, avoid using functionality that's available only on a specific platform or framework. Don't assume that particular data types (such as integers, pointers, and time) are of a given width (for example, 32 bits), because this differs between various platforms. Store the program's messages separately from the code, and don't hard-code cultural conventions such as a decimal separator or date format.
- Make Your Code Buildable: A single command should build your code into a form that's ready for distribution. The command should allow you to perform fast incremental builds and run the required tests. To achieve this goal, use a build automation tool like Make, Apache Maven, or Ant. Ideally, you should set up a continuous integration system that will check, build, and test your code every time you make a change.
- Put Everything Under Version Control: All elements of your system—code, documentation, tool sources, build scripts, test data—should be under version control.
- Avoid Security Pitfalls: Modern code rarely works in isolation. Therefore it will inevitably risk becoming the target of malicious attacks. They don't have to come from the Internet; the attack vector could be data fed into your application. Depending on your programming language and application domain, you might have to worry about buffer overflows, cross-site scripting, SQL injection, and similar problems.
- File and Folder Organization: Technically, you could write an entire application code within a single file. But that would prove to be a nightmare to read and maintain.
- Consistent Temporary Names: Normally, the variables should be descriptive and contain one or more words. But, this doesn't necessarily apply to temporary variables. They can be as short as a single character.
- Capitalize SQL Special Words: Database interaction is a big part of most web applications. If you are writing raw SQL queries, it is a good idea to keep them readable as well.
- Separation of Code and Data: This is another principle that applies to almost all programming languages in all environments. In the case of web development, the "data" usually implies HTML output.
- Alternate Syntax Inside Templates: You may choose not to use a fancy template engine, and instead go with plain inline PHP in your template files.
- Object Oriented vs. Procedural: Object oriented programming can help you create well structured code. But that does not mean you need to abandon procedural programming completely. Actually creating a mix of both styles can be good.
- Read Open Source Code: Open Source projects are built with the input of many developers. These projects need to maintain a high level of code readability so that the team can work together as efficiently as possible.