Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

Блог пользователя professorbrill

Автор professorbrill, 11 лет назад, перевод, По-русски

Пусть мы объявили переменные a and b в программе. Следующие 2 куска кода выполняются идентично.

1.

a = 1;
b = 1;

2.

a = b = 1;

Но есть ли такой стиль кода (Google C++ Style Guide не дал мне ответа), который утверждает, что какой-то из них предпочтительней?

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
11 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Why would you need one? This is just a matter of individual style (most of the time, as there are situations in which I prefer to clearly distinguish between groups of commands related to different parts of the algorithm).

A convention is necessary in a situation where different choices can lead to different results (like some right hand rules in physics), but not here, IMO.

»
11 лет назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

По-моему, такой конструкции лучше избегать.

Во-первых, это ухудшает восприятие кода, так куда привычнее глазу конструкции вида var = val;

Во-вторых, если нам понадобится для одной из переменных изменить значение, придётся переделывать всю строку, вместо изменения одной константы.

  • »
    »
    11 лет назад, # ^ |
      Проголосовать: нравится +26 Проголосовать: не нравится

    а если понадобится изменить обе переменные на одно значение, или удалить обе строки ...

»
11 лет назад, # |
  Проголосовать: нравится +19 Проголосовать: не нравится

Interesting, I was pretty sure that multiple assignments are against the Google Style Guide (and was even mentioning this couple of times when reviewing someone's code), but indeed the style guide does not mention this at all.

»
11 лет назад, # |
  Проголосовать: нравится +34 Проголосовать: не нравится

I think this is not a matter of coding style. Those two pieces of code actually mean different things. The first one means: we have two variables which have no relation between them and coincidentally equal to 1 in the beginning. The second one: we have two variables that are equal to each other in the beginning and their value is 1.

So, to know which one is preferable we have to know what those a and b mean.

  • »
    »
    11 лет назад, # ^ |
      Проголосовать: нравится +1 Проголосовать: не нравится

    Actually, many people don't care about that. For example, unexperienced coders who think that it's not possible to assign the same value to several variables at once, so they use just the first one. Or, some people deliberately try to make the code shorter and use the second one all the time.

    So while it's good to not keep it a matter of style, it still happens.

»
11 лет назад, # |
  Проголосовать: нравится +17 Проголосовать: не нравится

Being a Python beginner, I have once spent about half an hour debugging a solution which worked incorrectly because of a line like this one:

a = b = []

(I naively expected a and b to point to two different empty lists, while in reality, both pointed to the same list, of course).

Now, I prefer not to use such a construction, and this is one of the reasons. Also, most of the time, even if two variables are initialized with the same value, they are not related to each other, which makes the "a = b = 1" construction nonsemantic and just a really ugly way to make your program one line shorter.

»
11 лет назад, # |
  Проголосовать: нравится +7 Проголосовать: не нравится

Есть такая отчасти популярная тенденция — избегать выражений совершающих второстепенные (потусторонние) действия.

Например эту концепцию демонстрирует отсутствие операций пред/пост- инк/декремента в Питоне.

Выражение a = b = 1 подпадает под этот "грех" т.к. a присваивается значение выражения которое само по себе тоже что-то меняет.

Аналогичный вопрос например

while ((f = file.readLine(...)) != null) {
    doSomething();
}

здесь мы тоже одновременно с проверкой ещё какие-то действия выполняем, что любителей чистоты раздражает.

Поэтому стоит просто решить как вы сами к этому относитесь. Или если работаете в команде — как к этому относятся ваши коллеги. С точки зрения читабельности или модифицируемости кода по-моему этот вопрос вовсе выеденного яйца не стоит. В крайнем случае перепривыкнуть займёт немного времени (особенно если стайл чекер какой-нибудь включен).

»
11 лет назад, # |
  Проголосовать: нравится +4 Проголосовать: не нравится

There is popular idea — to avoid constructions which have side-effect. That is why python lacks pre/post inc/decrement operations. This construction has side effect — while assigning value of some expression to a we also change expression b.

However it is not extremely important problem, I think, so you can follow your personal tastes or if you are working in command — follow the style rules of this command. Usually you will have no problem switching between these two styles (especially if stylechecker is on).