Hacker News new | ask | show | jobs
by Gibbon1 3991 days ago
I'm not sure how... pass it around is 'better' than global scope. Meaning not sure what problems you're avoiding here. If the scope is a single thread, no problem. If it's accessed from multiple threads, you have problems whether it's a global, singleton, or passed by reference.

Not actually completely true, you can still have races in single threaded code. Consider two state variables that are effected by a shared variable. Not hard to have the two state variables in disagreement over the shape of the world.

1 comments

> I'm not sure how... pass it around is 'better' than global scope.

- Readability: You can see what components use the thing by following the variable as it is passed around.

- Testability: Tests can pass in a mock thing.

- Maintainability: If you discover someday that you need two different instances of the thing to pass into two different subsystems, you can do that. (This happens a lot, and programmers are really bad at foreseeing it.)

- Security: Only the components to which you've passed the thing can possibly use it (subject to the memory safety guarantees of your language).

http://www.object-oriented-security.org/lets-argue/singleton...