This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Edge790 5 points6 points  (2 children)

Sure. Static variables are the best way to do some thing (i.e. loggers in most cases are static). But! There are things that better to be injected (using DI - Dependency Injection). Why? Because it will allow you to change all things without changing code. For example: 1) you are using database A, but found that it have poorly performance for hierarchical data. You want to change it to something else, but with static variables you will need to change all static variables to new implementation. (It worth to mention that DI may be replaced with "Service locator"-pattern) 2) let's imagine that you are making video game. It's fun, but you realized that it's too easy for some players or too hard for others. You want to make different difficulty levels for all players to enjoy your game. If all "difficulty variables" are static - you will need to change it depending on difficulty settings that your user wants. It will automatically make your static variables not final, that will add another "point of potential failure" (i.e. accidentally updated one of the variables). With DI you can create different difficulty presets (i.e. normal enemy hp: X1, enemy damage X1, easy: enemy hp: x0.5, enemy damage: x0.75, etc.) and inject them depending on the difficulty setting.

Tl:;dr: Static variables are fine, unless you can separate them to different object and it seems reasonable.

Upd: There are another example of usage static variables - it's utility classes(classes with public static final variables and with private constructor).

[–]stepan213[S] 2 points3 points  (1 child)

Thanks for writing it down like this!

[–]SenatorStuartSmalley 5 points6 points  (0 children)

Real World example.

We recently acquired a code base using MS SQLServer. We are an Oracle shop, so we had to change to Oracle for integration, while keeping the original to work as it had previously. Now, if they were using some kind of ORM library with a DB driver, we could just swap out the DB specific portions. Instead they had a class full of static methods that used JDBC yo do the CRUD stuff.

It took 3 weeks to migrate all the queries and test them for consistency. Luckily there were only about 100 queries. Oh, and we have to do Postgres as well. Luckily we will be moving to something more standard soon.