Why are static variables considered evil?

前端 未结 30 2829
既然无缘
既然无缘 2020-11-21 05:04

I am a Java programmer who is new to the corporate world. Recently I\'ve developed an application using Groovy and Java. All through the code I wrote used quite a good numbe

30条回答
  •  故里飘歌
    2020-11-21 06:03

    Yet another reason: fragility.

    If you have a class, most people expect to be able to create it and use it at will.

    You can document it's not the case, or protect against it (singleton/factory pattern) - but that's extra work, and therefore an additional cost. Even then, in a big company, chances are someone will try at some point to use your class without fully paying attention to all the nice comments or the factory.

    If you're using static variables a lot, that will break. Bugs are expensive.

    Between a .0001% performance improvement and robustness to change by potentially clueless developers, in a lot of cases robustness is the good choice.

提交回复
热议问题