• Ever wanted an RSS feed of all your favorite gaming news sites? Go check out our new Gaming Headlines feed! Read more about it here.
  • We have made minor adjustments to how the search bar works on ResetEra. You can read about the changes here.

A or B

  • A, it's all about minimalism baby

    Votes: 288 41.3%
  • B, it's gotta be the explicit logic

    Votes: 409 58.7%

  • Total voters
    697

Roxas

The Fallen
Oct 28, 2017
3,575
Buenos Aires, Argentina
I'd take B all day long man, having to do code review I vastly prefer readable, correct code, specially if what you're doing is complex A could get kinda noisy to read. I get it if you're doing micro controllers and just want to save space, but otherwise, nope.
 

SteveMeister

Member
Oct 31, 2017
1,821
A
Code:
function doThing() {
    if (condition) {
        return 1;
    }
    return 2;
}

B
Code:
function doThing() {
    if (condition) {
        return 1;
    } else {
        return 2;
    }
}

Seen a lot of the former practice at my workplace lately and tbh it's totally bothering me, I'd put human readability above most things. Are you all about saving characters? Is the former actually somehow "safer" in your opinion?

(Edit: I should've made the example more dirty to make using a ternary not the easy answer, but yeah, just assume that's not plausible here)
My personal preference is for open and close braces to be in the same column. If a line ends up being wider than your visible columns you won't see the trailing brace. Makes for more easily readable code as the code gets more complex. And if you're not using an IDE that highlights corresponding braces or has outlining features, you can position the cursor over the open or close brace & mousewheel up or down to see its counterpart.

My personal preference is to avoid multiple return statements, and instead have a result variable that gets set appropriately and returned at the end of the function. The only exception is an early out at the beginning of a function. Break is ok if it's available. But a function should have the minimal number of returns as possible. If you find yourself using more, rethink your function design, maybe make use of switch or break the function up into multiple functions.

My personal preference with simple conditions is to use a ternary. But if the conditions become complex or you end up with nested ternaries, it's better to break them up.

So I'd write this:
Code:
int doThing()
{
    return condition ? 1 : 2;
}
That said, I'm not a stickler for varying code styles, as long as they're readable and consistent.
 

shnurgleton

Member
Oct 27, 2017
15,864
Boston
Everybody voting B is paid by LOC or is really afraid to deviate from textbook examples

Also I prefer a more functional style anyways. In current arrow-style Javascript I'd do

JavaScript:
const doThing = () => condition ? 1 : 2;

Terser code with fewer LOC generally means fewer places for bugs
 
Last edited:

Tony B

Member
Dec 29, 2018
669
Those are functionally two very different code blocks even if the output is the same in this scenario. The first one actually obfuscates the logic more because the blocks are all connected in a single logical chain. Only one of those statements will ever be executed. In the second block, you're guaranteed that each check will occur sequentially and in order if for some reason one of the statements was not actually a return statement. Or if multiple of the logic branches were true (like A < 2, followed by A < 3).

If you were to reduce a set of if statements into an if-else statement, the odds are fairly likely you'd bring in a bug or two.
That's more laziness of my part. I was going to make it a bunch of nested if/else statements but didn't want to muddy the waters of the argument by presenting something too different to the original examples.
 

Z-Beat

One Winged Slayer
Member
Oct 25, 2017
31,853
In this case I'd probably go with A since all you're doing are return statements but functionally there isn't much of a difference.

if it was doing something besides returns I'd go with B, obviously
 

Composer

Banned
Nov 14, 2017
176
A is the correct format is most situations. B has issues. The else is completely redundant in this situation. This is how we code at Google and you would be expected to make this clean up 99/100 times.
 

TitanicFall

Member
Nov 12, 2017
8,281
I tend to add default values at the beginning.

function doThing() {
var thing = "default";

if (condition) {
thing = "nondefault";
}
return thing ;
}
 

iapetus

Member
Oct 26, 2017
3,078
Neither. If it's that short, ternary if. Otherwise I'll rearrange it so that there's only one return statement.
 

EJS

The Fallen
The Fallen
Oct 31, 2017
9,196
B is probably a better answer for transparency but I always implement A.
 

GringoJB

Member
Oct 25, 2017
70
USA
I'd instinctually do it like B if I was writing it, but I really don't care either way... holy wars over this sort of thing drive me up the wall
 

MatchaMouse

Member
Mar 12, 2018
311
Not a fan of the brackets in either but I choose B. I feel like most people I've met that are all about minimalism in their code end up being elitist types and won't admit that it's much less intuitive to read.
 
Oct 27, 2017
42,700
Honestly? Depends on how many if statements there are
If there's just one, I'd go with A. If there are many, I'd opt for B, just be I think that looks nicer.
Extending it further, if multiple statements require curly braces, I'll apply that even to the ones that don't just for visual consistency
 

ivantod

Member
Oct 27, 2017
1,495
I know that else is not needed here but I like to put it in anyway because it seems to me to be a bit clearer for the person who is reading the code at some later point. So my choice usually would be B, although for an example as simple as this I would just use the ?: operator in one line.
 

EJS

The Fallen
The Fallen
Oct 31, 2017
9,196
Code:
function doThing() {
    return condition ? 1 : 2;
}

This is honestly what I would do. Simplistic expressions like this is what ternary's were made for, in my opinion.
 

subrock

Member
Oct 27, 2017
1,961
Earth
Id do 1 but in Swift I'd use a guard instead of an if. Looks a lot cleaner than an if else


Code:
func foo() {
  guard condition else { return 2 }
  return 1
}

edit: ternary is also a good solution, but in that case I'd likely remove the function call altogether and just do it inline
 

EJS

The Fallen
The Fallen
Oct 31, 2017
9,196
Id do 1 but in Swift I'd use a guard instead of an if. Looks a lot cleaner than an if else


Code:
func foo() {
  guard condition else { return 2 }
  return 1
}

edit: ternary is also a good solution, but in that case I'd likely remove the function call altogether and just do it inline
True, lol, I might just assign an integer in-line to the outcome of the expression - unless it really didn't go with the flow / purpose of the function, for some reason.
 

Mills

Member
Oct 28, 2017
244
Mostly boils to style/preference absent established norms of the codebase. I prefer single return statement for many reasons but I have no issue with any of the suggestions IFF the function is very short and very unlikely to get more complex, in which case I expect even a novice can read any of these and know what's going on at a glance. Most important is to pick one and stay with it so others or yourself at a later date don't need to expend mental energy making sure it isn't different for a reason.

I tend to add default values at the beginning.

function doThing() {
var thing = "default";

if (condition) {
thing = "nondefault";
}
return thing ;
}

My man.
 
Last edited:

ChrisR

Member
Oct 26, 2017
6,800
Id do 1 but in Swift I'd use a guard instead of an if. Looks a lot cleaner than an if else


Code:
func foo() {
  guard condition else { return 2 }
  return 1
}
Guard s seems pretty cool.

I'd probably go with A in production code, a base "fail state" with any conditional stuff above it. Tertiary is great if you 100% know whatever you are dealing with will be one value or another.
 
Nov 1, 2017
1,380
It doesn't really make a difference to me, I do whatever standards have been laid out by the employer because if I don't it's going to get dinged in code review anyway.
 

EJS

The Fallen
The Fallen
Oct 31, 2017
9,196
The last company I worked at (...2 months, cuz yeah) banned use of the ternary operator. 🤣
I know a lot of people that really, really don't like them and think they're really hard to read. I think nested ones are gross and don't serve a purpose, but clean, simple ones? I think they're great but everyone is different :)
 

correojon

Banned
Oct 26, 2017
1,410
In fact I usually do something a bit different:
Code:
int doThing(){
    result = 2;
    if condition{
        //Other code
        result = 1;
    }
    return result;
}

I know it's now widely accepted but I still don't like to exit functions mid-way through return statements, or loops with breaks/exits (I only do it if there's a notable performance gain).
 

EJS

The Fallen
The Fallen
Oct 31, 2017
9,196
All of my fellow ternary friends, hit me up if your company is hiring remote devs, lol.
 

The Albatross

Member
Oct 25, 2017
39,046
Example in the op is basically the same, but Im very explicit in my code over being concise. Personally it's much easier for me to read through explicit functions and if/else than those reductive switch statements or ternaries which do like 3 things in a single line. I basically only write ternaries in react statements.

I'm just naturally verbose. Also with minification and uglifying I don't really see the need to be super concise in a statement when my toolchain will end up reducing the size of my statements anyway.

I also prefer writing one function per operation. Like, a function does one thing. One function might map through something, then another function filters the results and a third reduces it. Rather than a single statement that does all three.

Whenever I take over a project and it's written in the most concise way possible it's super frustrating for me to take it over and step back thru the code.
 
Last edited:

Firebricks

Member
Jan 27, 2018
2,136
For the love of God I don't care how efficient and pretty your code is, 2 years later you aren't going to remember why you did it that way, your comment is going to be likely wrong or not there in the first place. Making your code dumb and readable is so important. Compilers are going to do the leg work anyways.
 
OP
OP
Stopdoor

Stopdoor

Member
Oct 25, 2017
5,779
Toronto
I do find it interesting this is apparently "settled" by linting but the majority seems to prefer the latter. Not that majority has much influence on what's "correct" but in a case like this where it's mostly about readability maybe that says something.

It's tiring to argue about this stuff but at least I can sleep content knowing I'm in the majority lol.
 

L.E.D.

Member
Oct 27, 2017
640
A is the correct way, a function should always have a default return value of some kind.
 

Zej

The Fallen
Oct 25, 2017
913
Ternary can be ugly, but I can live with it usually. I vote A.

Ruby:
def thing
    return 1 if condition
  
    2
end

At the end of the day, this is a style thing; you want to be consistent with team patterns/practices. If using JS, then a slightly modified StandardJS linter is great. Having good linters and something like codeclimate is great for a team.
 
Last edited:

Mills

Member
Oct 28, 2017
244
Wow... I would have left in 2 hours

I absolutely love the idea of someone going through the potential months long process of application, phone interview, possible background check/drug test, multiple stages of in-person interviews, offer negotiation, resigning your previous position, potentially relocating, orientation and onboarding only to walk out once they see ternary operator is not allowed in the style guide.
 
Last edited:

ratcliffja

Member
Oct 28, 2017
5,918
Also, I think the last line of a return function should always return something (typically the default value) and not live in a code block.
 

Weltall Zero

Game Developer
Banned
Oct 26, 2017
19,343
Madrid
The first one is especially bad, but both incur in arguably bad practices. If at all possible, you shouldn't use return except as the very last line in a function. The reason for this is that return, like break or goto, bypasses normal execution flow and makes code paths harder to follow.

I would use:
Code:
function doThing() {
    return condition ? 1 : 2;
}

Or if the language doesn't support the ? : operator:
Code:
function doThing() {
    int ret;
    if (condition) {
        ret = 1;
    } else {
        ret = 2;
    }
    return ret;
}

By the way, in the second example, leaving ret uninitialized helps catch potential situations where you don't set a correct value to it, since modern IDEs will display an error or warning that you're returning a potentially uninitialized value. E.g. this will display an error / warning:
Code:
function doThing() {
    int ret;
    if (condition) {
        ret = 1;
    } else if (condition2) {
        ret = 2;
    }
    return ret;
}

Of course, if your IDE doesn't warn about uninitialized values, then the safest option is to initialize it to a valid default value at the beginning.

B is better (less error prone in the long run) than A.
But usually I don't do returns in the middle of a function, so it's this instead:

Hahah, beaten by a minute. But yeah, exactly this.