You get a bonus - 1 coin for daily activity. Now you have 1 coin

Beautiful script or programming styles in PHP

Lecture



Beautiful script or programming styles.

This chapter is also written here for a reason. The script should be beautiful. And you need it, oddly enough, not for beauty.
The fact is that very few programs are written once and for all, and to immediately work as it should. The script, written beautifully, is much easier for you to debug, modify. In addition, for various reasons, another person may have to work with your creation. Beautiful, well-written code is much easier to understand.
Let's figure out how a beautiful code should look. First, look at the codes with the shortcomings, then analyze them.


№1
<?PHP for($i=0;$i<5;$i++){if($i%2)echo $i;echo 'O<hr>';} ?>

№2
<?PHP
for(
$i
=
0 ; $i
<5 ; $i++)
{
if
($i
%
2)echo
$i;
echo 'О<hr>'
;} ?>

№3
<?PHP $a = $b+$c * $d ?>

№4
<?PHP
for ($i = 0; $i < 5; $i++) {
if ($i % 2)
echo $i;
echo '<hr>'; }
?>

All the above scripts are written syntactically correctly, these are working scripts.

Here, consider code number 1. Everything is written line. Well, quickly: when does the code print the big letter O? Not convenient to look for, right? And if the code was on many sheets?

What are the disadvantages of code number 2, do not even need to explain. Try to answer the same question as in the previous case.

The disadvantage of code number 3 is that if you run a quick glance through it, you can get the deceptive impression that the addition operation takes place first, i.e. this arrangement of spaces also makes perception difficult.

In code number 4, due to tabulation, it seems that the '<hr>' tag is displayed only when the condition is met, but if you look at the curly braces, you will see that this is not the case.

Particularly stubborn personalities about the last two examples will say, they say, nothing of the kind, everything is perfectly clear: what and how. In vain so. In large codes, a similar attitude to the structure of the code can climb sideways through the most unexpected places. Yes, and small too.


Fundamental rules.

So, as can be seen from the first and second examples, I think it is not necessary to tell.

The third example tells us that the placement of spaces should be constant. There should not be such that there are 2 spaces, then 4, there is not even one. Still here it should be said that in long expressions

CODE:

$ b = $ a + $ c + $ z + $ f * $ r + $ e * $ f + $ a + $ o

The multiplication operation is still worth brackets, although it is still the first to be executed. This will make the code easier to read.
And more about spaces: Always separate commas and other operators from both sides with spaces.

CODE:

$ b = $ a + $ c + $ z + $ f * $ r + $ e * $ f + $ a + $ o

Nice to read such porridge?

From the 4th example we see the role of indents. Indents should show us the nesting of program structures. This means that all statements nested, for example, in a cycle, must start at some equal distance from the left edge further than the cycle operator itself. The same with the conditions. Operators of the same nesting level must be at the same distance from the left edge.


Place braces.

There are many styles:

<?PHP
if ($a > $b) {
// операторы
}
?>

<?PHP
if ($a > $b)
{
// операторы
}
?>

<?PHP
if ($a > $b)
{
// операторы
}
?>

<?PHP
if ($a > $b)
{
// операторы
}
?>

I use the first method in the blocks if, for, etc., and the second when describing functions. I like the first method because the closing bracket is on the same vertical line with the fact that it opens (in this case with the if operator), and the first bracket does not create an extra (it seems to me that unnecessary) indentation after if.
For functions, I use the second method, because ... yes, I don’t even know why; I like it so much I don’t like other ways because of the large amount of tabs. In any case, the closing brace should be placed alone on the line and it should immediately be seen that it closes.


The names of variables, functions and classes.

Names should tell a programmer about the assignment of a variable, function, or whatever. What can you say when you see $ a = 'Table' in the middle of the code? Nothing in essence. But $ product = 'Table' tells us what it is about. The same with functions: $ r = g ($ a, $ b) and $ sum = add ($ serv_1, $ serv_2). See the difference? But you do not need to give functions (more precisely, what you don’t need) type names add_first_service_and_one_more_s ervice_returning_their_summ_as_i nteger_value. Why - explain?


Comments

What you need to comment.

Comment need to:
* Unusual solutions. Because then do not remember what you had in mind here. And the other person - all the more, it will not understand.
* Decisions that had to be thought about. In case you want to shovel something. Perhaps you have already tried, and understood why it should be done that way. It is worth writing in the comments.
* Assignment of long blocks.
* Long logical conditions. In human language. Not "if more b and a less e". This is already evident from the code.
* Something that really needs a comment. No need to comment on this:

CODE:

ibase_connect ($ host, $ user, $ passwd); // connect to the database on interbase


What should be the comments.

Compare:

<?PHP
$a = 1; // Присваиваем переменной А единицу
$b = 6; // Присваиваем Б значение 6
// Цикл по $i от 1 до 6
for ($i = 1; $i <= $b; $i++ )
$ a = $a * $i; // Умножаем А на $i
?>

<?PHP
// Находим факториал числа $b
$a = 1;
$b = 6;
for ($i = 1; $i <= $b; $i++ )
$a = $a * $i;
?>

There is a difference? A bunch of comments in the first code didn’t tell us absolutely nothing, and three and a half words in the second case made us completely understand what was there for. First of all, we need to comment on what we are doing, and why. By the way, here's another:

<?PHP
function factorial($b)
$res = 1;
for ($i = 1; $i <= $b; $i++ )
$res = $res * $i;
?>


Here everything is clear without comments. This is about how to call functions and variables.

Where are the comments.

Usually, the comment of one command is located after the semicolon, and the comment of the block is located in a line above its first command. There is nothing more to write, in my opinion.

And more about the comments.
Do not be lazy to comment. Many programmers do not like to comment on their code, but they are wildly outraged when they have to work with someone else's non-commented code.


About nesting.

Here I will only say that situations like

<?PHP
function any_func()
{
if ( условие ) {
// вся функция
}
}
?>

It is better to describe them like this:

<?PHP
function any_func()
{
if ( ! условие ) {
exit;
}
// вся функция
}
?>


Goto

This operator is present in many programming languages, and it also appeared in PHP 5.3.0. But he is called Jump there.
You can use it, but only when necessary; when it facilitates reading and code implementation; when to avoid GOTO you have to enter many additional checks and variables. However, the occurrence of such a situation may indicate a design error. But if it is necessary, then all right. Just do not abuse it.
By the way, there is a break in PHP for exiting the loop, and continue for repeating. For the break operator, you can specify the number of how many levels of nesting you need to exit. So, to avoid his ability to eat.

Some more useful rules:

  • Good code comments on yourself
  • Never use goto, never strictly. No, and they will not come up with such constructions in which it would be impossible to do without it. If you have one site in the code more than 1 time, you should think about how to make it a function. This, however, should be attributed to a logically complete fragment, that is, to such a section that can be combined into a logical form.
  • A well-written script will save the programmer's time - one writer and ten readers.
  • I recommend writing comments in English only, so that they can be read in any encoding. I recommend writing not in transliteration, but in literary English.
  • It is not worth spending time on inventing super-tricky algorithms that will save 0.1 seconds at a benchmark of 10,000. A programmer's time is worth more than the time of these soulless pieces of hardware. And, besides, the processor time is getting cheaper, and the time of programmers is more expensive. This rule should be applied if the performance gains are clearly small compared to the development costs.
  • When naming functions and variables, stick to a certain - but - the same style. Do not write, say

    <?PHP
    $user_password="";
    $userPassword="";
    ?>

  • You will surely forget how and in what case you called this variable. Stick to the same style and you do not have to spend time searching for exactly how you called this variable itself.
  • For ease of reading in PHP, I recommend specifying the data type prefix in front of the variable names (the so-called "Hungarian notation"). This is due to the fact that in PHP there is no explicit type definition, and such naming helps to immediately understand which type the variable belongs to:

    <?PHP
    $sUsername="user123";
    $iUserage=20;
    $bUserdeleted=false;
    ?>

  • Write the script as if tomorrow you will have to refine it. Try to think it over so that it is easy to scale.

there are also special rules for code design, file connection, classes


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)