News for hackers. Stuff that matters.
Re:Want cleaner code? Use the rule of six by kouteiheika on Saturday September 24, 2022 @12:36PM (#32964241)
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.partition('=')[-1] }
You can write these nice functional pipelines where you just read the code top-to-bottom and see step-by-step what is being done to the data on each line. You don't have to jump up-and-down around the code when reading it, and you don't have to keep too much context in your head when reading it.

This is one of the reasons why I vastly prefer Ruby over Python for most data processing tasks. I wish more languages would support this style of programming.

Re:Want cleaner code? Use the rule of six by davnicwil on Saturday September 24, 2022 @01:06PM (#32964540)
> the code can't be read top-to-bottom

The idea of the technique is to split out code at a different level of abstraction with a clear name communicating what it does, while hiding the details of the how, because you don't need to care about that detail at all to fully grok the code in the calling function.

Where this breaks down is when the code you're trying to split out is not at a different level of abstraction, and how it works is meaningful to the surrounding code in the calling function.

So I think the issue you are seeing isn't with the technique, it's with the technique being misapplied. I think this is likely the only difference between when it 'often works' and 'just as often doesn't' in the code you're working in :-)

Re:Want cleaner code? Use the rule of six by lamontcg on Saturday September 24, 2022 @05:13PM (#32966574)
Each function becomes something new that needs to stick in your brain.

Someone that applies "MORF" to their code winds up nearly inventing their own language in the file that they're writing. All that takes up more memory when you're reading their code, because due to leaky abstractions the actual implementation of whatever the function name that you replace it with is often important.

I have an actual track record of taking code that someone had MORF'd to hell and rewriting it, and making it about 40% shorter, with much fewer concepts to process.

Inventing a term like "MORF" is probably illustrative of the problem itself. Without looking at the blog post what exactly was that acronym again? That is just one more thing for you to try to memorize. The author is riffing on things like "DRY" and "YAGNI" that are well-known, but it isn't really helping with readability when you lift it out of that context.

Re:Want cleaner code? Use the rule of six by AnimalMuppet on Saturday September 24, 2022 @11:13PM (#32968617)
> Each function becomes something new that needs to stick in your brain.

But if you don't put it in a separate function, then all that code becomes something that you have no choice but look at as part of this function, because the text of it is right there in the function.

Sticking part of the code in a sub-function gives you the choice: Do I trust that this function does what it says, with no other effects that I have to worry about? Or do I go look at it to make sure?

But not sticking the code in a sub-function gives you no choice - it's right there as part of the function you're looking at, and you have to see what that code is doing as part of understanding the function. And having that code not in a separate function makes it more likely that it has side effects that can mess up the rest of the function (separate functions is a firewall against side effects).

Re:Want cleaner code? Use the rule of six by nicoburns on Sunday September 25, 2022 @08:01AM (#32970558)
I like putting comments above paragraphs of code so that you can skim it by trusting the comments, but you can also inspect any individual paragraphs implementation without losing your context.
Re:Want cleaner code? Use the rule of six by thebackup on Monday September 26, 2022 @12:38AM (#32979489)
Agreed. A comment can also explain things that a function name cannot. I’m all for splitting code into paragraphs with a well written comment above each. Of course I also extract functions, but only when there are obvious benefit, like removing repetition.
Re:Want cleaner code? Use the rule of six by usrusr on Saturday September 24, 2022 @06:49PM (#32967275)
I agree, one of my favorite ide functions is the inline button. Because all too often that supposedly clear name turns out to be not clear at all.

Perhaps it would not be quite as bad if there was a clear distinction between "this is a function for reuse" and "this is a function that's naturally just elaborate code folding", but that does not really exist. Just stick to single-assignment variables and keep their scopes short and enjoy the good parts of sequential code.

Re:Want cleaner code? Use the rule of six by majormajor on Saturday September 24, 2022 @08:19PM (#32967817)
> All that takes up more memory when you're reading their code, because due to leaky abstractions the actual implementation of whatever the function name that you replace it with is often important.

"Better names" is a good answer for a sloppy pattern that looks like this:

fun saveRecord(record){

wireRecord = record.toWireRecord();

innerSaveRecord(wireRecord)

}

fun innerSaveRecord(wireRecord){

log("saving record " + wireRecord)

saveWireRecord(wireRecord)

}

That's a stupid level of nesting instead of a reasonably-named "convertAndLogAndSaveRecord()" - then you get into debates about if logging should be in that name, otherwise it's happening despite the name not saying it, etc.

So all that to say that moving into functions alone can be good, or can be bad.

The easiest-to-define benefit of the verbosely-named "convertAndLogAndSaveRecord()" is that it becomes easily testable vs having those lines inlined somewhere. (I'm often much more ambivalent on "reuse" benefits - if your function is specific it can't be made reusable without making it less well defined.)

But as far as I know, the world doesn't offer me a way to test that the function not only does what it says but doesn't do what it doesn't say. And it's similarly hard to talk other programmers out of shoehorning new logic into existing functions - now making them harder to reason about - rather than new functions that are composed differently or with the existing ones.

Because if "checkAccountingProcessResultsAgainstAudit" is going to give you readability benefits, it damn well better do what it says every time you call it instead of becoming a maze of conditionals and optional behavior.

Re:Want cleaner code? Use the rule of six by drewm1980 on Monday September 26, 2022 @03:05AM (#32980292)
Besides giving a block of code a name, functions also reduce the scope of the data the code can possibly be acting on. They also introduce a namespace that lets symbol names focus on locally relevant information. How did this huge refactoring patch you are describing hold up in code review?
Re:Want cleaner code? Use the rule of six by lifeisstillgood on Sunday September 25, 2022 @03:06AM (#32969518)
Err - OK - my google fu is failing me. What is MORF (I assume it's some kind of acronym for refactoring ...)
Re:Want cleaner code? Use the rule of six by Izkata on Sunday September 25, 2022 @03:27AM (#32969606)
It's defined in the article, the author seems to have invented it.
Re:Want cleaner code? Use the rule of six by wpietri on Saturday September 24, 2022 @02:06PM (#32965140)
This is my experience too. I love hiding detail for readability, but you have to hide the right details!

It's also definitely related to testability for me. If I'm pulling out the right details, then I'll often get a nice cluster of tests that pin down the higher-level concept in a way where it's both the production and test code that gets more readable.

Re:Want cleaner code? Use the rule of six by kristopolous on Sunday September 25, 2022 @01:11AM (#32969108)
The problem is those who create the messes to need that advice probably will take that advice and create even bigger messes

In practice, pithy adages don't get us any closer to sanity

Really the only news you can use is

1. Try to modify things with code you didn't write by not simply throwing parts away

2. If you think it's really difficult to deal with, figure out if other people agree with you.

3. understand why everybody thinks this

4. If you are doing that in your own code, then stop doing that.

You have to viscerally understand why a practice is bad and how doing it affects other people.

This is how you can intuitively avoid such practices in the future. Not through things that rhyme or acronyms that spell words but through social intelligence. It's fundamentally behavior

Re:Want cleaner code? Use the rule of six by danmaz74 on Sunday September 25, 2022 @02:17AM (#32969339)
I understand the idea, but it requires:

* great ability at naming methods - which isn't very common * massive discipline at RE-naming methods when they get changed even slightly to do something more

Regarding the latter, I've seen so many times methods which originally described what they were doing, but now they don't any more, that I never just trust the name to tell me what a method really does.

Re:Want cleaner code? Use the rule of six by catlifeonmars on Sunday September 25, 2022 @03:03AM (#32969505)
Naming is probably the single hardest part of writing scalable, legacy code. Cache invalidation is a cakewalk in comparison. I believe this is in part because naming is a miniature exercise in empathy for future readers particular of a piece of code.
Re:Want cleaner code? Use the rule of six by shellback3 on Saturday September 24, 2022 @01:34PM (#32964833)
I agree, my thoughts were along this line especially when I noticed the 'magic' number -3.
Re:Want cleaner code? Use the rule of six by khendron on Saturday September 24, 2022 @01:04PM (#32964515)
One of the advantages of functions is that a well-named function is self-documenting. If you can take a bunch of lines and wrap them in a function whose name summarizes exactly what it does, then you have improved readability in my opinion. In this example, I don't really need to know the details of how the query parameters are extracted. I just want to know I've got them.
Re:Want cleaner code? Use the rule of six by marginalia_nu on Saturday September 24, 2022 @03:17PM (#32965718)
Emphasis on well-named. Naming things is hard.

Maybe not relevant in simple toy examples, but you don't have to look far until to find a function that isn't so easy to name.

Re:Want cleaner code? Use the rule of six by lamontcg on Saturday September 24, 2022 @05:17PM (#32966597)
Emphasis also on "bunch of lines".

Usually when I see one-line functions they cost more in short term memory than they save. There's good exceptions to this with something like a horrible conditional that is necessarily horrible so you can bust it out into a method with a doc comment about the horribleness, its history, and its subtle madness. But developers that just break out one-line methods all over the place wind up writing hard to understand code.

Re:Want cleaner code? Use the rule of six by Shaanie on Sunday September 25, 2022 @04:49AM (#32969874)
One-line functions are also nice when a comment would've been warranted otherwise. But yes, easy to go overboard with it.
Re:Want cleaner code? Use the rule of six by nmz on Saturday September 24, 2022 @03:43PM (#32965950)
its also a level of indirection... It's sad but functions often slow performance down. but this depends on the language.
Re:Want cleaner code? Use the rule of six by marginalia_nu on Saturday September 24, 2022 @03:51PM (#32966025)
Can't be many languages where that matters in 2022. Auto-inlining of short functions was a thing in the 1990s.
Re:Want cleaner code? Use the rule of six by extasia on Sunday September 25, 2022 @10:08AM (#32971481)
This may be true for compiled langs. In interpreted langs this is not the case. Function calls in Python for example are notoriously expensive.
Re:Want cleaner code? Use the rule of six by nmz on Sunday September 25, 2022 @11:05AM (#32972019)
Beat me to it. Yes, I ran a quick benchmark[0] and not running a function always wins. now, one may argue that you are running a call, but if the interpreter was smart it would convert the small function calls to just a noops.

[0]: https://github.com/Nomarian/crapbenchmarks/tree/main/call

  Summary
  'Perl/nofunc' ran
    1.63 ± 0.30 times faster than 'Perl/func'
    1.73 ± 0.34 times faster than 'Lua/nofunc'
    2.11 ± 0.55 times faster than 'Lua/func'
    9.37 ± 1.62 times faster than 'Python/nofunc'
   12.18 ± 1.90 times faster than 'TCL/nofunc'
   16.02 ± 2.58 times faster than 'TCL/func'
   18.64 ± 3.02 times faster than 'Python/func'
Re:Want cleaner code? Use the rule of six by dTal on Sunday September 25, 2022 @06:59PM (#32977287)
If you're hand-wringing about the performance impact of function calls, Python is probably the wrong choice anyway.
Re:Want cleaner code? Use the rule of six by dqpb on Saturday September 24, 2022 @05:18PM (#32966602)
> Naming things is hard

Naming is hard unless you have a sensible concept hierarchy, and then naming is easy.

Concept hierarchies are hard, unless you have a sensible system model, and then concept hierarchies are easy.

System models are hard, unless you have domain expertise, and then system models are easy.

Re:Want cleaner code? Use the rule of six by marginalia_nu on Saturday September 24, 2022 @05:32PM (#32966705)
Not everything is a neat concept though.

Look at the Porter stemming algorithm for example. It simply does not decompose into something that is easy to put names on.

Re:Want cleaner code? Use the rule of six by dqpb on Saturday September 24, 2022 @06:03PM (#32966926)
> A consonant will be denoted by c, a vowel by v. A list ccc... of length greater than 0 will be denoted by C, and a list vvv... of length greater than 0 will be denoted by V. Any word, or part of a word, therefore has one of the four forms: CVCV ... C CVCV ... V VCVC ... C VCVC ... V

Looks fine to me.

Re:Want cleaner code? Use the rule of six by djbusby on Saturday September 24, 2022 @05:22PM (#32966631)
Domain expertise is hard.
Re:Want cleaner code? Use the rule of six by rocqua on Sunday September 25, 2022 @02:30AM (#32969389)
Those functions get more annoying when debugging though. Because now you have to jump to the body of the function to see if it really does what it says. And you view the body out of context so it is harder to see if there is a wrong assumption between the callee and caller.

On the whole I think such functions are valuable. But they do have downsides.

Re:Want cleaner code? Use the rule of six by watwut on Sunday September 25, 2022 @02:59AM (#32969493)
Genuinely, they ate not annoying to me at all when debugging. I check whether function returned what I expected from its inputs and either look for bug there or move on.

I don't recall much jumping put and in.

Re:Want cleaner code? Use the rule of six by patrick451 on Saturday September 24, 2022 @04:14PM (#32966184)
Yeah, but these little 5 line functions with one caller whose only purpose is to avoid a 50 line function somewhere else are almost never named well. At best, I can infer about 20% of what is going on without stepping into all those little helpers.
Re:Want cleaner code? Use the rule of six by layer8 on Saturday September 24, 2022 @12:56PM (#32964445)
One issue with functional pipelines is that the reader has to keep track of what the types and the data are on each line. It’s fine for 2-3 lines, but it can get non-obvious quite quickly. Assigning intermediate points to named variables can be appropriate, or indeed factoring portions of the pipeline out into separate functions.
Re:Want cleaner code? Use the rule of six by mdaniel on Saturday September 24, 2022 @01:42PM (#32964913)
That may be true for less capable editors, but IntelliJ (and therefore Rubymine for the cited code block) annotates the stream type variable when it can prove what it is: https://www.jetbrains.com/help/ruby/viewing-reference-inform... regrettably doesn't show an example of what I'm talking about

    .map { | *String* key_value | key_value.partition... }
where String shows up in light grey text indicating that IJ knows `key_value` is a String
Re:Want cleaner code? Use the rule of six by layer8 on Saturday September 24, 2022 @01:50PM (#32965002)
That’s nice, but it just highlights that the coding style isn’t sufficiently intelligible by itself. We can’t and shouldn’t rely on a static analyzer to be active to make code intelligible everywhere code is displayed (pull requests, diffs, ...).

Doing so favors writing code over reading code, which is generally the wrong bias. Editor support is appropriate and useful to help writing readable code, but it’s bad for editor support to become a prerequisite for existing code to be comprehensible.

Re:Want cleaner code? Use the rule of six by twblalock on Saturday September 24, 2022 @05:17PM (#32966600)
> That’s nice, but it just highlights that the coding style isn’t sufficiently intelligible by itself. We can’t and shouldn’t rely on a static analyzer to be active to make code intelligible everywhere code is displayed (pull requests, diffs, ...).

Yes, we absolutely should rely on that.

Why would programmers, who are basically tool-builders, reject tools that help us write and analyze our programs? This is not the 1970s, and bare-bones text editors are not the only option. Why should we, who build tools for others, restrict ourselves to a self-imposed unreasonable simplicity?

You are free to use Vi or whatever, but don't complain when everyone else uses better tools to improve their productivity, and if the code they write is better suited for those tools that is perfectly fine.

Re:Want cleaner code? Use the rule of six by layer8 on Saturday September 24, 2022 @05:33PM (#32966716)
I’m all for IDEs for writing software, but not as a prerequisite for reading source code, because the latter happens in all kinds of different contexts. E.g. a software like GitLab shouldn’t require an integrated static analyzer for any or all programming languages. That would only increase the barrier to entry for all software that happens to display source code. If source code can’t be read and understood as-is anymore, that just impedes interoperability and universality of tooling.
Re:Want cleaner code? Use the rule of six by twblalock on Saturday September 24, 2022 @05:56PM (#32966887)
Surely you must understand that the functionality provided by the tools will impact how the code is written, tested, reviewed, and deployed.

There is no ideal world where we can use tools to write code and it would be perfectly readable for people who don't use those tools.

Embrace the modern ecosystem, or build something better, or take a time machine back to the 1970s where there were no IDEs, source control, or CI/CD. Do you really think that would be better?

Re:Want cleaner code? Use the rule of six by layer8 on Saturday September 24, 2022 @06:15PM (#32967022)
I disagree, because it reduces the freedom of choice and variety of tools available for software development, and increases the dependency on bespoke tooling. Using a more sophisticated word processor shouldn’t reduce the readability of the text produced. If anything, IDE features should be helping to increase the readability of the resulting source code, instead of promoting a coding style that decreases it.

This is about decoupling. The same way one should be able to freely pick a VCS and CI/CD system of choice, one should also be free to pick the IDE, or any other system concerned with source code, of choice. Those should remain loosely coupled, and should each be easy to replace. The more requirements you impose on how source code has to be marked up for intelligible display, the more you restrict the choice of tools it can usefully work with, and the more laborious it becomes to create new adequate tools in that field.

Re:Want cleaner code? Use the rule of six by rocqua on Sunday September 25, 2022 @02:37AM (#32969409)
We should reject tools that only help us understand code that we are writing.

Put differently, we should avoid relying on functionality that isn't present in most places where we need to understand code.

Hence, static analysis should be present in many more places than just the IDE. Merge requests, commit diffs, and perhaps code blocks in discussions are prime targets.

I think this might be one case where the CLI is truly limiting us. No opportunity for contexts menus or pop-ups makes presenting the results of static analysis much harder.

Re:Want cleaner code? Use the rule of six by ParetoOptimal on Saturday September 24, 2022 @04:12PM (#32966172)
> editor support should not become a prerequisite for existing code to be comprehensible.

I don't know... i'm frequently torn deciding between whether i think this is true or not.

On another note, readability of code is less about coding style and more about familiarity.

Re:Want cleaner code? Use the rule of six by _nalply on Saturday September 24, 2022 @03:39PM (#32965912)
One way I try to solve that problem in Rust: use repeated `let thing = simple.invocation();`. No need to rename the variable `thing` if not neccessary. Rust allows redefining a variable with the same name. Additionally I sometimes give the thing a type which makes it even more explicit.

Something like this:

    let thing: Thing = source.prepare();
    let thing = thing.make_iterator();
    let (first, second) = thing.split();
    let first = first.filter();
    let second = second.reverse();
    let items: Vec<Item> = first.join(second);
Just to give an idea how to make a complicated ritual explicit and simple.

This simplifies debugging too. You can set a breakpoint and view the variables or you can use println!.

Re:Want cleaner code? Use the rule of six by jacknews on Saturday September 24, 2022 @09:25PM (#32968148)
oof
Re:Want cleaner code? Use the rule of six by yencabulator on Sunday September 25, 2022 @05:58PM (#32976793)
This does nothing for when it's a map of string to array of map of string to string. Shape is not meaning, and naming things helps communicate meaning.
Re:Want cleaner code? Use the rule of six by WastingMyTime89 on Sunday September 25, 2022 @05:38AM (#32970027)
I think it is compounded in the article exemple by the flow of the code being non obvious. The map applies to code in its last argument. The lambda is the last action and the url parsing will happen first but is last in the line.

I have far less issue with the piping operator in Ocaml (|>) which works exactly like a shell pipe because the code is in sequential order and that makes a huge difference.

Python like JS weren’t designed as functional languages and it shows in their syntax. Still grateful for the added functionality however.

Re:Want cleaner code? Use the rule of six by e_i_pi_2 on Saturday September 24, 2022 @02:21PM (#32965290)
Definitely a good point, refactoring is great and has a bunch of benefits but can also be overdone and create problems. I've heard/read Sandi Metz talk about this as "The Wrong Abstraction"[1].

The basic argument is that any time you do an extract refactor you're creating a new layer of abstraction that the next reader will have to learn and understand. This can also get worse over time as the abstractions drift away from their original purpose.

The solution she provides is to be okay with a little bit of duplication, then as patterns naturally arise in the codebase you can refactor when you know a few use cases and can clearly define the concept.

[1]: https://sandimetz.com/blog/2016/1/20/the-wrong-abstraction

Re:Want cleaner code? Use the rule of six by chrisweekly on Saturday September 24, 2022 @02:32PM (#32965395)
Yes! IME (24y and counting in the profession) devs reach too quickly for DRY while neglecting its counterbalancing principle: AHA (Avoid Hasty Abstractions).
Re:Want cleaner code? Use the rule of six by wizofaus on Saturday September 24, 2022 @03:19PM (#32965743)
I've seen this complaint before and it doesn't really align with my experience of frequently seeing literal duplication of code where no extra abstraction was required to avoid it - just selecting the code in question and factoring it out into a function, which, providing you named it sensibly, would also make the code easier to understand and debug. I could count on one hand the number of times I've seen code where repeating logic would make more sense than any extra levels of abstraction created to avoid it.
Re:Want cleaner code? Use the rule of six by lamontcg on Saturday September 24, 2022 @05:24PM (#32966650)
The point isn't to maintain the repeated code forever. The point is to generate the repeated code and (maybe) live with it for a bit until you understand what the right abstraction is and then remove the duplication with the correct abstraction.

I've lost track of the number of times that I've taken badly abstracted code, reintroduced all the duplication, then refactored to remove the duplication with an entirely different abstraction and the code was many times easier to read.

And have you lived in a codebase for many years, where you've never come back to a method that you extracted and realized that you named it wrong? Or the requirements of the code grew and the duplication wasn't really at the level that you picked and you wind up with a method that grows all kinds of horrible options to change its internal behavior?

Re:Want cleaner code? Use the rule of six by wizofaus on Saturday September 24, 2022 @10:44PM (#32968502)
I've definitely seen cases where existing code was reused for a secondary, seemingly similar feature, unnecessarily complicating it and creating maintenance headaches when business requirements between the two features later diverged, and at best you might be able to claim it would have been better to simply copy & paste the code and modify it first, then look at how to refactor to avoid obvious cases of duplication. But I wouldn't consider that an example of developers trying to stay DRY at all costs.

Honestly the biggest problem I've had with maintaining the principle of not duplicating code is when a PO and/or UI/UX designer think we should only apply improvements to one feature to reduce the amount of work, when in fact it should be less work to apply them to all.

Re:Want cleaner code? Use the rule of six by xigoi on Saturday September 24, 2022 @12:47PM (#32964350)
Nim, D, VimScript and other languages have “uniform function call syntax”, which allows you to chain arbitrary functions like this (not just the ones that the author decided to declare as methods, like in Ruby and other class-oriented languages).
Re:Want cleaner code? Use the rule of six by irq-1 on Saturday September 24, 2022 @03:04PM (#32965608)
I wonder how much of Go's simplicity comes from having "package.function" syntax that doesn't allow you to put too many functions in a single line? People complain about Java because of the length of the names. Do they complain about to many functions in line? Maybe with ( ? : ) Lisp has )))))) which seems like a stupid complaint, but maybe that's tied to people having to remember too much?
Re:Want cleaner code? Use the rule of six by WalterBright on Saturday September 24, 2022 @04:21PM (#32966233)
D does too:

    import std.algorithm, std.array, std.stdio;
    // Print sorted lines of a file.
    void main()
    {
     auto sortedLines = File("file.txt")   // Open for reading
                        .byLineCopy()      // Read persistent lines
                        .array()           // into an array
                        .sort();           // then sort them
     foreach (line; sortedLines)
         writeln(line);
    }
Re:Want cleaner code? Use the rule of six by somehnguy on Saturday September 24, 2022 @12:44PM (#32964332)
Looks similar to Streams in Java. We try to use that style where appropriate as it is much more readable and compact than imperative style imo.
Re:Want cleaner code? Use the rule of six by vbezhenar on Sunday September 25, 2022 @12:20AM (#32968928)
For me that's questionable. Yes, there's code which fits finely with streams and looks very readable. Yet there's code which looks like it was shoehorned into a Procrustean bed and looks much better with ordinary loops.
Re:Want cleaner code? Use the rule of six by jonnycomputer on Saturday September 24, 2022 @12:56PM (#32964444)
I like this style too, though it can make debugging trickier.
Re:Want cleaner code? Use the rule of six by wizofaus on Saturday September 24, 2022 @03:23PM (#32965775)
It's been my feeling for a while that debugger technology hasn't really caught up with newer styles of coding (despite them having been around for over a decade). Only being able to set a breakpoint at a line-level or watch values that are assigned to a named variable is incredibly limiting.
Re:Want cleaner code? Use the rule of six by veltas on Sunday September 25, 2022 @01:02AM (#32969069)
gdb for a long time has been able to watch almost any expression at all. Unfortunately the visual studio debugger can't watch very much at all and that's what many of us are stuck with.
Re:Want cleaner code? Use the rule of six by wizofaus on Sunday September 25, 2022 @03:16AM (#32969564)
VS's debugger can watch arbitrary expressions, but it's not necessarily what you want (and admittedly isn't always reliable, or causes severe performance issues depending on the language etc.). What I'd really like is the ability to set breakpoints anywhere at all on a line, including a line like `xyz.map(_ -> ...).filter(_ -> ...)` such that, e.g. I can set a breakpoint between map( ) finishing and filter being called such that I can see what the map function has returned/what will be passed to filter, and of course at any point inside the lambda functions. And it's not just VS (or even VS code), but Chrome DevTools, XCode, IntelliJ/Android Studio etc. etc.
Re:Want cleaner code? Use the rule of six by atoav on Sunday September 25, 2022 @05:13AM (#32969961)
I build most of my classes that way in python.

    class Motor:
        def __init__(self):
            self.max_speed = 10.0
            self.clockwise = True
            self.controller = Controller()

        def set_max_speed(self, max_speed: float=10.0) -> 'Self':
            self.max_speed = max(0.0, max_speed)
            return self

        def start(self) -> 'Self':
            self.controller.start()
            return self

        etc..

Then you can use it as follows:

    motor = Motor().set_max_speed(5.0).start()
There is nothing stopping you from building iterators that work the same way
Re:Want cleaner code? Use the rule of six by BiteCode_dev on Sunday September 25, 2022 @03:43AM (#32969649)
I don't know, it doesn't seem very far form the python version:

    values = (
        key_value.partition('=')[-1]
        for key_value in 
        s.partition('?')[-1].split('&')
    )
Re:Want cleaner code? Use the rule of six by oriolid on Sunday September 25, 2022 @07:54AM (#32970529)
This is already showing why the the Python list/iterator comprehension syntax isn't great. The part "s.partition('?')[-1].split('&')" reads from left to right, and then the rest is read from end to beginning. It gets even more confusing with nested comprehensions. In my opinion both the dotted pipeline style and the Lisp style where you always start from the deepest nesting level are both more readable than Python's approach with sometimes from left to right, sometimes from right to left and sometimes from middle out.
Re:Want cleaner code? Use the rule of six by leobg on Saturday September 24, 2022 @01:04PM (#32964516)
Any way to do that in Python? Basically an anonymous function across multiple lines, which can be collapsed in the IDE view?
Re:Want cleaner code? Use the rule of six by gilch on Saturday September 24, 2022 @01:21PM (#32964683)
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
Re:Want cleaner code? Use the rule of six by Too on Monday September 26, 2022 @01:29AM (#32979737)
That’s misleading.

While you can have multiple lines, you are not allowed to have multiple statements.

Nobody wants to write code chained together with ternaries and and-operators. When someone says multi-line lambdas, what people actually mean is multi-statement lambdas.

Re:Want cleaner code? Use the rule of six by gilch on Wednesday September 28, 2022 @08:12PM (#33014814)
The misleading part wasn't from me. I'm trying to correct a common misconception here. Both "multiple" and "lines" are wrong.

Lambdas can't have single statements either. The body is only an expression. So why are we saying "multiple" (a word to distinguish from "single") if you meant to multiply statements? The number of statements is zero.

Does a try/except fit on one line? That's a try statement. Does a class? Technically possible, but typically no. That's a class statement. It's not just the "class" word, or the first line. The class statement includes its body. Many Python statement types can't fit on one line, and many others don't have to. So why are we saying "lines" to mean statements when these are not remotely the same thing?

The statement/expression distinction is a holdover from FORTRAN. Statements are just expressions that don't return a value. (Yes, Smalltalk and Haskell can implement control structures with expressions just fine, thank you.) Many functional languages do away with the distinction altogether and just use expressions. You only really need lambdas in Python for the functional style, and in functional style, expressions are all you need!

Re:Want cleaner code? Use the rule of six by vorticalbox on Saturday September 24, 2022 @01:12PM (#32964584)
Not exactly the same but in python you can use pipe to create pipelines

https://pypi.org/project/pipe/

Re:Want cleaner code? Use the rule of six by watwut on Sunday September 25, 2022 @03:01AM (#32969502)
No, this pipeline is not more readable. It is a annoying to have to constantly have to read it. It makes it harder to figure out what larger algorithm and design is.
Re:Want cleaner code? Use the rule of six by KerrAvon on Saturday September 24, 2022 @02:35PM (#32965418)
This style is increasingly common in Swift, especially for Combine pipelines and SwiftUI modifiers.
Re:Want cleaner code? Use the rule of six by badrabbit on Saturday September 24, 2022 @11:10PM (#32968608)
Sub routines are underused. Make it a function right where it is?
Re:Want cleaner code? Use the rule of six by tomlin on Saturday September 24, 2022 @04:36PM (#32966345)
Ruby maps are so ugly.

  .map { |key_value|
  key_value.partition('=')[-1] }
Reading this literally makes me sick to my stomach. Language design is much more important than language popularity, although it will be popularity that wins. (Yay downvotes for pointing out things everyone can see - highschool dynamics)
Re:Want cleaner code? Use the rule of six by samtheprogram on Saturday September 24, 2022 @04:41PM (#32966379)
Just because it’s a different syntax than you’re used to reading in another language doesn’t make it ugly. If you’re used to reading it and work in the language regularly, it actually looks quite clean.

This sounds like a Windows user who can’t stand macOS because they don’t know where anything is.

Your post downvote edit assumes your opinion here is objective. It isn’t.

Re:Want cleaner code? Use the rule of six by tomlin on Saturday September 24, 2022 @11:31PM (#32968693)
Parentheses as pipes is what you do when you’ve backed yourself into a corner.

Ruby has decided (for some reason?) to use two ways to declare.

Function(param, param)

and

{ |param, param| }

why? What is a good reason for this?

It would be an anti pattern in design, not sure why Ruby gets a special hall pass.

Re:Want cleaner code? Use the rule of six by klibertp on Sunday September 25, 2022 @09:56AM (#32971370)

   collect: [ :keyAndValue | (keyAndValue splitAt: '=') last ].
is why.

EDIT: (it's been a few months since I used it, so I) made a mistake in the syntax (declared local variable instead of a formal block argument), it's fixed now.

Re:Want cleaner code? Use the rule of six by tomlin on Sunday September 25, 2022 @10:03AM (#32971426)
You might as well have leaned on the keyboard, it wouldn’t look much different. This is not readable code.
[dead]
[dead]
[dead]
Re:Want cleaner code? Use the rule of six by dang on Thursday September 29, 2022 @02:07PM (#33024799)
Posting like this will get you banned on HN, regardless of how right you are or feel you are. Please review the site guidelines (https://news.ycombinator.com/newsguidelines.html) and please don't post like this to HN again.

This is particularly important when your argument happens to be a good one, because in that case you're discrediting the truth by posting abusively (see https://hn.algolia.com/?dateRange=all&page=0&prefix=true&sor... for past explanations of this point). That hurts everyone. It particularly hurts those of us who happen to agree with your view (me, for example—I haven't read much of this thread but I'm pretty sure I've made similar arguments about readability in the past).

Re:Want cleaner code? Use the rule of six by tomlin on Thursday September 29, 2022 @08:13AM (#33019464)
I don’t know Russian. Your point doesn’t line up with the topic at all. I know Ruby. I still think it’s unreadable. Can you try next time?

  I feel incredibly sorry for the poor kids you teach. They will be suffering aftereffects for the rest of their lives.
I feel bad that your account hasn’t been flagged for your behaviour on here. For someone who thinks they understand Ruby so well, you certainly haven’t taken any time to understand the rules. Personal attacks? Really? You just showed your cards. Weak arguments are followed with weak ad hominem.

It’s not just me, no one is teaching Ruby to kids because it’s not a good language for readability. Take it up with all of the teachers who see it just as I do.

Re:Want cleaner code? Use the rule of six by dang on Thursday September 29, 2022 @02:07PM (#33024800)
Please don't respond to a bad comment by breaking the site guidelines yourself. That only makes everything worse.

https://news.ycombinator.com/newsguidelines.html

Re:Want cleaner code? Use the rule of six by xtracto on Saturday September 24, 2022 @10:20PM (#32968381)
I'm curious , can you show an example of how to achieve the same in another language that you will consider pretty?