Which is your preferred way to control logical flow? #programming #javascript

preview_player
Показать описание
#Shorts

Support the Show
* BTC: 1DckZocn7pA7MDzKSu98UbS4TjocfK633x
* ETH: 0x1C0FDD6d450679359876a077A15DFd0537E8C2D8

You can find me on these socials:
* I am an Odysee partner

# Comment Section Rules

1. Be kind to each other.
2. Don't swear, don't use racial slurs (you will be automodded)
3. I reserve the right to permanently ban habitually abusive commenters and I don't apologize. Banned users /won't/ be notified.

If you can't *cope* with having rules, you're welcome to *not* leave a comment.

You can email me at gardiner-at-heavyelement-dot-io

# What are your machines specs?
Office Rig:
* AMD Ryzen 7 1800x
* MSI Pro Series X370 SLI PLUS
* AMD RX VEGA 64
* GSkill Ripjaw V DDR4 8GB x4 (32 GB)
* Fractal Design Define R9 Case
* Manjaro GNOME

Living Room Gaming Rig:
* ASUS X99-E-10G WS
* Intel Core i7-6900K @ 3.2GHz
* NVidia Titan X (Pascal)
* DDR4 Corsair Vengeance RGB 8GB x8 (64GB)

Backup Rig
* System76 Thelio Minor
* AMD Ryzen 5 3400G
* DDR4 16GB RAM
* Zotac Nvidia GTX 970 4GB

Home Server:
* ASUS M5A78L-M/USB3
* AMD FX 6300 at 3.5 GHz
* Nvidia GTX 750 1GB
* DDR3 20 GB RAM

Рекомендации по теме
Комментарии
Автор

it always depends, the nested flow for categorizing data/action, the elimination flow for filtering data.

faisalhakim
Автор

There are many things wrong with the first script:
- Given that you're only trying to check if the input is 1 of the 3 strings (and no specific processing depending on the input), a Switch statement is absolute overkill here. Switch statements have their uses, but this is not one of them. ;)
- Javascript Switch statements use strict comparisons (===), so it will automatically check if the input is a string if you're comparing it with a string. If it isn't, it will go to default;
This means you don't need the if around your switch case, as the Switch statement will automatically set arg1 to the default value;
- There's no need to add a specific case for 'default value', as it will automatically go to default if it can't find it.
- If you're processing a value in a function in order to validate it, I personally prefer not updating/returning the input value, but using an internal value to set and return.

Second script seems better, though I would rewrite it as this:
function inputValidation(arg1){
const allowed_values = ["alpha", "beta", "gamma"]
if(typeof arg1 !== "string' && allowed_values.include(arg1)) return arg1;
return allowed_values[0]
}

(second one is fine as it is, but the programmer in me likes optimizing it a bit; no unnecessary variables, etc...)

Terrible_Tactics
Автор

Definitely the 2nd. In growing code nesting gets harder to read with every statement, especially if you start to use the else tree as well. With guards the assumption after all guard clauses will always be:"Everything is fine, go ahead with whatever you need to do."

heyrim
Автор

2nd

but i do prefer early-exits for the error cases and having the validated values in the end

in the example that would translate to inverting the "in array" check and returning the default value early and having the value itself returned at the end if everything was fine

remissio
Автор

I use a mix of both usually. I'll return out of situations where nesting logic further would get convoluted or I want to exit out of execution early on, particularly in cases where an error condition is met or such. But the nested structure typically is easier to read at a glance so I will nest logic where it makes sense.

onelazynoob
Автор

Return logic looks better IMO, the only thing (for me, I’m not JS developer) is to have returns on a separate line from If statement. The same line returns might be easily overlooked

denys-p
Автор

The first one, and it can be refactored to be much smaller than what you have there.

The use case for switch are very few and far between i.e. because switch is generally easier to read the more things you have to test.

But if that's true, then it's generally a sign you should be splitting things out differently anyway.

marble_wraith
Автор

Definitely the second, it usually results in code with less cyclomatic complexity, that is permutations of distinct code paths in those big ugly if else blocks. This makes it far easier to increase line coverage of automated testing and generally better tests. You do have tests right?

alsweetex
Автор

The way you start your videos is top! (you repeat the 6 letters: friend), so please keep going; this is not meant sarcastic!

yamayama
Автор

What I do know for sure is that I hate weakly typed languages

TagetesAlkesta
Автор

Return for me is much easier to hold in my head than nested when i trying to debug code in my head

leastexpected
Автор

Depends on the complexity of the program. This concrete example is super simple, so definitely option 2.
Option 1 is good for when you want to have different outputs depending on which input you have - pretty overkill for simple input validation.

MeltEmber
Автор

The second option is orders of magnitude easier to refactor and more readable if there are a lot of validation steps (like manually validating dates). I used to code using only one return statement, but I changed my ways when I realized it was faster, easier and more efficient to use the the other approach.

AlbusRegis
Автор

Number two. The "blocking logic" is mostly called "guard clauses". A function should always have a single responsibility / outcome (single responsibility principle) and using guard clauses helps immensely to uphold this rule. Guard clauses also should aim for recovery over early return as much as possible. When you are not doing plain type validation (which you have to do a lot of in JS), the clause should try to get your function back on the "good" path.

TitanNanoDE
Автор

Out of habit, even if the "if" only run "return", i usually put the code to run in a nest simply to make it easier for me to know which one run for each if. I don't go for "switch", and just use "else if" if i have to; simply because max condition i've ever made is 5 (usually just categorization a, b, c, d, e for testing). More than 5, i prefer to use array and "for" loops of "if" and put error handling on each part to know if something goes wrong.

itssilence
Автор

I like my nested statements. It helps me make sure that what I think should happen is happening.

sudge
Автор

Guard clauses makes it easier to read most of the times. Less nesting and you can immediately see what the exceptions/error cases are.

christianbaer
Автор

I prefer early exits. Not only do they reduce indenting, but they also help narrow down the problem. Say you have "if (a != null) {...}" that to me implies that somewhere later down the code, a can be null again and you need to look out for it.

But when you see "if (a == null) return;", that condition is now definitely cleared up for the entire rest of the function and you can read on, knowing that a cannot ever be null again. (Unless your variables are mutable, but I don't often see an early exit condition on those)

nordern
Автор

Blocking logic is my go to it avoids nesting and can help make code far more readable one thing to note is i'd always put {} around my if statements as that way it's consistent!

ThomasSoulard
Автор

Moving from the first to the second style is called "Replace Nested Conditional with Guard Clauses" in Martin Fowler's "Refactoring" (2e, p.266).

"If the method is clearer with one exit point, use one exit point; otherwise don't"

giving a strong preference to the guard clause style.

PeerReynders