top | item 42998744

(no title)

matheweis | 1 year ago

> A Few Rules For Using Globals: > If you change observable state, restore it

I’m sorry but no. Humans are human and mistakes will be made. I’ve lost count of the number of esoteric bugs I’ve had to track down due to global state being changed and not put back properly.

If you have to qualify a pattern with rules that are easily forgotten or open to corner case bugs, it’s far better to just not use that pattern in the first place.

discuss

order

thom|1 year ago

The author shows encapsulation of global state elsewhere. I’m not sure why they wouldn’t use RAII for the log level stuff so it was automatically rolled back.

levodelellis|1 year ago

I'm the author. I seen people make mistakes writing pure functions with many if statements in them. For a small period I heard people say loops should be banned. Would you want to go that far?

If your narrow the usage of a global within a file you can get a lot of mileage. That's not how people tend to use globals and why I wanted to write about it

tialaramex|1 year ago

Just two of the "rules" is enough to see that there's no sense here:

1. It should be hard or impossible to use incorrectly. For example, counter() keeps increments consistent. 2. If you change observable state, restore it.

That can be summarised as "To prevent mistakes: Don't make any mistakes". It made lots of sense once I saw this was by a C++ programmer, C++ is the language with, as a prominent C++ practitioner put it: False Positives for the question: Is this a valid program?

If you're used to a language which gaslights you by having the compiler not emit any diagnostics whatsoever and just calmly handing you a nonsensical output executable because what you wrote was subtly wrong obviously global variables seem fine, what's not to like? You just have to be inhumanly competent at all times, which was the baseline requirement for the entire language.

levodelellis|1 year ago

I had a feeling someone would bring this up (I'm the author.) Your state really shouldn't be depending on IDs or handles from a counter function. I'm not sure if most people can agree with what is considered using a global variable which is why I wanted to define it near the start

Salgat|1 year ago

Yeah, I like how the OP basically recreates scoped variables by applying all these strict rules, instead of just using scoped variables. For example, with DI, instead of a global variable, we just use a singleton/scoped dependency. Why? Because we can enforce those rules implicitly without hoping everyone pinky promises to use the global variables correctly.

levodelellis|1 year ago

If you want to write code to show me what you're talking about (best if I can run it) I'll tell you why or why not. I can tell you right now I dislike DI (and singletons) for reasons I can't cover in a single post