Live data from Hacker News

Want cleaner code? Use the rule of six

davidamos.dev

81–90 of 352 posts

Re: Want cleaner code? Use the rule of six

#81
post #26

I have written a lot of Powershell in the last few years. I eschew the clever powershell ways of doing things if someone else may end up owning it (think: where-object, foreach-object) in favor of expressions that resemble other languages (foreach, for). If I'm writing it for myself, and only ever myself, I'll use the more clever powershell ways of doing things. Expressions like: 1..10 | % {$_} If you're coming from…

I primarily write in PowerShell for end-user shell tools and Go for network services.

Where-Object is going to let you cut down on the number of lines of code compared to foreach() and for(), and in my opinion will make the code more readable.

$vms | Where-Object -Property Name -match "sql"

vs

$vmOutput = @()

for($i = 0; $i -lt $vms.count; $i++) {

    if($i.Name -match "sql"){

        $vmOutput += $i

    }
}

vs

$vmOutput = @()

foreach($vm in $vms){

    if($vm.Name -match "sql"){

        $vmOutput += $vm

    }
}

For the Foreach-Object point, that cmdlet also give you the option to use begin{}, process{} and end{} blocks. So that you can with begin{} do something before any of your objects are processed, process your objects with process{}, and after all objects have been process do something with end{}. This logic with for and foreach would have to come before and after the for and foreach statements.

I don't see this as a "PowerShell being clever" but more as a PowerShell is a shell that uses pipelines like nix shells but it has everything as an object unlike nix shells. So you get to take advantage of that.

Re: Want cleaner code? Use the rule of six

#82
post #36

I see a troubling trend with some coworkers where they seem to stretch the limits of time and space to make every line as dense as possible, usually using lodash. I think it is a point of pride for them, but I think it's obvious that everyone's life would be easier if they just wrote their code out "long form" and, god willing, added some comments for various steps. Instead, I find myself having to re-write ultra-den…

Once I read something along the lines of “every programmer goes through that phase were we wants to show how clever he is, by writing whole programs in one line. Until he understands how stupid that is”. I do not have the source, regrettably.

I was taking my first multi-threaded resource allocation course when I first ran into the famous Kernighan quote.

> “Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.”

It clicked and instantly disabused me of the notion that smart people write code that's any smarter than the minimum required to solve the problem at hand.

Re: Want cleaner code? Use the rule of six

#83
post #20

Earlier quoted context omitted.

I'm working on a project that is following Uncle Bob's Clean Code guidelines of striving to having functions be ideally 3 lines or less, and nor more than say 7. I have mixed feelings about it. My initial prejudices have largely held. I do find the code harder to read and follow. Having to jump around, follow variables that change name as they are passed through functions, keeping track of state that was moved to a c…

>guidelines of striving to having functions be ideally 3 lines or less, and nor more than say 7. I have mixed feelings about it. Dont feel bad about it Those small functions with hard limits are just terrible advice When you gotta know functions impl., which for me is very often Then this approach just increases cognitive load

Those guidelines should (my personal position) be taken as advisory, and never as hard rules. Functions should be “small enough, that a less than gifted can understand it”. Is difficult to measure in lines. Best example is a big switch with 10 cases. Artificially breaking that in smaller pieces is not helpful. I have a soft rule of 3 to 7 different control structures (if, for, case, etc) in total, and 2 or 3 nested.

Re: Want cleaner code? Use the rule of six

#84
Early in my career, I took to heart such books and articles and often felt guilty and lessor-programmer when I cut corners. Here's my 2 cents now:

- Some of this is the coding equivalent of "6 rules for financial freedom" or "6 ways to find your dream soulmate". Generic advice that doesn't reflect highly nuanced reality.

- These rules are guidelines at best. There are justifiable reasons to break them; which I do often. Albeit this requires experience (and dare I say, wisdom). For example, refactoring code into a separate function levies a cost (of indirection) on the reader. Therefore copy-paste is sometimes fine.

- Clode "cleanliness" is a moving target. For a coder's mental health and value proposition for his project, he/she should know what code can afford to stay dirty.

PS: I love Jonathan Blow's opinions on coding/programming. Here are a few: https://www.youtube.com/watch?v=21JlBOxgGwY https://www.youtube.com/watch?v=ubWB_ResHwM https://www.youtube.com/watch?v=KcP1fXQv0iU

Re: Want cleaner code? Use the rule of six

#85

Earlier quoted context omitted.

I think there's a real smell with those long, dense lines of code. Tends to mean your data structures are out of control: objects with arrays that point to other objects that then also have arrays on them. My oh my. Comments being required are also another smell that the code doesn't explain itself. I know this is said so often it's a cliche, but it really is true. I think both of these things point back to the same…

Sure, if the computer can figure out what a given fragment of code is supposed to do, so can you (a sufficiently clever programmer). The question rather is, do you spend 20s reading a comment or 15m to solve the riddle? There's a real danger that comments aren't updated when code is, particularly if 3rd parties make those changes. This is one of the corners where there will never be a single answer which is right in…

> There's a real danger that comments aren't updated when code is, particularly if 3rd parties make those changes.

So much this. If it took you everything you learned over the last week + an epiphany to come up with a bit of code, how is someone scanning through supposed to understand it?

Or, in example with hilariously apropos incomplete post-hoc comments, 0x5F3759DF https://en.m.wikipedia.org/wiki/Fast_inverse_square_root#Ove...

Re: Want cleaner code? Use the rule of six

#86
post #42

In this case `query_params` works well, but it's sometimes hard to find descriptive and reasonably concise names for the intermediate value. In those cases, the ideal would be using only postfix chaining, so that you can read it by only keeping the intermediate value and the next operation in mind: s.split('?')[1] .split('&')[-3:] .map(lambda x: x.split('=')[1]) Unfortunately, that's not how Pythons map(), len() and…

Idiomatic Python wouldn't use a map here, but a generator expression:

    (x.split('=')[1] for x in s.split('?')[1].split('&')[-3:])
Removing the lambda cuts down on the noise considerably.

And honestly, with this many splits with fixed indexes, I'd probably use a regex. Now there's a dense language for you.

Re: Want cleaner code? Use the rule of six

#87

Earlier quoted context omitted.

I think there's a real smell with those long, dense lines of code. Tends to mean your data structures are out of control: objects with arrays that point to other objects that then also have arrays on them. My oh my. Comments being required are also another smell that the code doesn't explain itself. I know this is said so often it's a cliche, but it really is true. I think both of these things point back to the same…

Sure, if the computer can figure out what a given fragment of code is supposed to do, so can you (a sufficiently clever programmer). The question rather is, do you spend 20s reading a comment or 15m to solve the riddle? There's a real danger that comments aren't updated when code is, particularly if 3rd parties make those changes. This is one of the corners where there will never be a single answer which is right in…

Often, breaking out a well named variable or three is the better way to make code readable.

Re: Want cleaner code? Use the rule of six

#88

This seems perfectly reasonable advice. However I do wonder how many people actually struggle with this sort of code quality. It's certainly more than a few, since I've encountered bad code with these issues. But it's not exactly the most pressing issue either. As the author demonstrated, you can refactor this with a little thought. It's the code equivalent of tidying your room, sweeping the floors and putting your s…

I’ve seen some engineers that think it’s clever to put everything into a one-line list comprehension where possible, even if that means rewriting named variables as letters to make them fit. The result is really hard to read.

I’ve also (more common) encountered engineers that don’t actively try to be clever by being terse, but also don’t put their mind to writing clearly.

Put differently, I think one has to actively try to write easy-to-read code.

I agree with your point that this sort of micro-style point isn’t as big as architectural questions, but it’s definitely something you want to teach junior engineers so that it’s second nature by the time they are at the level where they are thinking about architecture.

For that you can try reading Bob Martin, Martin Fowler, Kent Beck, Domain Driven Design, Hexagonal, etc. - but you also just need to build for a decade while thinking about that stuff to really master it. Sadly architecture often seems more craft than formal engineering at this level.

Re: Want cleaner code? Use the rule of six

#89
post #15

We break everything down and then we reach one of the most difficult problems in software engineering: Coming up with good and short names for all these extra intermediate variables and functions.

Typically, relatively unspecific names like "i" or "size" are good enough. It's better than not naming at all and producing a complicated expression tree instead. More specific names cost energy, both inventing and reading them (because they are typically longer). Err on the side of short and not too specific.

in most situations, I would rather see a complicated statement split over several lines than several simple statements with vague/unhelpful variable names. if the variable name itself doesn't help me understand what it means, I have to remember the full expression anyway.

Re: Want cleaner code? Use the rule of six

#90
post #68

I don't necessarily agree with the step of putting the code in a separate function; that often works, but just as often makes it so that the code can't be read top-to-bottom anymore which hurts readability. In this case there's, I think, a better alternative; the equivalent-ish code in Ruby for the example code here would be something like this: values = s .partition('?')[-1] .split('&') .map { |key_value| key_value.…

Any way to do that in Python? Basically an anonymous function across multiple lines, which can be collapsed in the IDE view?

Python's lambdas can have as many lines as you want. Just wrap parens around it. Hissp uses this form as a compilation target. Its REPL shows the Python compilation. Play around with it til you get it: https://github.com/gilch/hissp
Post reply on HN