It is a smart solution to the problem and with better formatting it would probably be better code, but with everything on one line like this it's really hard to see what is nested into what.
I used to write code like this, it looks better because it's shorter, but I learned after a while that readability is so much more important than writing short code.
I work with JS every day, and it took me some time and a lot more brainpower to read the second one.
A lot of it comes down to personal preference I suppose, but the consensus seems to be that nesting like this on one line is hard to read.
I agree that the solution is better, but i would split it up more, into multiple variables with good names, to avoid the nesting and make it more apparent what each step does.
While I understand this may be considered bad code; personally as someone who has barley touched javascript the top code I can understand, the new code is more or less a guessing game to me.
He made it imperative rather than declarative. This is a common discussion alongside frontend developers whether to follow the imperative principle or not cause of readability issues.
I anticipated this response, but imo less code is easier to read by merit of there being less to read (As long as it's not ridiculously obfuscated, of course).
The new code can also be broken into multiple lines and commented.
The old code is very unoptimized and could be improved without "golfing" it, regardless.
Edit: I guess that was an unpopular opinion. Still, I think the new code can be made just as readable as the old with good formatting.
No, I'll double down. If you know what .map does, the new code takes a few seconds to figure out. Date strings, Set, Dates, boom, done. The old code is a mess with a weird edge case for the first item that requires you to think about the logic of uniqueness rather than simply asking the interpreter for it. I swear, this sub seems to think every bulky convoluted mess is actually better and "mOrE REadAbLe" because it doesn't use linq or whatever other perfectly good method they don't understand.
Huh. I’m a Junior dev, so I’m no expert or anything. But the old code is more legible to me. I could pretty much just go line-by-line and “get it.” Even though I understand the new code, it took me longer to get. It’s more concise, yes. But I really had to think about each step. But idk, I can admit I’m not the best. So maybe it’s just me.
There is a reason I prefer Lua over any other language. There is no discussion about if you know the language or not. The language definition itself fits on less than an A4. Since I don't know javascript I would copy paste your first or your second example and assume it's the way to do it.
The second one needs more attention since you are using language typical constructs. It still looks less daunting than lambda functions in python. In python the language is so alien to lambda functions they even had to add a lambda construct into the language to make it possible.
What I do think is discomforting is that the language does not support hashed objects.
I think you're right in this one. The best code I have ever written followed the "One Line does one thing" rule. Splitting up the second approach here into different lines and commenting would be a good first step, but code should be legible first, functional second. Nobody is going to be able to maintain code that's hard to read, even if you figure it out after a few seconds, since it still requires more mental effort to understand.
While I agree that the formatting could be better on the last one, it's still simple to go command by command. He maps it all to utc dates, then he creates a set and he converts to date. It's like 3 commands, all of them quite basic.
Well, hopefully the whole thing is a function with a sensible name, in which case I don't see the need for a comment. But yeah, either making a variable for the date list (as the nesting with the set creation require some thought) or splitting it in a few lines should be enough.
Controversially to the majority of comments here, I work with JS a lot, and the new code is much quicker to understand. Only thing I'd do is assign the set to a "uniqueValues" const, and use that in the dates assignment. Just so it's more legible for those who don't know what a Set does
It's okay if they don't know what Set and .map do, I guess, but the issue there is knowledge, not complexity. And the new code is not anywhere near as complex as they seem to be implying.
This is common attitude I see in developers, and it's really toxic. Someone not knowing a language feature doesn't mean anything. We were all beginners once.
For example, I know developers who have no idea of what C# "records" are, but they blow the average dev out of the water.
Objects are equal only if the come from the same reference. So of your example you put the today in an array twice so the array has a reference to it twice. Meaning that once you create a set the duplicate date will be removed.
In order to separate the objects you can use Lodashs Clone or CloneDeep to break the references up. Now in JS the Map function returns a brand new array with new references so nothing is equal in reference to each other even if it was before. It's also a limitation when dealing with an object array containing objects with duplicate values though the references are different.
A lot of people will reflexively say the new code is "not readable", incorrectly thinking this is ninja code. Just format this into a few lines and make comments. Functional programming like this is very easy to interpret if you are used to the pattern. It's needlessly taboo to the point of being obnoxious.
Lots of people saying the original code is more readable. Personally I found the new code more readable. Parsing out procedural logic can be complicated, and writing code that way tends to be more bug prone in my experience. That being said, I don't actually think the original code was all THAT bad. I mean there's room for improvement, but it did what it needed to do decently well enough. Both are O(n2) if I read them correctly. I think it might be just a case of "data brained programmers vs logic brained programmers"
Edit: the only way I could really see improving the second code is to split formatting to multiple lines. It would be nice if JavaScript had some sort of dot notation to turn an array into a set, or at least a pipe operator. That would make things really easy to read but alas.
I don't think so. The first is definitely O(n^2). For the second implementation, the collision will be based on a hashing and therefore O(1) with the assumption that the hashcode implementation is of high quality, resulting in overall O(n) performance.
I prefer reading the first but it could easily be implemented with a for loop and a Set rather than the duplicate flag with a search.
Doh! You're right. Second is definitely O(n). When you put it that way, the first example is definitely less efficient. Still not too bad compared to most of the code on this subreddit though.
I don't really want to know it, but this code seems to suggest that Set objects don't have map() method... because why would you ever want to call a function on every element of a set, right?
Also, this seems to suggest that you can only make sets of strings? Some Shell flashbacks right here...
Okay, I was being a bit of a showoff (wrongly, I've come to realise, since it shouldn't be on one line at all), but I would have happily posted the old code only, since it's not remotely acceptable.
Would you say this is more readable or should I break it down even more and only make one action per line?
// map and remove duplicate date strings
const dateStrings = [...new Set(championshipGames.map(game => game.date.toUTCString()))];
// map date strings to date objects
const dates = dateStrings.map(dateString => new Date(dateString));
This looks pretty good to me, but I'm in the camp or not having any problems with the 2nd version of the code in the first place.
If you want to make things even clearer, you could store the dates as strings in its own variable. Store those turned into a set in their own variable. And then finally store the set mapped into dates in its own variable. Three steps is still much shorter than the original code.
I'd write up the code, but I am on a phone right now
EDIT:
// need strings cause objects can't be used in dedup
const dateStrings = championshipGames.map(g => g.date.toUTCString());
// deduped strings
const dateStringsDeduped = [...new Set(dateStrings)];
// final array of deduped dates
const datesDeduped = dateStringsDeduped.map(s => new Date(s));
It's not THAT much more readable than yours. Yours was fine I think, but who knows - maybe this would save a junior dev some brain cycles. Readability is very subjective.
More or less. My focus was more to separate things based on the function syntax though, because I think that is what makes OP's second version of the code difficult for developers to parse. The first line uses dot notation, the second line uses standard notation, and the final uses dot notation.
My opinion is that most of the comments are too obvious. I think variable names, and maybe either separating it into a function or just one comment at the top is enough to tell the reader what the code is supposed to do. The only comment that is useful, in my opinion, is the one that explains why we are converting the Date objects into strings in the first place - because it isn't obvious to someone that isn't very familiar with JavaScript.
Example 1: (If function is going to be used in multiple places)
championshipGames.uniqueDates = function () {
// need strings cause Dates won't be deduplicated in Set
const dateStrings = championshipGames.map(g => g.date.toUTCString());
const uniqueDateStrings = [...new Set(dateStrings)];
return uniqueDateStrings.map(s => new Date(s));
}
const uniqueDates = championshipGames.uniqueDates();
Example 2:
// Get array of unique dates
const dateStrings = championshipGames.map(g => g.date.toUTCString()); // need strings cause Dates won't be deduplicated in Set
const uniqueDateStrings = [...new Set(dateStrings)];
const uniqueDates = uniqueDateStrings.map(s => new Date(s));
That the old code reads better (to some people) is besides the point. It scales worse. They're doing a linear search and comparison for each element before adding it. Dates should have been a set.
To everyone complaining about how the new code is less legible, then you just haven't worked with data streams before (though I will agree that when chaining method calls, they should all be on their own line). Mapping is a very common concept in Java, Python, Javascript, Ruby (and I'm sure plenty more that I haven't personally used). The only language-specific operator I see is the spread operator (...), but if you're familiar with JavaScript, you'd know what it does, and if you didn't, but are writing JavaScript, it'd be worthwhile to learn.
The spread operator takes an array/list and spreads it into the individual items. This let's you repackage (there is probably a better word than that) a collection. In OP's code they are repackaging a Set into an Array. Another cool thing it lets you do is: say you have all of the parameters to a function in an array. Rather than call the function with (arr[0], arr[1],...) You can just write (...arr).
Hard disagree. Sets by definition have no duplicates, using a filter means you have to think about the logic of why duplicates are removed, and imo is much harder to understand.
Using sets to determine uniqueness is more efficient by an order of magnitude. Your suggestion is essentially a nested loop which changes the algorithmic complexity from linear to exponential.
There are two map statements because it goes Date > string > Date. This is because JavaScript Sets don't recognise when objects are identical, so they have to be strings for that part.
Almost everything posted on this sub "gets the job done", that doesn't make it good code. Old code is O(n2) while new code is O(n), as other people have pointed out.
The new code eliminates duplicates by turning an array into a set and back into an array. This works because set objects don't store duplicates.
both bad. first seems to have some unintentional behaviour, but is better because it can be read more fluently. the new one has all the nice syntactic sugar, but is like a huge bowl of spaghetti condensed into one line.
Readability is the most important thing in Clean Code imho.
While personally, I prefer the first one because I use a procedural language primarily (Go), the second is easier to read for me, but in my opinion, that is only because the first one's logic isn't great. I'd have used a data structure that doesn't contain duplicates, like a set, or in Go, a map[time.Time]struct{}. Then I feel they'd both be roughly equal in readability, but I see how the second would be preferable in a language that uses that pattern commonly.
Good code = readable, and efficient code. Your new method is clever, but realize that not all developers will want to use it like that. This is especially true if they had to debug it for some reason.
The New code is actually bad code so this still fits the sub I guess. What happens when someone else comes along and has to decipher this one liner? It's going to take significantly more time than to just follow through the original implementation.
Readability and maintainability is KING, end of story.
Everyone keeps saying this, but every time I try to read over the code, the one liner feels like it takes a tenth of the time to understand. Anyway, as other people have pointed out, the new code is the correct method by far, it just shouldn't be on one line.
Ooh hot take. There's a variety of opinion about this it seems.
Still, I'd rather write 3 lines that everyone can understand than have one line for the sake of it. Especially when those "inexperienced devs" might get their hands on it.
If you want to reduce lines of code from 10 to 1, you need to write not only 1 line of new code but also 9 lines of comment to explain what the hell you did because in most case, 1 liner is very harder to read and understand. That way you can spend 3 minutes of writing comment for the sake of 30 minutes of your new junior who's gonna inherit this code from you and trying to fix a bug somewhere near this line
I like the new code, but it is important to be aware that it iterates more times, which could be important for a large number of items I am a dum and didn't pay attention to details! Other than that, just put some newlines for readability and it's good. I think it takes less time to understand. There are like 3 things; understand each one, and you're good. The old code has way more things to think about, and more context to keep in mind. Each thing is very simple, but still.
The new code does not iterate more times. It is actually more efficient by an order of magnitude. The new code is linear in the worst-case O(n+m) while the old code is exponential in the worst-case O(n*m).
where m is number of unique dates and n is number of games.
The old code is O(n*m) because for every championship game we loop through the entire dates array.
The new code is O(n+m) because first we loop through the games, then again to insert the dates of those games into a set, and finally loop through the unique dates to get our result. That is O(n+n+m) => O(2n+m) => O(n+m).
As a rule of thumb, it is almost always better to have loops side-by-side instead of nested.
Touche! I totally skimmed past that inner for loop in the old code. This is another vote for less code (assuming the shorter code is not overly opaque of course).
Good code is readible, self documenting code. The first is better than the second, even if the second is more concise. If I was maintaining this code, the first bit would be way easier for someone unfamiliar to understand.
Whitespace can also solve the problem by separating your code into newlines
204
u/Xuntari Apr 13 '22
It is a smart solution to the problem and with better formatting it would probably be better code, but with everything on one line like this it's really hard to see what is nested into what.
I used to write code like this, it looks better because it's shorter, but I learned after a while that readability is so much more important than writing short code.
I work with JS every day, and it took me some time and a lot more brainpower to read the second one.
85
u/ItsT1ps Apr 13 '22
While I understand this may be considered bad code; personally as someone who has barley touched javascript the top code I can understand, the new code is more or less a guessing game to me.
23
u/Lataero Apr 13 '22
Controversially to the majority of comments here, I work with JS a lot, and the new code is much quicker to understand. Only thing I'd do is assign the set to a "uniqueValues" const, and use that in the dates assignment. Just so it's more legible for those who don't know what a Set does
11
u/xcski_paul Apr 13 '22
Why is the new code changing it all to strings then changing it back to dates?
7
u/jonnysteps Apr 13 '22
Comment game strong
7
u/whoopsdang Apr 13 '22
A lot of people will reflexively say the new code is "not readable", incorrectly thinking this is ninja code. Just format this into a few lines and make comments. Functional programming like this is very easy to interpret if you are used to the pattern. It's needlessly taboo to the point of being obnoxious.
4
u/zerofox2189 Apr 13 '22 edited Apr 13 '22
Lots of people saying the original code is more readable. Personally I found the new code more readable. Parsing out procedural logic can be complicated, and writing code that way tends to be more bug prone in my experience. That being said, I don't actually think the original code was all THAT bad. I mean there's room for improvement, but it did what it needed to do decently well enough. Both are O(n2) if I read them correctly. I think it might be just a case of "data brained programmers vs logic brained programmers"
Edit: the only way I could really see improving the second code is to split formatting to multiple lines. It would be nice if JavaScript had some sort of dot notation to turn an array into a set, or at least a pipe operator. That would make things really easy to read but alas.
9
u/nittendev Apr 13 '22
When the new code is the bad code.
2
u/[deleted] Apr 14 '22
I don't really want to know it, but this code seems to suggest that
Setobjects don't havemap()method... because why would you ever want to call a function on every element of a set, right?Also, this seems to suggest that you can only make sets of strings? Some Shell flashbacks right here...
2
u/propostor Apr 13 '22
I think you just wanted to show us all you managed to write it all in one line.
The old version is perfectly acceptable code, if not a little bit cumbersome.
The new version is the opposite, it's not easy to follow unless you really know what you're looking at.
5
u/StampeAk47 Apr 13 '22
Would you say this is more readable or should I break it down even more and only make one action per line?
Trying to learn how to write readable code.
4
u/HeyZooos Apr 13 '22 edited May 15 '22
That the old code reads better (to some people) is besides the point. It scales worse. They're doing a linear search and comparison for each element before adding it. Dates should have been a set.
4
u/StrongJoshua Apr 13 '22
To everyone complaining about how the new code is less legible, then you just haven't worked with data streams before (though I will agree that when chaining method calls, they should all be on their own line). Mapping is a very common concept in Java, Python, Javascript, Ruby (and I'm sure plenty more that I haven't personally used). The only language-specific operator I see is the spread operator (...), but if you're familiar with JavaScript, you'd know what it does, and if you didn't, but are writing JavaScript, it'd be worthwhile to learn.
The spread operator takes an array/list and spreads it into the individual items. This let's you repackage (there is probably a better word than that) a collection. In OP's code they are repackaging a Set into an Array. Another cool thing it lets you do is: say you have all of the parameters to a function in an array. Rather than call the function with (arr[0], arr[1],...) You can just write (...arr).
1
u/[deleted] Apr 13 '22
I think the nicest solution would be use lodash/ramda function which does that. But depends if your codebase uses those of course. :)
1
u/NikZM Apr 13 '22
Deduping with iso strings and sets seems hacky and unitutive. I would opt for using a filter((obj, i, array) => arr.findIndex(obj) === i)
1
u/FrezoreR Apr 13 '22
There's way too much happening on one line in the new one.
I suggest using line breaks to make functional chains easier to read.
I don't think I understand why there are two map-statements after each other. One should be enough.
1
u/DaFyre2010 Apr 13 '22 edited Apr 13 '22
Nothing wrong with either. They get the job done, right?
"old code" is v1, "new code" is v2.0, lol.
Edit:
As one who is not overly familiar with the "new code" style of coding... how do you deal with duplicates there?
3
u/Darkpolearm Apr 13 '22
I'm genuinely scared by the amount of comments saying ur new version isn't readable
1
u/haasilein Apr 13 '22
both bad. first seems to have some unintentional behaviour, but is better because it can be read more fluently. the new one has all the nice syntactic sugar, but is like a huge bowl of spaghetti condensed into one line.
Readability is the most important thing in Clean Code imho.
2
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 13 '22
Image Transcription: Code
I'm a human volunteer content transcriber and you could be too! If you'd like more information on what we do and why we do it, click here!
2
u/ArsenM6331 Nov 15 '22
While personally, I prefer the first one because I use a procedural language primarily (Go), the second is easier to read for me, but in my opinion, that is only because the first one's logic isn't great. I'd have used a data structure that doesn't contain duplicates, like a set, or in Go, a
map[time.Time]struct{}. Then I feel they'd both be roughly equal in readability, but I see how the second would be preferable in a language that uses that pattern commonly.3
u/[deleted] Apr 13 '22
Good code = readable, and efficient code. Your new method is clever, but realize that not all developers will want to use it like that. This is especially true if they had to debug it for some reason.
0
u/CastielUK Apr 13 '22
The New code is actually bad code so this still fits the sub I guess. What happens when someone else comes along and has to decipher this one liner? It's going to take significantly more time than to just follow through the original implementation.
Readability and maintainability is KING, end of story.
1
u/[deleted] Apr 13 '22
I'm still docking you for making "dates" mutable. :)
1
u/Tensh1_267 Apr 13 '22
If you want to reduce lines of code from 10 to 1, you need to write not only 1 line of new code but also 9 lines of comment to explain what the hell you did because in most case, 1 liner is very harder to read and understand. That way you can spend 3 minutes of writing comment for the sake of 30 minutes of your new junior who's gonna inherit this code from you and trying to fix a bug somewhere near this line
1
u/recycle4science Apr 13 '22 edited Apr 14 '22
I like the new code, but it is important to be aware that
it iterates more times, which could be important for a large number of itemsI am a dum and didn't pay attention to details! Other than that, just put some newlines for readability and it's good. I think it takes less time to understand. There are like 3 things; understand each one, and you're good. The old code has way more things to think about, and more context to keep in mind. Each thing is very simple, but still.-1
u/oali0000 Apr 13 '22
Good code is readible, self documenting code. The first is better than the second, even if the second is more concise. If I was maintaining this code, the first bit would be way easier for someone unfamiliar to understand.
Whitespace can also solve the problem by separating your code into newlines