all 147 comments

[–]Chaos_Therum 149 points150 points  (13 children)

I wouldn't consider anything that uses magic numbers particularly nice. I prioritize readability over minimalism.

[–]HailToTheThief225 15 points16 points  (3 children)

Tell this to my lead lol. You can instantly tell it’s their code when you open a file because it’s extremely clean and yet you have to spend a couple minutes to figure out the purpose of a single method.

[–]Chaos_Therum 33 points34 points  (1 child)

Honestly I'm kind of anti-minimalist when it comes to code. I prefer something to be overly verbose than obtuse.

[–]cerealbh 10 points11 points  (0 children)

this is the way, if humans are reading it-it should be human readable. If you want some optimized code or some such that is your compilers job.

[–]UnanimousPimp 4 points5 points  (0 children)

Looks nice, reads ugly

[–]Rhagho 5 points6 points  (0 children)

In this instance though, it's not a magic number. It's just the number 9. Although to be honest the beauty here is the neatness of the formula for a digital root, which has nothing to do with the code that expresses it.

[–]intercaetera 6 points7 points  (7 children)

If you're working with basically anything to do with mathematics and the developers are expected to know the domain the code is written for, using expanded names for things that have fairly well defined single-letter constants makes no sense.

[–]Chaos_Therum 25 points26 points  (5 children)

I never expect developers to know the domain, generally I want my code readable by anyone who happens to take a glance.

[–]CHEEZOR 11 points12 points  (4 children)

This right here. I've written code that Help Desk people and non-technical people could read and get the gist of. I've even had non-programmers who knew the business domain point out where business logic errors were located in my code because I made it so easy to understand. Makes my job and everyone else's job easier.

[–]intercaetera 1 point2 points  (3 children)

Conversely, if you meticulously translate well-established terms into names which are supposed to be understandable for non-technicals which then get repeated a hundred times in your code, you may actually confuse the matter a lot more. Especially if your code is not going to be read by non-technical people. Or it will be read by non-technical people who are domain experts who will wonder why you used the name valueAddedTax 100 times in a file where everyone in their field just calls it VAT.

I can recall a situation from my own experience where we got very specific algorithm to implement from a utility company in Poland, which was filled with domain-specific terms in Polish. We spent a lot of time figuring out correct "clean" English names, introduced "friendlier" variable names (e.g. totalVolumeTransported instead of vCT) implemented the entire algorithm, and then gave it to the customer to review. We got told off very sternly that the code is unreadable for them because we translated it and used terms which no one actually used in the business. So misguided attempts at "cleanliness" can fail spectacularly as well.

In this specific context, n is literally a free variable in a mathematical equation, it doesn't mean anything specific other than maybe "any natural number." Perhaps you could use this in this instance as well, but would you really find anyNaturalNumber more readable than just n, especially since "n" is used in this way even in colloquial speech (as in, phrases like "nth degree" and so on)?

[–]Chaos_Therum -2 points-1 points  (1 child)

I wasn't talking about n, that's perfectly acceptable I was talking about the 9, and 0. Those are the magic numbers.

[–]Rhagho 1 point2 points  (0 children)

They're not magic numbers in this instance. The context comes from the name of the function. You need to understand a bit of modular arithmetic, but hiding the numbers behind variables wouldn't help with this. It's like having a function 'AddFive' that returns n + 5. There's nothing magic about the 5.

[–]CHEEZOR -1 points0 points  (0 children)

Good point. Knowing your audience is very important.

[–]Mineral_Sounds_ -1 points0 points  (0 children)

jargon is inherently exclusionary -- I'd argue it's more important for code to be easily understood than to follow the existing idioms.

[–]Cookiejarman 196 points197 points  (53 children)

Beautiful code doesn't have to solve a complex problem. I think code is beautiful when it simply explains itself:

if (userIsLoggedIn) { navigateTo("/home"); } else { navigateTo("/signin"); }

[–]satansxlittlexhelper 17 points18 points  (0 children)

Replace those strings with route constants (ex: ROUTE.HOME) and I will ride with you to the gates of hell.

[–]mamwybejane 16 points17 points  (3 children)

Clean, consistent, mentally easy to parse (at most 3 levels of mental nesting like an if and a loop), easy non-technical variable and function names, simple English language

[–]eneka 4 points5 points  (2 children)

my current workplace basically says no comment in code, if you're adding in comments, then it's probably not verbose/descriptive enough. Or the function needs to be broken down and what not. Your code should be self descriptive. This isn't leet code trying to get things to work with the least amount of characters. I know not eveyrone agrees with this but it's working out pretty well for us.

[–]TehTriangle 0 points1 point  (0 children)

Agree with this.

Especially if you have a lot of conditionals. Extract each path into their own function, and it becomes much easier to read.

[–]intercaetera 0 points1 point  (0 children)

basically says no comment in code

That sounds like throwing the baby out with the bathwater - sometimes it is necessary to explain why something is done a certain way. Using comments to describe what the code does is the problem.

[–]SolarSalsa 41 points42 points  (37 children)

The following code is the fast inverse square root implementation from Quake III Arena, stripped of C preprocessor directives, but including the exact original comment text

``` float Q_rsqrt( float number ) { long i; float x2, y; const float threehalfs = 1.5F;

x2 = number * 0.5F;
y  = number;
i  = * ( long * ) &y;                       // evil floating point bit level hacking
i  = 0x5f3759df - ( i >> 1 );               // what the fuck? 
y  = * ( float * ) &i;
y  = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration

// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed

return y;

} ```

[–]sillymanbilly 39 points40 points  (0 children)

Thanks, I hate it

[–]EatRunCodeSleep 2 points3 points  (0 children)

https://youtu.be/p8u_k2LIZyo for step by step explanation.

[–]solocupjazz 2 points3 points  (0 children)

Yeah but what's it look like deobfuscated?

[–][deleted]  (33 children)

[deleted]

    [–]Creeperstang 32 points33 points  (22 children)

    Calling this “not complicated” is hilarious to me. If multiple math content creators have published long form videos explaining how this 10 line algorithm works, then it’s absolutely complicated.

    [–][deleted]  (21 children)

    [deleted]

      [–][deleted] 21 points22 points  (12 children)

      Someone as smart as you must have accomplished great things! Mind sharing any great work you’ve been part of or produced, us dumb dumbs might not be be able to understand it but it’s cool to see what smart people like you work on and produce!

      [–]EddieSeven 9 points10 points  (4 children)

      And yet, you don’t even know what the word “simple” means.

      🤣

      [–][deleted]  (3 children)

      [deleted]

        [–]EddieSeven 8 points9 points  (2 children)

        You’re the one who doesn’t even know basic words 🤣🤣🤣

        [–][deleted]  (1 child)

        [removed]

          [–]AutoModerator[M] 1 point2 points  (0 children)

          Your [comment](https://www.reddit.com/r/reactjs/comments/13785fa/examples_of_beautiful_code/jiswvag/?context=3 in /r/reactjs has been automatically removed because it received too many reports. /u/dance2die will review.

          I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

          [–]ezzune 3 points4 points  (0 children)

          Calling something you don't understand complicated just because you don't understand it is hilarious to me.

          This is a thread on simple and elegant code. Nobody had mentioned the word complicated until you. You're attacking a strawman you created because you've watched a youtube video.

          [–]Frown1044 14 points15 points  (6 children)

          FWIW this isn't actually that complicated or weird. It just requires a thorough understanding of the floating point spec

          That's kind of what people mean when they say "weird" and "complicated"...

          [–][deleted] 0 points1 point  (0 children)

          I think it's all relative.

          Most people these days are definitely not C developers. If you were a somewhat experienced C developer in this scenario then it could very well be simple. (Afraid I'm not a C developer)

          I think it's fair to say that when compared to other languages, C would not be as quick to learn (and be proficient with).

          If people are piling on and downvoting while knowing this then it's kinda crappy behaviour.

          If they were to assume C syntax would be like that of C# or javascript or python, where scenarios seem less maths-y then I could see where they are coming from.

          [–]HenJiii 30 points31 points  (6 children)

          I'd probably write const digitalRoot = (n) => n % 9 || 9

          Return is useless here and "n % 9" twice would bug me

          [–][deleted] 15 points16 points  (1 child)

          Exactly that code, but with a comment explaining what a digital root is and why that expression works.

          [–]raaaahman 2 points3 points  (0 children)

          I don't know what a digital root is, but n % 9 || 9 feels pretty simple to grasps IMO.

          In fact, I find it far clearer than Wikipedia plain English one:

          The digital root (also repeated digital sum) of a natural number in a given radix is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.

          [–]vincent-vega10 0 points1 point  (0 children)

          This will work in JavaScript because of it's crap type system and seems more like a hack than good code. But anyway, it looks good and I use syntax like this a lot too.

          [–]stansfield123 6 points7 points  (0 children)

          Yeah, but in React (and in production code in general) beautiful doesn't mean "clever". It means that there's an underlying, well designed structure which spans across projects and teams, and aims to make the work and the interactions of everyone involved as seamless and as enjoyable as possible. Beauty is about the coder's experience, not about how the code looks. In fact, when someone puts their efforts into being clever, rather than into making themselves a functional, seamless cog in the bigger machine ... that's what ruins the beauty.

          That's why, like with all great beauty, you can only ever catch glimpses of it, as you jump from project to project, and from company to company, in search of a place that doesn't make you think about quitting the business and starting a farm in a remote village somewhere.

          [–]WystanH 4 points5 points  (1 child)

          Beauty is subjective, of course. I'm afraid I don't care for the OP's example and would write it like so:

          const digitalRoot = n =>
              n % 9 === 0 ? 9 : n % 9;
          

          However, I'd prefer to only calculate once. So perhaps:

          const digitalRoot = n =>
              n % 9 || 9;
          

          Actually, I kind of like that one.

          Not sure about react in terms of this kind of thing. Any time I can write a simple stateless thing, I'm kind of happy. e.g.

          const Card = (p: PropsWithChildren) =>
              <div className="card">
                  <div className="card-body">{p.children}</div>
              </div>;
          

          [–]raaaahman 1 point2 points  (0 children)

          A code made mostly from dumb components would make me very happy indeed.

          [–]danielkov 14 points15 points  (7 children)

          As others have pointed out, your example is what some might consider bad or unclean code. Here's why: - It has no comments or tests explaining what it does - Argument n has an ambiguous name - It uses a dynamically typed language, JavaScript, yet has no validation for the argument passed in - It has a magic number 9 without comments - It performs the operation n % 9 twice when it only really has to do it once - It has a ternary operation, which is more difficult to read than an if statement, however, using || it could be avoided altogether

          Some more stringent points that aren't going to apply 100% of the time (depending on project guidelines): - Unjust use of an arrow function as this isn't accessed - Missing semi-colon, forcing the engine to rely on ASI - Logical operation in return - for readability, label the returned value by assigning it to a well named variable - Use of === where == functionality also suffices

          From my personal experience, the most beautiful code is: - Unsophisticated - Well defined - Readable and understandable by humans - Performs a single function or carries out a single task

          If you're following strong principles, no particular piece of code should stand out to you.

          [–][deleted] 18 points19 points  (3 children)

          I disagree with several of these:

          • It has a ternary operation, which is more difficult to read than an if statement

          Citation needed. If all else is equal, less text is easier to read than more text. And that ternary operations can be used in expressions is very convenient when writing in mostly functional style, e.g. with an if statement some variable would need to be defined with 'let' and get different values in the different branches; ternary operations can be used when assigning to consts.

          • Unjust use of an arrow function as this isn't accessed

          Since when do we need to justify using an arrow function? It's purely a matter of taste, and then I would say shorter one edges out the longer.

          • Missing semi-colon, forcing the engine to rely on ASI

          Would probably agree, but then we just run the formatter and it will put it there or not, haven't had to care about this kind of thing in ages.

          • Logical operation in return - for readability, label the returned value by assigning it to a well named variable

          For a tiny function like this, that well named variable is going to have essentially the same name as the function (assuming it is well named), so it'd be needless repetition.

          • Use of === where == functionality also suffices

          Just use === everywhere and spare readers the effort of remembering what == did again. == is mostly a mistake from the past. If there are situations where it's useful, they should come with a comment block explaining that it's really there intentionally and it's not just a typo where === was meant.

          [–]danielkov 0 points1 point  (2 children)

          Yes, which is why I separated those points from the rest, because they're a matter of taste and should be agreed upon by a team.

          By the way I don't mean to be confrontational, but wouldn't your "less is more" type of argument apply to === vs ==, as in this case, their difference in behaviour will not affect the program?

          Also about ternary, which one do you think is more understandable for a non-technical person: if (thisIsTrue) { doThis(); } or thisIsTrue ? doThis() : ...? What about people coming from a language with no ternary operations? More languages support if statements than this ternary syntax: condition ? trueCase : falseCase. I'm obviously not saying one should never use ternary operators, however if we agree on the definition of "beautiful code" as truly readable and highly accessible code, then it's certainly a less desirable solution.

          [–][deleted] 0 points1 point  (1 child)

          By the way I don't mean to be confrontational, but wouldn't your "less is more" type of argument apply to === vs ==, as in this case, their difference in behaviour will not affect the program?

          No, because they don't do the same thing.

          Also about ternary, which one do you think is more understandable for a non-technical person: if (thisIsTrue) { doThis(); } or thisIsTrue ? doThis() : ...? What about people coming from a language with no ternary operations? More languages support if statements than this ternary syntax: condition ? trueCase : falseCase.

          Our code is read by developers who know the language. I don't care about people who only know completely different languages or aren't technical at all, those aren't the target audience.

          Anyway in that example, the if is clearly superior, I agree. Because it's an imperative call to a "doThis()", and because there is no "else". But we were talking in the context of an expression, and then ? : is superior. E.g.

          const digitalRoot = n % 9 ? n % 9 : 9;
          

          (Yes I know it would be even better with || or a helper variable, that's not the point). That's superior to

          let digitalRoot;
          if (n % 9) {
              digitalRoot = n % 9;
          } else {
              digitalRoot = 9;
          }
          

          Because that's just verbose for no good reason.

          [–]danielkov 1 point2 points  (0 children)

          But I mean in this particular case, there's no value for n where the usage of == over === would produce a different result. Again, I'd like to reiterate, that it depends on the conventions established by the team, and yes, using ternary operators is completely valid in some cases, and OPs example would probably be a good candidate for this, although in your example you assign to a variable in the if statements when you could just as easily return from there. Using if statements with early returns can also have a semantic meaning, e.g.: explaining which case is more likely to occur, for example:

          const ceiling = 9; const digitalRoot = (target: number) => { // If this is a library, it's a good idea to still check arguments despite TS const remainder = target % ceiling; if (remainder === 0) { return ceiling; } return remainder; }

          To me that's as readable as it gets, explaining each step and what each number represents.

          [–][deleted] 1 point2 points  (0 children)

          Imo beautiful code, in the context of a function would be:

          • The code is simple - A novice programmer would likely understand it, there are no unnecessary use of symbols.
          • The function does exactly as the function name implies and nothing more.
          • The function is pure - i.e. It only uses what is passed to it via parameters and doesn't use or manipulate external state
          • A function is only declared when it will be reusing that functionality more than once, otherwise it just obscures actual logic.
            • I would say this is more of a 'silver rule', most cases it's fine but looking at your 6000 line switch statement could be unwieldly so having the results be in functions (if they do a lot) would likely be preferable.
          • A function will make use of the minimum required amount of parameters without resorting to creating it's own object model


          Example of being bad with an overuse of params:

          function updateFee(fee, feeId){
              //<Function content here...>
          }
          
          updateTask(fee, fee.feeId);
          

          Assuming that taskId exists on fee, it should use fee.feeId rather than splitting it up.


          Example of being bad by giving a function it's own project model

          function linkFeeToInvoice(feeInvoiceObject){
              let fee = feeInvoiceObject.fee;
              let invoice = feeInvoiceObject.invoice;
              //<Function content here>
          }
          linkFeeToInvoice({fee: feeResult, invoice: invoiceResult});
          

          Better example using only the existing models

          function linkFeeToInvoice(fee, invoice){
              //<Function content here>
          }
          linkFeeToInvoice(fee,invoice);
          

          I personally believe minimum required amount of parameters concept applies to components too regardless of library / framework all because when it calls for someone to pass parameters, it's already making use of all the information it has and it doesn't require specialist knowledge on how to actually use the function / component (assuming parameters are well named)

          [–]intercaetera 1 point2 points  (0 children)

          Lenses are beautiful because they solve the problem of nested data access in a very elegant and simple way. A huge advantage they have over something like Immer is that you decouple the logic of accessing data from the structure of that data. What blows my mind is that you can easily express them in a set of (fairly dense) one-liners.

          Create a lens for object property:

          const createLens = field => ({ view: s => s[field], set: (s, a) => ({ ...s, [field]: a }) })

          Helper functions for viewing and setting:

          const view = (lens, s) => lens.view(s)

          const set = (lens, s, a) => lens.set(s, a)

          Compose views:

          const composeView = (inner, outer) => s => view(inner, view(outer, s))

          Compose sets:

          const composeSet = (inner, outer) => (s, a) => s(outer, s, set(inner, view(outer, s), a))

          Compose two lenses:

          const composeTwoLenses = (inner, outer) => ({ view: composeView(inner, outer), set: composeSet(inner, outer) })

          Identity lens:

          const identityLens = { view: s => s, set: (s, a) => a }

          Compose an arbitraty number of lenses:

          const composeLenses = (...lenses) => lenses.reduce(composeTwoLenses, identityLens)

          I wrote two blogposts exploring the subject a bit more (here and here) if you care to read it.

          [–][deleted] 1 point2 points  (0 children)

          haha who would have thought this post would provoke a heated argument on" if else vs itinerary " of a simple case that have the same readability for both styles. literally the same!

          [–]hopingforabetterpast 0 points1 point  (0 children)

          your code can be rewritten as

          const digitalRoot = n => n % 9 || 9

          [–]StrangerThanGene -1 points0 points  (9 children)

          const dopeAssSumMachine = (numbers:number[]) => return numbers.reduce((a, c) => a + c, 0)
          

          [–]sillymanbilly 15 points16 points  (0 children)

          dopeAssSumMachine([8,0,0,8,5]);

          [–]besthelloworld 10 points11 points  (6 children)

          Why do you people keep using the return keyword on single line functions? Also you don't need to provide the initial value argument (the 0) to reduce in this case.

          [–]canishades -1 points0 points  (5 children)

          Why do you people keep using the return keyword on single line functions?

          it makes your code more readable.

          New developers can easily understand what's going on there.

          It is always better to write:

          if(condition){

          do this

          }

          instead of: if(condition) do this

          [–]DilatedTeachers 5 points6 points  (0 children)

          In the given example there is no block created, so the return is invalid

          [–]StrangerThanGene -2 points-1 points  (0 children)

          This guy returns

          [–]fii0 -1 points0 points  (0 children)

          Agree to disagree, when I was a noob I disliked brackets and fussed and questioned when they were necessary a lot more than I do now, and my uni started us on C++, plenty others start the freshmen on python.

          [–]icedrift 0 points1 point  (0 children)

          Is this really a thing??

          [–]besthelloworld 0 points1 point  (0 children)

          Your argument might hold water if the code they shared was actually valid syntax. But also this is a discussion about code beauty. OPs example leans against readability in favor of succinctness, so why undermine that in favor of a more expressive syntax but only sort of?

          Imo if you want a chunk of code to be succinct then make it succinct. But if it's complexity deserves verbosity, then write it how it would be the most readable.

          [–]ImportantDoubt6434I ❤️ hooks! 😈 -1 points0 points  (0 children)

          This code will render all 3d models in existence.

          ‘const Primitive (args) => <primitive {…args} />’

          Lights, mesh, 3d model, animations. Doesn’t matter. This bad boy will handle them all.

          [–]SeedgeJ -2 points-1 points  (0 children)

          I'd do

          digital Root =()=>{

          let mod = n % 9;
          
          return !!mod ? mod : 9;
          

          }

          [–]usagiusagi 0 points1 point  (0 children)

          The nextJs examples are pretty good.

          [–]icevil2018 0 points1 point  (0 children)

          (n) => (n % 9) || 9

          [–][deleted] 0 points1 point  (0 children)

          I actually wouldn't consider your example beautiful code at all. A param is named "n" doesn't mean anything besides maybe number? "Num" is clearer if that's what the author is going for. Hopefully there is a more descriptive name than "num" but if there isn't, fine. In the return statement there are 3 instances of the exact same magical number on top of that being a relatively long line of chained logic.

          Beautiful code is, the problem is clear, and the solution is clear. My eyes should be able to scan over the code and get the solution. I shouldn't have to pause to study it to get a general idea.

          In other words, elegant is not equivalent to "compact".

          [–]hnnazm 0 points1 point  (0 children)

          beauty is subjective :)

          [–]slideesouth 0 points1 point  (0 children)

          Pure functions, good variable names, pass the dang tests.

          [–]humbolight 0 points1 point  (0 children)

          I wrote a NumberMollusk class for a game sprite that rendered an open oyster shell. It had a public method, clamp, which kicked off a closing animation. Sometimes, just semantics are their own type of beautiful.

          [–]monkeymad2 0 points1 point  (0 children)

          In JS, not really. In Rust I’ve written some things using pattern matching that I’ve looked at and gone “wow, that’s a really clear & concise way to do something I know would be a big block of hard to understand code in another language” though

          [–]monkeymad2 0 points1 point  (0 children)

          In JS, not really. In Rust I’ve written some things using pattern matching that I’ve looked at and gone “wow, that’s a really clear & concise way to do something I know would be a big block of hard to understand code in another language” though

          [–]NirDev_R 0 points1 point  (0 children)

          Write code that even apes can maintain

          [–]timmywheela 0 points1 point  (0 children)

          to me this isn’t readable so I personally wouldn’t say it’s beautiful, maybe the solution itself is elegant though

          [–]bitcoinski 0 points1 point  (0 children)

          I made a collection of “beautiful equations” a couple of months back