• 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

Radnom

Member
Oct 25, 2017
1,019
If you are the function caller you have no idea what constitutes an error, that the function can give an error and so on, because it is returning an int regardless, but if the function returns a result type then the user knew that function could fail, and would have to account that when calling it.
Totally on a different tangent. This example makes me squirm.

Code:
bool isBanana(String type) {
    return type == "banana"; // just return if it's banana or not, no need for if/else
}
The example was just to show my aesthetic preferences for having a return value at the lowest tab level- they're complete nonsense examples otherwise, the bool function even returns an int haha. But this topic was purely about aesthetics, not functionality right?
I just like seeing that return right there at the bottom and not buried in who knows how many tabs of brackets :)

EDIT:
Like in the top example, I prefer A, but if it wasn't return values, i.e.

Code:
function doThing() {
    if (condition) {
        callFunctionX();
    } else {
        callFunctionY();
    }
}
then I'd prefer that, more like B
 

CheeseWraith

Member
Oct 28, 2017
618
Explicit logic (and comments on why a particular approach was taken when coding) is the only way to ensure maintainability.

If I need to change a function years after the implementation I'm sure I will be grateful to my past self if I followed those two principles.

Source: already was in this situation with mission critical code.
 

Ferrio

Member
Oct 25, 2017
18,072
I tend to dislike code that's too smart for it's own good, but I'd go with A here. Sometimes being too explicit has the opposite effect imo.
 

Micael

Member
Oct 28, 2017
1,368
The example was just to show my aesthetic preferences for having a return value at the lowest tab level- they're complete nonsense examples otherwise, the bool function even returns an int haha. But this topic was purely about aesthetics, not functionality right?
I just like seeing that return right there at the bottom and not buried in who knows how many tabs of brackets :)

EDIT:
Like in the top example, I prefer A, but if it wasn't return values, i.e.

Code:
function doThing() {
    if (condition) {
        callFunctionX();
    } else {
        callFunctionY();
    }
}
then I'd prefer that, more like B

Oh sure, was just using your example to prove the point that a lot of this early return code tends to be seen in sanity checks, and the real problem there is that if else is just the wrong language construct to use in those scenarios (although for many languages it might be the best one available).
 

krealian

Member
Oct 25, 2017
167
I chose A but it's not about minimalism. It's more about the function having a default return value that only differs if condition is true. This is very much specific to the example, though.

EDIT:
Like in the top example, I prefer A, but if it wasn't return values, i.e.

Code:
function doThing() {
    if (condition) {
        callFunctionX();
    } else {
        callFunctionY();
    }
}
then I'd prefer that, more like B

I agree with this.
 

JS3DX

Member
Feb 15, 2018
255
I choose B, because readability is always king.

Some people say "I'd choose A if it's a personal project" but if your brain collapses and the project is complex enough, you'll lose valuable time trying to read your own code.
 

Skade

Member
Oct 28, 2017
8,862
B, forever and always.

Sure, minimising anything you can might be fun and look nice (sometimes, most of the time i think it looks like shit). But one need to think about other devs touching your code after you. Some are not used to minimising everything and it's a chore for them to understand what your code means at a glance.

Clarity over fancy. Always.

Not that A is difficult to read in this instance, and i would probably not write this particular piece of code like A or B.

More like :
Code:
function doThing() {
    var x = 2;

    if (condition) {
       x = 1;
    }

    return x;
}
 
Last edited:

Randdalf

Member
Oct 28, 2017
4,167
A because you always end up adding more conditions and It's better in every way to early out than it is to start nesting if statements.
 

Vex

Member
Oct 25, 2017
22,213
Is all of coding/programming really that easy (or rather, logic based). Because I fully understood the OP despite having zero coding experience whatsoever.

This was really fun!
 
Nov 28, 2017
735
Sweden
While the functionality is the same, the implications are different to me.

A implies early exit given some special case, eg checking valid input.
C++:
int GetVertexBufferSize(const Mesh* mesh) {
    if (mesh == nullptr) {
        return 0;
    }

    return mesh->GetVertexCount() * sizeof(MeshVertex);
}

B implies two equally valid code paths.
C++:
int GetVertexBufferSize(const Mesh& mesh) {
    if (mesh.IsSkinned()) {
        return mesh.GetVertexCount() * sizeof(SkinnedVertex);
    } else {
        return mesh.GetVertexCount() * sizeof(StaticVertex);
    }
}
 

Skade

Member
Oct 28, 2017
8,862
Is all of coding/programming really that easy (or rather, logic based). Because I fully understood the OP despite having zero coding experience whatsoever.

This was really fun!

It's "basically" a logic take on english language, so it's designed to be somewhat easy to comprehend. Yes.

But what is shown in the OP is extremely simplistic and basic. You'll get more obscure stuff to read when looking at actual functionnal code. And you could stumble on this :

Code:
function doTHing() {
    return (condition) ? 1 : 2;
}

That's the same, but much less readable. So good luck getting it when you don't know what this way of writing means.
 

Elfforkusu

Member
Oct 25, 2017
4,098
It always depends.

I like negative logic returns a lot -- helps avoid nesting. But in the OP's case I would probably prefer B.

Well, I'd actually prefer the ternary tbh

While the functionality is the same, the implications are different to me.

A implies early exit given some special case, eg checking valid input.
C++:
int GetVertexBufferSize(const Mesh* mesh) {
    if (mesh == nullptr) {
        return 0;
    }

    return mesh->GetVertexCount() * sizeof(MeshVertex);
}

B implies two equally valid code paths.
C++:
int GetVertexBufferSize(const Mesh& mesh) {
    if (mesh.IsSkinned()) {
        return mesh.GetVertexCount() * sizeof(SkinnedVertex);
    } else {
        return mesh.GetVertexCount() * sizeof(StaticVertex);
    }
}
^
 

lightchris

Member
Oct 27, 2017
680
Germany
Is all of coding/programming really that easy (or rather, logic based). Because I fully understood the OP despite having zero coding experience whatsoever.

This was really fun!

These were basic examples (and of course there are differences between imperative/declarative programming languages, etc.).
But generally yes, it is always logic based and simple in principle. If you are good at such things or even find them fun, you might be a good programmer. ;)
 
Oct 25, 2017
6,459
not sure where the love for single line ternaries come from. they interfere with the simplicity of "step over line" debugging, so why even bother
 
Last edited:

GarbColle

Member
Sep 5, 2019
155
I'm surprised nobody posted the obviously best solution (might only work in C though):

C:
int doThing() {
   return 1 + !condition;
}

Also why did nobody so far notice the misleading name of the function? It's called doThing(), but doesn't actually do (any)thing. So it should rather be called something like getValue().

In more seriousness A for avoiding indentation creep. Single-return if e.g. concurrent code and locking is needed:
C:
int doThing() {
    int ret;

    lock();
    if (condition)
        ret = 1;
    else
        ret = 2;
    unlock();

    return ret;
}

can also be combined when there are checks that do not require locking:

C:
int doThing() {
    int ret;

    if (!precondition)
        return -ENOCOFFEE;

    lock();
    if (condition)
        ret = 1;
    else
        ret = 2;
    unlock();

    return ret;
}
 

brainchild

Independent Developer
Verified
Nov 25, 2017
9,480
Is all of coding/programming really that easy (or rather, logic based). Because I fully understood the OP despite having zero coding experience whatsoever.

This was really fun!

Essentially, yes. Computers are very simplistic on a fundamental level; they work by determining whether a transistor switch is turned on or off (by detecting the presence or absence of a positive voltage). With multiple switches in either an 'on' or 'off' state, it is possible to combine that information to make a logical system based on Boolean logic. In other words, you can start to get the computer to abstractly use very simple logic, like denoting whether or not a statement is true or false. Once you have that foundation, making more complex logical systems (as conveniently as we write English) is just a matter of adding more layers of abstraction in the form of programming languages that are more similar to how we use human languages (and are eventually translated back into the language that the computer understands).
 

iapetus

Member
Oct 26, 2017
3,078
If you're using these forms they're for different purposes. A is fine when there's a default value and different values for specific cases. B is way better where there are a number of mutually exclusive cases with their own return value.
 

ray_caster

Member
Nov 7, 2017
664
Neither. For small contingent code I use conditional moves, especially if I want to generalize the code to possibly include data parallelism without explicitly invoking platform-specific intrinsics.
 

Weltall Zero

Game Developer
Banned
Oct 26, 2017
19,343
Madrid
Is all of coding/programming really that easy (or rather, logic based). Because I fully understood the OP despite having zero coding experience whatsoever.

This was really fun!

Logic-based, yes (I mean, obviously; that's how computers work). As easy as the OP, not really; the example is made to be the simplest possible one to illustrate the issue without distraction.

But yeah, coding and particularly its keywords like if, else, etc, are made to be as close as possible to (English) language as possible. Some languages are even closer; for example Pascal (if I remember correctly; I haven't used it since college, 25+ years ago) has "then" after the condition in the "if", and also BEGIN and END instead of open and close brackets.

If you had fun parsing through this, why don't you try learning to code? It is really fun... well, to the sample population composed of me, at the very least. :D Let me know if you're interested and I can point you in the direction of some resources.

That's the same, but much less readable. So good luck getting it when you don't know what this way of writing means.

Uh... what? The ? : operator is not "less readable", or even particularly esoteric at all.

I would argue being able to impress employers with clever code is a real world application of clever solutions.

Nah. There's two types of people that you need to impress when applying for a the job:
- The higher ups that don't know shit about coding.
- The programmers that have probably endured enough of this "clever" (translation: fucking obnoxiously unreadable) coding to last a lifetime.
You can't impress the former with clever coding tricks, because they don't understand it. The latter will discard your application the instant they imagine themselves having to parse through code like that on a daily basis.

Bit of a sidetrack, but in C#, wouldn't case B fail because there's no default Return? Like, I'd have to do this if I wanted to add the explicit else case becuse without the second Return False, it wouldn't compile:

C#:
bool MyFunc()
{
    if (situation)
    {
        return true;
    }
    else
    {
        return false;
    }

    return false;
}

Otherwise, I'd be forced to use A, right? I realise B is clearer to human readability.

Edit: Might this be a compiler quirk if it wouldn't otherwise do this for others?

The code you posted would actually show a warning (if not a compile error, depending on your settings) due to the dead code at the end. The last return at the end is not just redundant, it's unreachable.
 
Last edited:

Prine

Attempted to circumvent ban with alt account
Banned
Oct 25, 2017
15,724
A, declarative all day everyday
 

Jashobeam

Member
Oct 27, 2017
2,523
I use A, because if the function requires a return value having the return statement as the last line seems proper.
 

Tony B

Member
Dec 29, 2018
669
Logic-based, yes (I mean, obviously; that's how computers work). As easy as the OP, not really; the example is made to be the simplest possible one to illustrate the issue without distraction.

But yeah, coding and particularly its keywords like if, else, etc, are made to be as close as possible to (English) language as possible. Some languages are even closer; for example Pascal (if I remember correctly; I haven't used it since college, 25+ years ago) has "then" after the condition in the "if", and also BEGIN and END instead of open and close brackets.

If you had fun parsing through this, why don't you try learning to code? It is really fun... well, to the sample population composed of me, at the very least. :D Let me know if you're interested and I can point you in the direction of some resources.



Uh... what? The ? : operator is not "less readable", or even particularly esoteric at all.



Nah. There's two types of people that you need to impress when applying for a the job:
- The higher ups that don't know shit about coding.
- The programmers that have probably endured enough of this "clever" (translation: fucking obnoxiously unreadable) coding to last a lifetime.
You can't impress the former with clever coding tricks, because they don't understand it. The latter will discard your application the instant they imagine themselves having to parse through code like that on a daily basis.



The code you posted would actually show a warning (if not a compile error, depending on your settings) due to the dead code at the end. The last return at the end is not just redundant, it's unreachable.

Completely agree about the clever code part. Don't get me wrong, "clever" code has it's place, but that place is typically once you've profiled the code, identified genuine bottlenecks and so on, and seasoned programmers are more than capable of researching/implementing these when required (plus it'll be backed up with enough comments about the algorithm/reference code etc. so as to not hurt maintainability). I typically roll my eyes when people by default try to produce uber optimal code in areas that don't really need it. For example, that little command line app for parsing geo-referenced data files that we'll only run maybe 5 times tops probably could have been written without copy/pasting ID Softwares Fast Inverse Square Root function (not joking sadly).
 

metalgear89

Banned
Oct 27, 2017
2,018
Prefer A.

I like minimalism for simple pieces of code. if your code becomes complex trying to be minimilist makes things harder for others to read.
 

Micael

Member
Oct 28, 2017
1,368
Yaps there is definitely a place for clever programming in high performance applications, but if absolutely nothing else it very much needs to be profiled, because branchless programming while beneficial to processing speed by removing the reliance on CPU branch prediction, is also for simple stuff already taken into account by the compiler (well depending on the compiler ofc), so removing the if else statement by getting clever with say a multiplication can actually lead to the creation of more cpu instructions not less.
 

Tony B

Member
Dec 29, 2018
669
Yaps there is definitely a place for clever programming in high performance applications, but if absolutely nothing else it very much needs to be profiled, because branchless programming while beneficial to processing speed by removing the reliance on CPU branch prediction, is also for simple stuff already taken into account by the compiler (well depending on the compiler ofc), so removing the if else statement by getting clever with say a multiplication can actually lead to the creation of more cpu instructions not less.

The first 5 minutes of this gives a good example of exactly that point, where his branchless version produced far less optimal machine code despite the source code appearing to be far more optimal.



Optimisation is an iterative process, there's no getting around that unfortunately. That's not to say we can't preselect algorithms that we know to be faster, for example, I'm not suggesting people always start with BogoSort and work their way down to using a far saner algorithm (not going to name one as I know I'll get a whole plethora of better algorithms thrown back at me!), but it's more when someone starts optimising at a level that's encroaching on compiler micromanagement, then they need to absolutely understand what difference it makes to the compiled code/execution times.
 

Weltall Zero

Game Developer
Banned
Oct 26, 2017
19,343
Madrid
For example, that little command line app for parsing geo-referenced data files that we'll only run maybe 5 times tops probably could have been written without copy/pasting ID Softwares Fast Inverse Square Root function (not joking sadly).

I did assume it was a hyperbolic example until you clarified, hahah. Especially since FISR is the perfect and best known example of esoteric "smart" optimization.
 

Tony B

Member
Dec 29, 2018
669
I did assume it was a hyperbolic example until you clarified, hahah. Especially since FISR is the perfect and best known example of esoteric "smart" optimization.
Sadly not, if I didn't find it funny they thought it was a good idea, I might have been somewhat irked. The icing on the cake in my case is that it's likely that the individual immediately jumping to FISR likely resulted in slower code, especially since many modern processors these days have support for Inverse Square Roots in hardware as a single instruction (plus they were going from double -> float -> double to get that sweet Carmack optimisation they craved so much).
 

ToddBonzalez

The Pyramids? That's nothing compared to RDR2
Banned
Oct 27, 2017
15,530
Is all of coding/programming really that easy (or rather, logic based). Because I fully understood the OP despite having zero coding experience whatsoever.

This was really fun!
Kinda? Programming is basically writing logic in a language that a computer can understand. Obviously the rabbit hole goes way deeper than the simple in examples in the OP, but coding isn't some mystic art. It's a skill basically anyone can learn with some perseverance.
 

Skade

Member
Oct 28, 2017
8,862
Uh... what? The ? : operator is not "less readable", or even particularly esoteric at all.

For someone who never read code and never encountered that, i'm pretty sure it is indeed much less readable yes. I was responding to a non coder. And it's rarely used in such a simple manner as my example. And i mean... I WAS confused the first time i stumbled on it years ago, and i already was working as a dev for a few years at the time. And to be fair, i just don't like it. I think it looks like shit, tho i admit i'm a bit peculiar in how i like my code to look.
 
Last edited:

Micael

Member
Oct 28, 2017
1,368
Yeah the ?: operator is most definitely far less recognized, and borderline unreadable to non coders unfamiliar with it, now obviously that doesn't mean it shouldn't be used, much like say a modulo operation with its usual % symbol might make non programmers think it is something else entirely.

Kinda? Programming is basically writing logic in a language that a computer can understand. Obviously the rabbit hole goes way deeper than the simple in examples in the OP, but coding isn't some mystic art. It's a skill basically anyone can learn with some perseverance.

Yaps things get way more complex when you start having to name things, which is the real hard part of programming, after several years of it still have issues with it, and as far as I can tell all programmers do.
 

Skade

Member
Oct 28, 2017
8,862
Yaps things get way more complex when you start having to name things, which is the real hard part of programming, after several years of it still have issues with it, and as far as I can tell all programmers do.

Indeed, the usual issues often tend to be " Fuck, what's this function for again ? And that var ? Who the hell wrote that ? Ah... That's me... ".
 
Oct 27, 2017
4,927
Sometimes booleans can be fun too if you want everything in a easy to read way and be concise enough to fit in one line:

Code:
mood = value_one * (today == monday) + value_ten * (today == TGIF) + value_whatever * (today != monday and today != TGIF)

I believe it also reduces branching so in my personal experience, it's made a lot of scripts run faster. Definitely test it before you refactor everything lol.
 

Weltall Zero

Game Developer
Banned
Oct 26, 2017
19,343
Madrid
For someone who never read code and never encountered that, i'm pretty sure it is indeed much less readable yes. I was responding to a non coder. And it's rarely used in such a simple manner as my example. And i mean... I WAS confused the first time i stumbled on it years ago, and i already was working as a dev for a few years at the time. And to be fair, i just don't like it. I think it looks like shit,

Fair point, I missed that you were replying to a non-coder.

tho i admit i'm a bit peculiar in how i like my code to look.

Aren't we all. :)

(plus they were going from double -> float -> double to get that sweet Carmack optimisation they craved so much).

Oh man, it keeps getting better, hahah.
 

Tomasoares

Member
Oct 28, 2017
4,532
A, since usually that kind of flow is for guard clauses (if X early return, otherwise do the meat of the function). The example in the OP is so small that it's easy to forget how B often leads to nested hell.

Yeah, something that usually makes the code difficulty for me to read is lots of nested curly brackets
 

Pwnz

Member
Oct 28, 2017
14,279
Places
One of my colleagues way back in interviews got this wrong. They wanted C - a switch case that's more scalable.

Reality is this shit doesn't matter. Inevitably you'll work with a team that is anal about coding conventions, but modern programming languages like python have tox tests that force you to adhere before doing a pull request.
 

exodus

Member
Oct 25, 2017
9,951
It depends on the intent.

A is good if your if statement is validating or checking preconditions before continuing with the rest of the method.

B or ternary would be preferred otherwise.
 

T-Virus

Alt-Account
Banned
Jun 5, 2020
711
B but not with those fucked up braces. I hate when people do that shit

This is way cleaner

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