Coding standards

8 January 2019

In every self-respecting IT company there are standards for writing code.

Some companies follow generally accepted code standards or standards that are dictated by the framework on which they are being developed.

In "VIS-A-VIS" for 15 years of practice, full of cones, by trial and error, we have developed our own rules with which we want to share in this article.

​​

What are the standards for writing code?

For easier entry into the project of new programmers, reducing the time spent on developing new and maintaining old code.

When code in the same style it is much easier to figure it out, isn't it?

The code should be written as if it was written by one person, and not by looking at the project code one could say that Masha wrote these lines, she liked to use snake_case instead of camelCase. And this code Vasya, his controllers swelled into hundreds of lines of code.

Often the maintenance of this kind of code will be several times more expensive than its original development.

So let's think about our fellow programmers who in a month, year, or two years will look into your code and say:

- “Waaah! What a wonderful code, many years of goodness and health to the author of this code and his children ”, and not "What asshole could write such a shitcode?! ”.

 

So, the rules for writing code:

0. PSR - 1/2

This rule is numbered 0, because this item is the basis of everything and it goes without saying.

"It's like going to write to the toilet in the toilet, and not where it is impatient."

What should accustom, if not yet accustomed, every novice programmer, and do not forget about this more experienced programmer.

The article how to write clean and beautiful code in PhpStorm I wrote earlier (see the link below):

https://www.vis-design.com/en/blog/kak-pisat-chistyi-i-krasivyi-kod-v-phpstorm-pri-pomoshi-plaginov-sonarlint-i-code-sniffer.htm

In fact, when this becomes a habit, then additional plug-ins are no longer needed, the code according to PSR standards is written easily by itself.

1. Single Responsibility Principle (principle of shared responsibility)

Each class method must perform only one function for which it was written.

Sometimes doing review code for young programmers seems like they are trying to save disk space, trying to shove all the code into one method or class instead of splitting a large method into smaller methods, or transferring logic to additional service classes.

2. Dry principle (don't repeat yourself)

If you see that the same code is written in different parts of your code, then you should consider putting it into a separate method or class.

3. Don't use else

Sounds pretty weird? How to write this code without else?

And you try and see right away how your code has become better and clearer.

Virtually any code can be written without using the else operator. If you still need to write else, use ternary operators.

4. Do not shit where there is already someone shit to you

If you have come to a new project for you that other programmers have already written to you, and you have felt the smell of bad code, then you don’t need to drop your pants and sit down next to you.

Try to remove this place, refactor the existing code and continue to write the code according to all the rules and standards.

5. Don't write bicycles

It’s good that we use in our projects the most popular framework in the world and 70% of all the code that we need is already written and tested by someone before us. You just need to use it.

Making a review of the Laravel project you can often find traces of native php code, which increases the source code at times, usually such code comes from lack of knowledge of the framework or the desire to write some kind of crutch.

This code should not be allowed in production.

6. The nesting of if and foreach statements should not be more than 2

Deep nesting complicates code understanding.

7. Parameters in functions (methods)

​7.1 Number of parameters

Must be no more than 2 parameters.

The fewer parameters in a function (method), the better, and ideally no parameters at all.

7.2 Avoid boolean flags in arguments

Logical arguments clearly indicate that the function performs more than one operation.

They are very confusing code.

​8. Titles

The name of the variables, methods, classes, should be camelCase, in English, informative, so that after reading the name of the method or variable, it was immediately clear what it should do.

The model name should be like the name of the table in the singular, if the table is called users, then the model should be called User.

Methods that process the request. This is for example a form handler. Such methods must begin with the do prefix.

An example of the names of handler methods: doUpdateAdForm, doRemoveAd, doChangeStatus.

Methods that make logical checks. The result of their call in most cases is a boolean true / false.

Such methods must have an is or has prefix, for example: hasUserEmail, isProductExists.

Heters and seters.

All methods that either return the state of an entity or change it must begin with the get or set prefix.

Example: getContent, setUserEmail, getSystemErrors.

9. Comments

Do not write comments, especially if they are:

// this is a dog
$dog = new Dog ();

 

Spend better time inventing an informative variable name, see clause 8, rather than writing a similar comment.

10. Commented out code

When you meet the commented out code, it is not clear whether it is needed or not, it only hinders and confuses.

Do not forget to delete it.

11. DB

The name of the fields and tables should be like, as recommended by Laravel, tables in the plural (products, users, etc.), connecting columns between tables, and the name of the table in the singular underscore id (user_id, product_id, etc.).

Columns with boolean values must have the prefix is_ or has_ for example, has_active or is_active

12. "Magic Numbers"

Replace "magic numbers" with named constants.

13. Arrays

The keys of associative arrays are written in snake_case and no camelCase (an exception if compact() is used).

Keys for a regular array are not assigned manually.

Unacceptable:

$array = [];
$array[42] = 'wtf';

 

When declaring an array, each element of the array must begin with a new line and end with a comma, even if it is the last element.

Bad:

$newArray = ['some_default' => 'values', 'another_default' => 'more values'];

Good:

$newArray = [
    'some_default' => 'values',
    'another_default' => 'more values',
];

 

14.  Strings

All strings should be placed in single quotes only.

Bad:

$str = “Hello world - $age”;

Good:

$str = ‘Hello world - ’ . $age;

 

15. Short and readable syntax where possible​

Session::get('cart') --- session('cart')
$request->session()->get('cart') --- session('cart')
return Redirect::back() --- return back()
return view('index')->with('title', $title)->with('client', $client)
--- return view('index', compact('title', 'client'))

 

16. Cycle indexes

This is normal when a small cycle of 1-3 lines has an index called i, j or k.

But if the body of the cycle is noticeably larger, then it is better to give the index meaningful names. And it will be easier for you to deal with this code over time.

Immediately it becomes clear what the loop is doing, and other programmers who will work with your code will also become easier.

Bad:

foreach($array as $k=>$v) {}

Good:

foreach($array as $slug => $product)

 

17. Readable conditions in the if operator

If there are more than 2 conditions in if, then it is better to put all conditions in a separate variable or method.

Bad:

if ($user->sex = ‘m’ && ($user->age > 18 || $user->age < 65))  {
  …
}

Good:

if ($user->ifAccess()) {
 …
}
Class User {
  private function ifAccess () {
    return $this->sex = ‘m’ && ($this->age > 18 || ($this->age < 65))
  }
}

 

18. Organization of methods in models

In large projects, models can be quite large, so for better organization we have methods in a certain sequence grouped according to their purpose.

First there are mutators, then scouts, then communications, public methods, protectode and at the end private, an example of this class is below:

class MySuperModel()
{
  public function getAttributesTest();
  public function scopeTest();
  public function relavionsTest();
  public function ();
  protected function()
  private function();
}

 

The article was prepared by PHP-developer of Digital Agency VIS-A-VIS – Arthur Shchablevsky.

Did you like the article? - Share the link::