Wildeblood wrote:So, what's the difference? Which is better?
Since it’s a stylistic difference, “better” is largely subjective, but it’s worth considering why you’d do one over the other.
One school of thought is that it’s good to keep the main path of the function “to the left”, i.e. not heavily indented, so that the structure of the “important” code is easy to see without having to match up many levels of nested braces. In this view, “early exits” dealing with cases where your function doesn’t need to do anything are good, because those cases can then be ignored in the rest of the code. Capt. Murphy’s original code follows this approach.
Another perspective is that having multiple return statements in a function is always bad, because it makes it harder to follow the control flow. It also means that if you need to clean up anything before returning, that code gets duplicated and it’s easy to miss one spot if you’re updating the code.
It’s possible to mix these philosophies. For instance, you might choose to use early exits for trivial cases and bad parameters (like “don’t bother doing any collision testing work in this region if there are fewer than two objects in it”), but use a single-return approach for the “meat” of a function. This is the broad tendency in Oolite itself, although I wouldn’t want to give the impression that Oolite is self-consistent.
Which it should be. The most important thing about code structure is consistency, because if you use the same pattern in all relevant parts of your code it becomes easy to read the pattern itself rather than the steps it’s made up of. Good coding style is about making code readable to humans.
That said, this is honestly a few steps beyond most OXP coders. The #1 code structure tip for beginners is: use a consistent indentation style. Code at the same nesting level (mostly meaning the same number of enclosing {}s, although there are other types of nesting) should be aligned on their left margin. This makes it vastly easier to see the structure of the code. If you don’t have an established preference, try to match the appearance of Oolite’s scripts and plists. A programmers’s editor like Notepad++ or Gedit or Xcode will help you do this automatically for .js files. (If your editor has a setting for indentation style, the Oolite norm is similar to Allman style.)