TL:DR
See bottom;
The breakdown
After reading the discussion If/else or just if?, it made me think that it might be helpful ...
For further actions, you may consider blocking this person and/or reporting abuse
Gotta admit, that does indeed look a hundred times more readable (assuming you're familiar with regular expressions).
I would just like to chime in on this line of code in the final example:
I think it would be better if the fallback value was
null
instead offalse
. It doesn't change anything about the program, but semantically,null
makes more sense because the variabledomain
expects a string value. If we were to stick with usingfalse
, then I don't think it makes sense that adomain
name is a Boolean value. I think it would make more sense to say that it isnull
, or rather nonexistent.But then again, I might just be nitpicking here. Nonetheless, it still is a hundred times more readable than the initial code.
I like your argument and I agree with you. Thank you for the feed back btw!
No problem, man! Great article. It made me think of how I could refactor my code in a similar way.
I’m glad to hear! I will add more to it tomorrow as I wasn’t able to list all my tricks. But this should be a good start. Thank you!
My try on this:
Added this to the tips! Gave you credit.
I have seen this and used it in the past. I am less likely to use this but it still gets the job done! And much smaller. Thanks for your feedback.
Mind to elaborate? 🙃
Sure! First I'd like to say that I find nothing wrong with your solution. I just prefer to avoid using try/catch as a way to soak up possible errors unless I plan on dealing with those errors.
I use try/catch when intentionally handling errors that would be thrown. Example borrowed from Mozilla for lack of valid example off top of head.
I am clearly opinionated here :)
This works and it reads clearly, but it is devoid of specificity.
You desire to control flow on state, not on error. Error is normally flow control failed.
The code tells nothing about what is expected, only it might fail in certain generic ways.
Try excepts are essentially GOTOs, as flow control they smell?
People will point to the performance hit, but creating the additional stack frame and even unwinding it is usually significant.
The variability of being able to optimize the code in the protected frame varies, so can hit perf noticably or nearly none.
Unless you are using ES7 try blocks are synchronous, so careful with this approach.
My real concern it is backwards and -to me- lazy. If your state is bad in a known detectable way why continue much less spread it to myroutine which may incur other side effects due to caller pollution. Then finding it assuming myroutine has some protection is up the call stack we go.
There are cases where this is the only real choice and there are cases where detection is expensive and or very rare so the trade-off might be compelling. Otherwise, if never approve the PR.
I appreciate that you don’t just accept it and you have an difference of opinion. The world would be boring if no one challenged others. I would love to see you write out the code to show what each of your points refer to.
I am curious, with the "cunningham's law" post, are you stating that you think I'm wrong on my post? If so I'd be happy to hear why you think so.
No, I didn't think you were wrong. I had the impression you were searching for a more concise solution 🤣
It was to show others how they can clean up their code to make it smaller and easier to read. Yours definitely does that. lol. Thanks for providing feedback.
Three minor additions: you can omit the ternary in your case in favor of a logical gate and you should use
/regex/.test(string)
instead ofstring.match(/regex/)
if you don't want to do anything with the result and lastly, you don't want domains like localhost.mydomain.com to be interpreted as secure, so better make sure that regex captures the whole domain string - so now it looks like this:I would even think that using a direct comparison for the domain would be faster and more readable than the regex, so now it becomes:
Aw! you're so right! I should have used test vs match, also I should have added in $ for an exact match. I'll update this! Part of the fun was to show people they can resort to regex when doing multiple test against a single variable. If it was another scenario of checking the domain against lets say 3 or more possible values, then regex is a quick way to solve this.
Thank you for the great feed back.
You're welcome. I'm usually rather eager to solve things with regex myself. So I usually think again: "will a regex make that code better?" and try it without the regex. In ~50% of the cases, I keep the regex. For the sake of having an example, I feel it's justified. For live code, I would have removed it.
I like your clear view on this. I agree that the regex is over kill when we are only checking two values.
While this obviously works, I personally don't like this style of code.
Ok it takes up less screen real estate, but it's operation is not obvious.
Fundamentally code is a document and a document is useless if it is difficult or impossible to read.
What is difficult to read it what is obvious to you strongly depends on what you're used to. Using logical gates is pretty common for example in Python.
So basically your judgement depends on your own bias for a certain style.
I am not familiar with JS since I write in another language, but your example is clear enough to follow.
Still, I did not find that the examples after the first improvement got any better. To me, "more readable code" is not necessarily "shorter code" and - again - I am not very familiar with JS, but your final result is not very readable to me. You abstract away code in a const, and I am an advocate of doing that but these constructs are so small that I find it gains little. Personally I would have stopped after the first improvement. Improving the code is good, but remember that better is the enemy of good enough ;)
For some of the people out there, this may not be a style they like. I also could have also went in to more detail as to why abstracting out the logic to constants can help clean up the code, with more scenarios. But for many people, they like this and it helped them. So it’s really about taking what works for you and leaving the rest behind.
Regex is not much readable when there are more strings.
This is for me better solution:
This is also a very nice solution. I’ll add it to the tips! Thank you. I know that for some people, regex can be a eyesore. But there is beauty in its power.
Not much difference but I like to use sets for these comparisons for faster lookups.
I actually also like this as a solution. Thank you!
Yay for a more declarative style of programming, nice walkthrough! :)
A tip for future reference, you can highlight code blocks by appending the name of the language, in this case
javascript
at the end of the three backticks, like this:this is the result:
Ha! I knew that one but assumed the site didn’t handle it. Dummy me for assuming. Thanks for the compliment and tip!
It could be made even prettier if js had null-propagation and elvis, IE:
(excuse my bad coding, writing on phone)
I tried this and it did not work for me. I'd love to see a work example as I have seen this pattern before but couldn't remember to do it.
It's not supported in current ECMAscript. However, a standard proposal called "optional chaining" is currently accepted: github.com/tc39/proposal-optional-...
Wow I hadn't caught up to that. Very interesting share. Curious to see if it gets implemented.
Out of curiosity, before reading the article I copied the initial example and tried my best on it myself.
This is what I ended up with:
On one hand, I feel ridiculous I have a function that will only run once.
On the other, there are no
let
bindings in the file.I did consider
Array.prototype.includes()
but elected not to use it for just two elements.I don't think the RegEx has good readability, especially having had to escape the dots.
I also noticed that you used
===
for comparing to"undefined"
but==
for the domain.Is there a reason you are using
hasOwnProperty
instead of just the truthiness of the objects? Is it more performant?Myself, in the process of writing this, I went back and changed it, and was happily surprised that
So I loved that you took try at it. You did good!
Doing a function is typically a sure thing. It's never stupid to abstract out to a function. It's a great habit to practice. Even if it only gets used once, you are completely right about it helping to avoid having to do things such as declaring additional variables and also making the assignment highly clear
const secure = needsSecure()
vsconst secure = !isLocal;
.Now far as this part, you can do 1 better.
this instead, removing an additional
if
statement.With the RexEx, that was more of an option to show others that you could bring in RegEx to do your checking. But you and others have pointed out, that my goal was to make the code more readable... so to a lot of people, it's hard to read so therefore it did not make the code "easier to read".
Far as strict comparison, vs non-strict. That is a bad habit I need to break. You caught me red-handed lol. Stick with using strict comparison, and only use non-strict as needed.
Now for the final part,
hasOwnProperty
is there for a good reason. I am wanting to specifically check for a Boolean answer, sohasOwnProperty
will give me that. You can definitely do it your way and it'll work. When it's a single variable, that is how I do it.When I'm digging down in to an object I prefer to be more intentional with it by using
hasOwnProperty
So then, something like this?
I guess.
It's actually really unclear how to do such checks, you have to keep in mind what failures you actually expect to have.
On one hand, if you expect an object, truthiness gets rid of
null
,undefined
,false
(we'd be getting thefalse
from the typeof equality, as well ashasOwnProperty
) as well as less importantly0
, and""
.But on the other hand, if you expect a number, you will have weird failure on
0
, which is very commonly a normal number. In which case you often check for undefined.But it doesn't solve everything!
Maybe we should always use
typeof
:/But what is your next action if
hostname
is an object? Pretending it wasn't set and defaulting to secure?Honestly, truthiness seems like the best bet to me, I just need to keep track of when it can be a
0
or""
or a literal significantfalse
and it'll be okay.I think I'll just keep using that.
Wow, I have never realised how useful can be this declaration of variables on top. Going destroy a bunch of my else statement at once! Thanks.
I’m super happy I could help you learn some new tricks!
Nice cleanup and great explanations
Thank you!