Статьи

если – еще лучшие практики кодирования стиля

Следующий пост будет расширенным обсуждением фигурных скобок без правильного или неправильного ответа, просто больше «дело вкуса». Речь идет о том, помещать «else» (и другие ключевые слова, такие как «catch», «finally») в новую строку или нет.

Некоторые могут написать

1
2
3
4
5
if (something) {
  doIt();
} else {
  dontDoIt();
}

Я, однако, предпочитаю

1
2
3
4
5
6
if (something) {
  doIt();
}
else {
  dontDoIt();
}

Это выглядит глупо, возможно. Но как насчет комментариев? Куда они идут? Это почему-то выглядит неправильно для меня:

1
2
3
4
5
6
7
8
9
// This is the case when something happens and blah
// blah blah, and then, etc...
if (something) {
  doIt();
} else {
  // This happens only 10% of the time, and then you
  // better think twice about not doing it
  dontDoIt();
}

Разве следующее не намного лучше?

01
02
03
04
05
06
07
08
09
10
11
// This is the case when something happens and blah
// blah blah, and then, etc...
if (something) {
  doIt();
}
 
// This happens only 10% of the time, and then you
// better think twice about not doing it
else {
  dontDoIt();
}

Во втором случае я действительно документирую случай «если» и «еще» отдельно. Я не документирую вызов «dontDoIt ()». Это может пойти дальше:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
// This is the case when something happens and blah
// blah blah, and then, etc...
if (something) {
  doIt();
}
 
// Just in case
else if (somethingElse) {
  doSomethingElse();
}
 
// This happens only 10% of the time, and then you
// better think twice about not doing it
else {
  dontDoIt();
}

Или с try-catch-finally:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
// Let's try doing some business
try {
  doIt();
}
 
// IOExceptions don't really occur
catch (IOException ignore) {}
 
// SQLExceptions need to be propagated
catch (SQLException e) {
  throw new RuntimeException(e);
}
 
// Clean up some resources
finally {
  cleanup();
}

Это выглядит аккуратно, не так ли? В противоположность этому:

01
02
03
04
05
06
07
08
09
10
11
12
// Let's try doing some business
try {
  doIt();
} catch (IOException ignore) {
  // IOExceptions don't really occur
} catch (SQLException e) {
  // SQLExceptions need to be propagated
  throw new RuntimeException(e);
} finally {
  // Clean up some resources
  cleanup();
}

Мне любопытно услышать ваши мысли …

Ссылки: лучшие практики стиля кодирования if-else от нашего партнера по JCG Лукаса Эдера из блога JAVA, SQL и JOOQ .