Notes on codestyle

Quite often I come across a question about the quality of the code: "Why is it written this way, and not so?". And I explain every time. That is why I decided to write a kind of note with explanations.





The second question that arises is: "Where did you learn to write so beautifully?" The answer to which will be by the end of the article.






A fairly common problem when writing code is that it looks like a solid text, and contains problem areas that complicate not only reading, but also further maintenance. In such cases, you should not neglect the use of line breaks and additional "space" characters.





I remembered a bearded anecdote about real events:





The developer reads his code written:





- today: great modern cool code! I would always write like that!





- yesterday: so, I stopped here. Aha!





- last week: what was I doing there? ..





- last month: so where is the problem with the description?





- last year: to break the legs of the one who wrote this code!






Recently I met such a piece of code (I will insert it with a picture so as not to disrupt its appearance):





- , , ...





. . - .





. . , , ? , .






, .





- , - .





:





$salaryFirstBaseEmployer = $employer->salaryBases->first()->salary_base;
$salaryLastBaseEmployer = $employer->salaryBases->last()->salary_base;
$begin = Carbon::parse('2020-05-01')->startOfMonth()->startOfDay();
$end = $begin->clone()->endOfMonth()->endOfDay();
$endMonth = $begin->clone()->endOfMonth();
$startPeriod = new CarbonPeriod($begin, $end);
$endPeriod = new CarbonPeriod($begin, $end);
      
      



, , , :





$salaryFirstBaseEmployer = $employer->salaryBases->first()->salary_base;
$salaryLastBaseEmployer  = $employer->salaryBases->last()->salary_base;

$begin = Carbon::parse('2020-05-01')->startOfMonth()->startOfDay();

$end      = $begin->clone()->endOfMonth()->endOfDay();
$endMonth = $begin->clone()->endOfMonth();

$startPeriod = new CarbonPeriod($begin, $end);
$endPeriod   = new CarbonPeriod($begin, $end);
      
      



:





, -, .





, .





PS: Several people, including messages outside Habr, have already written that there are such things as PSR, code autocomplete, code formatting in the IDE, cs-fixer, and so on. Do you really think that I don't know about their existence? The problem, revealed in the article, is not that they are not used, but what prevents from initially writing beautifully code without setting fire to farts of other developers? ..





PS2: It so happened that the overwhelming majority of commentators caught on to the examples in the article, scoring on its main message. In this regard, I have removed all examples that do not carry a semantic load and importance for the article as such.








All Articles