A
A
Anastasia Soboleva2016-08-08 16:13:58
PHP
Anastasia Soboleva, 2016-08-08 16:13:58

Should I create additional variables for better readability of the code?

It is possible to write highly readable and self-documenting code, but sometimes this requires creating additional variables and breaking lines of code. How good or bad is this practice?
Simple example:

// $prices - двумерный массив с ценами
// $type - тип параметра
foreach($prices as $price) {
    $amount = $price[$type];
    $total += $amount;
}

Shorter version:
// $prices - двумерный массив с ценами
// $type - тип параметра
foreach($prices as $price) {
    $total += $price[$type];
}

Which style is preferred?

Answer the question

In order to leave comments, you need to log in

6 answer(s)
A
Alexey Nikolaev, 2016-08-08
@SobolevaSys

Depends on the situation. In your example, the second one. But, in the case of the code below - the first one.

foreach($houses as $house) {
    $current_floor = $house[$floor];
    $rooms_count = count($current_floor['flats']['1-room']); // например, только 1-комнатные

    $total_rooms += $rooms_count;

    /* вышенаписанное гораздо лучше, чем
    $total_rooms += count($house[$current_floor]['flats']['1-room']);
    */
}

In general, when you feel that your code is becoming unreadable, ugly, or simply unmaintainable, take appropriate action to correct the situation, including creating intermediate variables to visually separate the code.

M
Mikhail Osher, 2016-08-08
@miraage

I look at the following criteria to take out to a variable:
1) collection[key] is used more than once
2) key is too heavy (complicated) - then I take out the key (keeping the logic of point 1)

F
Fat Lorrie, 2016-08-08
@Free_ze

There are no universal rules here. Look at the code with a fresh eye and think, will the steps of the algorithm be obvious in a white view?
You can also rely on the proximity of the algorithm to natural language: "for each price tag, add a certain type of price tag to the total price tag." That is, the additional variable here rather adds verbosity - an extra entity that needs to be kept in mind.

X
xmoonlight, 2016-08-08
@xmoonlight

2nd.
it is not only shorter, but also much less resource intensive.
Well, and ... "crowbar in the sleeve": php.net/manual/ru/function.array-sum.php

M
Maxim Timofeev, 2016-08-08
@webinar

And it's easier like this:

$total = array_column($prices, $type);
$total = array_sum($total);

D
Denis, 2016-08-09
@prototype_denis

The most common problem...
I would choose the third way and call $type humanly, without creating an extra variable and explicitly making it clear that "type" is not some abstract substance, but a concrete thing, in this case the sum type.

<?php

foreach($prices as $price) {
    $total += $price[$amountType];
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question