• Simulation6@sopuli.xyz
    link
    fedilink
    arrow-up
    82
    arrow-down
    1
    ·
    10 hours ago

    Figuring out what the code is doing is not the hard part. Documenting the reason you want it to do that (domain knowledge) is the hard part.

    • steventhedev@lemmy.world
      link
      fedilink
      arrow-up
      13
      ·
      8 hours ago

      One upvote is not enough.

      I once wrote a commit message the length of a full blog post comparing 10 different alternatives for micro optimization, with benchmarks and more. The diff itself was ten lines. Shaved around 4% off the hot path (based on a sampling profiler that ran over the weekend).

    • tatterdemalion@programming.dev
      link
      fedilink
      arrow-up
      21
      ·
      10 hours ago

      Agreed.

      And sometimes code is not the right medium for communicating domain knowledge. For example, if you are writing code the does some geometric calculations, with lot of trigonometry, etc. Even with clear variable names, it can be hard to decipher without a generous comment or splitting it up into functions with verbose names. Sometimes you really just want a picture of what’s happening, in SVG format, embedded into the function documentation HTML.

    • lobut@lemmy.ca
      link
      fedilink
      arrow-up
      1
      ·
      8 hours ago

      I can’t recall the exact change but a coworker did something five years very intentionally. The comments, the commit and everything described what they did but not why.

      I think it was with side effects: true and I fixed a certain way we bundled things and I believe that could have solved the issue but I don’t know for sure :/

  • steventhedev@lemmy.world
    link
    fedilink
    arrow-up
    47
    ·
    11 hours ago

    Ew no.

    Abusing language features like this (boolean expression short circuit) just makes it harder for other people to come and maintain your code.

    The function does have opportunity for improvement by checking one thing at a time. This flattens the ifs and changes them into proper sentry clauses. It also opens the door to encapsulating their logic and refactoring this function into a proper validator that can return all the reasons a user is invalid.

    Good code is not “elegant” code. It’s code that is simple and unsurprising and can be easily understood by a hungover fresh graduate new hire.

    • YaBoyMax@programming.dev
      link
      fedilink
      English
      arrow-up
      6
      ·
      6 hours ago

      This is the most important thing I’ve learned since the start of my career. All those “clever” tricks literally just serve to make the author feel clever at the expense of clarity and long-term manintainability.

    • traches@sh.itjust.works
      link
      fedilink
      English
      arrow-up
      36
      ·
      10 hours ago

      Agreed. OP was doing well until they replaced the if statements with ‚function call || throw error’. That’s still an if statement, but obfuscated.

      • BrianTheeBiscuiteer@lemmy.world
        link
        fedilink
        arrow-up
        6
        ·
        8 hours ago

        Don’t mind the || but I do agree if you’re validating an input you’d best find all issues at once instead of “first rule wins”.

    • verstra@programming.dev
      link
      fedilink
      arrow-up
      11
      ·
      10 hours ago

      I agree, this is an anti-pattern for me.

      Having explicit throw keywords is much more readable compared to hiding flow-control into helper functions.

    • Womble@lemmy.world
      link
      fedilink
      English
      arrow-up
      5
      arrow-down
      4
      ·
      edit-2
      9 hours ago

      Good code is not “elegant” code. It’s code that is simple and unsurprising and can be easily understood by a hungover fresh graduate new hire.

      I wouldnt go that far, both elegance are simplicity are important. Sure using obvious and well known language feaures is a plus, but give me three lines that solve the problem as a graph search over 200 lines of object oriented boilerplate any day. Like most things it’s a trade-off, going too far in either direction is bad.

  • koper@feddit.nl
    link
    fedilink
    arrow-up
    25
    ·
    edit-2
    10 hours ago

    Why the password.trim()? Silently removing parts of the password can lead to dangerous bugs and tells me the developer didn’t peoperly consider how to sanitize input.

    I remember once my password for a particular organization had a space at the end. I could log in to all LDAP-connected applications, except for one that would insist my password was wrong. A trim() or similar was likely the culprit.

    • HamsterRage@lemmy.ca
      link
      fedilink
      arrow-up
      8
      ·
      7 hours ago

      The reason for leaving in the password.trim() would be one of the few things that I would ever document with a comment.

    • spechter
      link
      fedilink
      arrow-up
      21
      ·
      10 hours ago

      Another favorite of mine is truncating the password to a certain length w/o informing the user.

      • Flipper@feddit.org
        link
        fedilink
        arrow-up
        5
        ·
        8 hours ago

        The password needs to be 8 letters long and may only contain the alphabet. Also we don’t tell you this requirement or tell you that setting the password went wrong. We just lock you out.

    • Aijan@programming.devOP
      link
      fedilink
      arrow-up
      12
      ·
      edit-2
      10 hours ago

      Thanks for the tip. password.trim() can indeed be problematic. I just removed that line.

  • Rogue@feddit.uk
    link
    fedilink
    arrow-up
    2
    arrow-down
    1
    ·
    5 hours ago

    A quick glance and this seemed nothing to do with self documenting code and everything to do with the flaws when code isn’t strictly typed.

  • graycube@lemmy.world
    link
    fedilink
    arrow-up
    5
    ·
    9 hours ago

    I would have liked some comments explaining the rules we are trying to enforce or a link to the product requirements for it. Changing the rules requirements is the most likely reason this code will ever be looked at again. The easier you can make it for someone to change them the better. Another reason to need to touch the code is if the user model changes. I suppose we might also want a different password hash or to store the password separately even a different outcome if the validation fails. Or maybe have different ruled for different user types. When building a function like this I think less about “ideals” and more about why someone might need to change what I just did and how can I make it easier for them.

    • nous@programming.dev
      link
      fedilink
      English
      arrow-up
      3
      ·
      2 hours ago

      and how can I make it easier for them.

      I am wary of this. It is very hard to predict what someone else in the future might want to do. I would only go so far as to ensure nothing I am doing will unnecessarily block a refactor later on but I would avoid trying to add or abstract things in ways that make the current code harder to read because you think it might be easier for someone to add to in the future.

      I have needed, far too many times, to strip out some unused abstraction to do something that abstraction was never intended to allow because someone was trying to save me time and predict what might happen to the code in the future and got it completely wrong. It is far easier to add an abstraction to simple code later on when it actually helps then to try and figure out what the abstraction is and remove it when it is found to be wrong.

  • dohpaz42@lemmy.world
    link
    fedilink
    English
    arrow-up
    8
    arrow-down
    5
    ·
    8 hours ago
    async function createUser(user) {
        validateUserInput(user) || throwError(err.userValidationFailed);
        isPasswordValid(user.password) || throwError(err.invalidPassword);
        !(await userService.getUserByEmail(user.email)) || throwError(err.userExists);
    
        user.password = await hashPassword(user.password);
        return userService.create(user);
    }
    

    Or

    async function createUser(user) {
        return await (new UserService(user))
            .validate()
            .create();
    }
    
    // elsewhere…
    const UserService = class {
        #user;
    
        constructor(user) {
            this.user = user;
        }
    
        async validate() {
            InputValidator.valid(this.user);
    
           PasswordValidator.valid(this.user.password);
    
            !(await UserUniqueValidator.valid(this.user.email);
    
            return this;
        }
    
        async create() {
            this.user.password = await hashPassword(this.user.password);
    
            return userService.create(this.user);
        }
    }
    

    I would argue that the validate routines be their own classes; ie UserInputValidator, UserPasswordValidator, etc. They should conform to a common interface with a valid() method that throws when invalid. (I’m on mobile and typed enough already).

    “Self-documenting” does not mean “write less code”. In fact, it means the opposite; it means be more verbose. The trick is to find that happy balance where you write just enough code to make it clear what’s going on (that does not mean you write long identifier names (e.g., getUserByEmail(email) vs. getUser(email) or better fetchUser(email)).

    Be consistent:

    1. get* and set* should be reserved for working on an instance of an object
    2. is* or has* for Boolean returns
    3. Methods/functions are verbs because they are actionable; e.g., fetchUser(), validate(), create()
    4. Do not repeat identifiers: e.g., UserService.createUser()
    5. Properties/variables are not verbs; they are state: e.g., valid vs isValid
    6. Especially for JavaScript, everything is const unless you absolutely have to reassign its direct value; I.e., objects and arrays should be const unless you use the assignment operator after initialization
    7. All class methods should be private until it’s needed to be public. It’s easier to make an API public, but near impossible to make it private without compromising backward compatibility.
    8. Don’t be afraid to use if {} statements. Short-circuiting is cutesy and all, but it makes code more complex to read.
    9. Delineate unrelated code with new lines. What I mean is that jamming all your code together into one block makes it difficult to follow (like run-on sentences or massive walls of text). Use new lines and/or {} to create small groups of related code. You’re not penalized for the white space because it gets compiled away anyway.

    There is so much more, but this should be a good primer.

    • RecluseRamble@lemmy.dbzer0.com
      link
      fedilink
      arrow-up
      6
      ·
      edit-2
      7 hours ago

      I would argue that the validate routines be their own classes; ie UserInputValidator, UserPasswordValidator, etc.

      I wouldn’t. Not from this example anyway. YAGNI is an important paradigm and introducing plenty of classes upfront to implement trivial checks is overengineering typical for Java and the reason I don’t like it.

      Edit: Your naming convention isn’t the best either. I’d expect UserInputValidator to validate user input, maybe sanitize it for a database query, but not necessarily an existence check as in the example.

      • dohpaz42@lemmy.world
        link
        fedilink
        English
        arrow-up
        4
        arrow-down
        1
        ·
        6 hours ago

        I wouldn’t. Not from this example anyway. YAGNI is an important paradigm and introducing plenty of classes upfront to implement trivial checks is overengineering…

        Classes, functions, methods… pick your poison. The point is to encapsulate your logic in a way that is easy to understand. Lumping all of the validation logic into one monolithic block of code (be it a single class, function, or methods) is not self-documenting. Whereas separating the concerns makes it easier to read and keep your focus without mixing purposes. I’m very-engineering (imo) would be something akin to creating micro services to send data in and get a response back.

        Edit: Your naming convention isn’t the best either. I’d expect UserInputValidator to validate user input, maybe sanitize it for a database query, but not necessarily an existence check as in the example.

        If you go back to my example, you’ll notice there is a UserUniqueValidator, which is meant to check for existence of a user.

        And if you expect a validator to do sanitation, then your expectations are wrong. A validator validates, and a sanitizer sanitizes. Not both.

        For the uninitiated, this is called Separation of Concerns. The idea is to do one thing and do it well, and then compose these things together to make your program — like an orchestra.

        • nous@programming.dev
          link
          fedilink
          English
          arrow-up
          3
          ·
          2 hours ago

          This is abuse of the separation of concerns concepts IMO. You have taken things far too far many made it far less readable overall. The main concern here is password validation - and the code already separated this out from other code. By separating out each check you are just violating another principal - locality of behavior which says related things should be located close to each other. This makes things far easier to read and see what is actually going on without needing to jump through several classes/functions of abstraction.

          We need to stop trying to break everything down into the smallest possibly chunks we can. It is fine for a few lines of related code to live in the same function.

        • RecluseRamble@lemmy.dbzer0.com
          link
          fedilink
          arrow-up
          1
          ·
          edit-2
          3 hours ago

          If you go back to my example, you’ll notice there is a UserUniqueValidator, which is meant to check for existence of a user.

          Oops, right, I just glanced over the code and obviously missed the text and code had different class names. Another smell in my opinion, choosing class names that only differ in the middle. Easily missed and confusion caused.

          I don’t think our opinions are too far off though. You’re just scaling the validation logic to realistic levels and I warn that in practice coders extrapolate too quickly and too often, which results in too much generic code which is naturally harder to understand and maintain than specific code.

      • Zagorath@aussie.zone
        link
        fedilink
        arrow-up
        5
        ·
        8 hours ago

        If the doco we’re talking about is specifically an API reference, then the documentation should be written first. Generate code stubs (can be as little as an interface, or include some basic actual code such as validating required properties are included, if you can get that code working purely with a generated template). Then write your actual functional implementation implementing those stubs.

        That way you can regenerate when you change the doco without overriding your implementation, but you are still forced to think about the user (as in the programmer implementing your API) experience first and foremost, rather than the often more haphazard result you can get if you write code first.

        For example, if writing a web API, write documentation in something like OpenAPI and generate stubs using Swagger.

          • Zagorath@aussie.zone
            link
            fedilink
            English
            arrow-up
            3
            ·
            8 hours ago

            Yup absolutely. I mentioned web APIs because that’s what I’ve got the most experience with, but .h files, class library public interfaces, and any other time users who are not the implementor of the functionality might want to call it, the code they’ll be interacting with should be tailored to be good to interact with.