logoalt Hacker News

skipantslast Friday at 9:49 PM2 repliesview on HN

I often employ this pattern in Ruby using `.tap` or a `begin` block.

It barely adds any functionality but it's useful for readability because of the same reasons in the OP.

It helps because I've been bitten by code that did this:

  setup_a = some_stuff
  setup_b = some_more_stuff
  i_think_this_is_setup = even_more_stuff
  the_thing = run_setup(setup_a, setup_b, i_think_this_is_setup)
That's all fine until later on, probably in some obscure loop, `i_think_this_is_setup` is used without you noticing.

Instead doing something like this tells the reader that it will be used again:

  i_think_this_is_setup = even_more_stuff
  
  the_thing = begin
    setup_a = some_stuff
    setup_b = some_more_stuff
    run_setup(setup_a, setup_b, i_think_this_is_setup)
  end
I now don't mentally have to keep track of what `setup_a` or `setup_b` are anymore and, since the writer made a conscious effort not to put it in the block, you will take an extra look for it in the outer scope.

Replies

ramses0yesterday at 3:55 AM

JavaScript chiming in...

    function abc() {
       let a = 1
       {
         let b = 2
       }
       console.log(typeof a)      
       console.log(typeof b)
     }
     abc()
Used to do this occasionally for exactly the same reasons- don't leave dangling variables junking up your scope, and don't make weirdo functions with parameter passing that you'll only ever call once!
gleennlast Friday at 9:58 PM

Clojure also has the threading macro -> and ->> which are great at converting exactly the same type of code into a stream of modifications instead of breaking out everything into variables. Naming things can be very useful sometimes but sometimes it is entirely gratuitous and distracting to have

let input = read_input(); let trimmed_input = input.trim(); let trimmed_uppercase_input = trimmed_input.uppercase();

...

The extra variable names are almost completely boilerplate and make it also annoying to reorder things.

In Clojure you can do

(-> (read-input) string/trim string/upcase)

And I find that so much more readable and refactorable.