←back to thread

498 points azhenley | 4 comments | | HN request time: 0.89s | source
Show context
nixpulvis ◴[] No.45771961[source]
I try to keep deeper mutation to where it belongs, but I'll admit to shadowing variables pretty often.

If I have a `result` and I need to post-process it. I'm generally much happier doing `result = result.process()` rather than having something like `preresult`. Works nicely in cases where you end up moving it into a condition, or commenting it out to test an assumption while developing. If there's an obvious name for the intermediate result, I'll give it that, but I'm not over here naming things `result_without_processing`. You can read the code.

replies(5): >>45772035 #>>45772551 #>>45773468 #>>45775029 #>>45776914 #
nailer ◴[] No.45772551[source]
result.process()

That doesn’t make logical sense. You already have a result. It shouldn't need processing to be a result.

replies(1): >>45773269 #
riskable ◴[] No.45773269[source]
It also doesn't make sense for `process()` to be an attribute of `result`. Why would you instantiate a class and call it result‽
replies(2): >>45773534 #>>45775586 #
1. Bayko ◴[] No.45773534[source]
A more common example for me at work is getting a response from url. Then you gotta process it further like response.json() or response.header or response.text etc etc. and then again select the necessary array index or doc value from it. Giving a name like pre_result or result_json etc etc would just become cumbersome.
replies(1): >>45773943 #
2. nixpulvis ◴[] No.45773943[source]
I would never do `response = response.json()`. I use it when it's effectively the same type, but with further processing which may be optional.
replies(1): >>45775077 #
3. nomel ◴[] No.45775077[source]
Depends on how clear it is.

I usually write code to help local debug-ability (which seems rare). For example, this allows one to trivially set a conditional breakpoint and look into the full response:

    response = get_response()
    response = response.json()
The fact that the first response is immediately overwritten proves to the reader it's not important/never used, so they can forget about it, where a temp variable would add cognitive load since it might be used later.

and I think is just as clear as this:

    response = get_response().json()

This motivated by years of watching people through code, and me working with deeply non-software engineers, and is always very much appreciated.
replies(1): >>45785592 #
4. nailer ◴[] No.45785592{3}[source]

    get_response().json() 
is ideal, and I'm assuming yoiu're writing an HTTP wrapper since decoding JSON is a sensible default.

If you need to add an intermediary variable, name it as clearly as possible:

    raw_response = get_response()
    response = raw_response.json()