Лучший Синтаксис метода Java? Возвратиться рано или поздно? [дубликат]

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

php artisan serve --port 8001
6
задан Community 23 May 2017 в 10:31
поделиться

10 ответов

If it's a method you'll be calling thousands of times, then early return is better to achieve a [slightly] increased performance.

If not, then I'd prefer late return, since it improves readability.

Remember programmers usually spend more time reading than writing code, so anything you can do to improve readability will be certainly welcome.

9
ответ дан 8 December 2019 в 03:01
поделиться

As with most coding styles, it's really a matter of preference, but guard clauses are considered by many to be a best practice.

5
ответ дан 8 December 2019 в 03:01
поделиться

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

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

boolean valid = true;
if( condition1 ) {
   valid = false;
}
if( valid ) {
   ...
   if( condition2 ) {
      valid = false;
   }
}
if( valid ) {
   ...
   if( condition3 ) {
      valid = false;
   }
}
... (etc)

Однако, если вы окажетесь в любой из этих ситуаций ... вам, вероятно, следует провести рефакторинг функции.

4
ответ дан 8 December 2019 в 03:01
поделиться

I prefer returning early and avoiding deep nesting. This is particularly true right at the start of the method: test anything that's simple, and get out (or throw an exception) if you can do so really early.

If it's right in the middle of a method, it's more of a judgement call.

Note that I'd refactor your example straight away to use a single if:

boolean validate(DomainObject o) {    
  if (o.property == x || o.property2 == y) {
     return true;
  } ...
  return false; 
}

I realise this was only a toy example, but my point is that it's always worth looking for more ways to simplify your code :)

9
ответ дан 8 December 2019 в 03:01
поделиться

To me, this is sort of one of those religious war topics with no correct answer. The argument against returning early essentially boils down to the fact that having one and only one point where a function can exit reduces the number of possible paths through your code, thus, in theory at least, reducing the chances for bugs. My personal style is to, in situations where it makes sense to return early do so, and in situations where it makes sense to limit to one return statement I do that.

2
ответ дан 8 December 2019 в 03:01
поделиться

If exceptions aren't part of the picture, I prefer returning immediately when I can.

It can be easy to mismanage the flag variable and I'm against flag variables in general. Not returning also might make a maintainer think that further work might be done (if the method is long).

1
ответ дан 8 December 2019 в 03:01
поделиться

There are two factors pulling against each other.

The first factor is ease of debugging. If you return immediately (as shown in your second code snippet), it sometimes becomes difficult to debug a big function since it is hard to find these return statements, specially if they were put there by mistake.

The second factor is ease of implementation. If you are checking basic correctness of arguments at the beginning of the function and there is a long piece of code before the function finishes, you might have to put that entire code in a condition loop. If you don't, at some point the argument might get used for some long calculation, wasting time, because it would ultimately be rejected anyways.

So, the answer could be like this:

If the function is small, 
        save the return status in a variable and return at the end. 
else 
        return immediately.
1
ответ дан 8 December 2019 в 03:01
поделиться

Personally, I like the second method better. It is straightforward and clearer to me, but I do know there are people who must have only one return in a function.

0
ответ дан 8 December 2019 в 03:01
поделиться

Honestly I think it depends on the situation. Personally I use both, and I decide based on which one will make the code more clear and easy to read.

If you have heavily nested if statements (or any other control structure) and it may get confusing, then I would return inside the statements

Don't worry too much about what is 'best practice' in this case, as it is more important that the code is clear and easy to understand. Use what feels right for the situation.

0
ответ дан 8 December 2019 в 03:01
поделиться

For this case, I prefer:

boolean validate (DomainObject o) {
    if (o.property == x ||
        o.property2 == y ||
        ...) {
          return true;
    } else {
          return false;
}

In general, I like to use early return to handle error conditions, and return at the end to return computed results.

0
ответ дан 8 December 2019 в 03:01
поделиться
Другие вопросы по тегам:

Похожие вопросы: