Why best practices vary for Static classes in OOP?

前端 未结 2 1117
小蘑菇
小蘑菇 2020-12-19 11:01

I\'m currently reading about Java best practices and I found that according to this book we must Favor static classes over nonstatic. I\'ve remembered that in C# be

相关标签:
2条回答
  • 2020-12-19 11:30

    Advice given by JoshuaBloch also applies for c# and advice given for c# also applies for java(upto an extent as they talk about static classes).

    Why use static members?

    • They don't need an instance to call them
    • In c# they use call opcode, which doesn't needs to check for null(which is a micro optimization) as opposed to instance methods(which uses callvirt opcode). I believe similar thing will be there in java also.
    • They don't prevent something from GC if instance is not used.
    • Also no overhead of passing this reference to all the methods hidden.

    If you are used to Resharper productivity tool for visual studio, It will give the same advice as JoshuaBloch given for java, in c# saying that Method can be made static which is justified in the given link.

    Why not use static members?

    • They are not testable(easily).
    • They can't implement interface member.
    • They can't be injected via Dependency Injection.
    • They don't participate in polymorphism (which is very much needed in object oriented languages).
    • In c#, static classes can't be passed around as references.

    So, both advices are good if you understand them and they apply for both the languages. Use them when they are appropriate and avoid them when they are not.

    0 讨论(0)
  • 2020-12-19 11:39
    1. I consider that second text fragment is all about member class and enclosing, which is Java-specific feature (how it is implemented).
    2. Static class or field (as in C#) is actually bad design practice - take a look at OOP and SOLID. In addition it can result in some performance issues on CLR level. But it's nothing wrong with private static method. As I remember, Resharper advices to make private methods independent on concrete instances static. It increases readability and has no side-effects. And you not need to unit test private method. It's bad practice too.
    3. Finally, some authors write about technologies in nutshell and some - about design principles. Often there is a contradiction between these points of view (but depicted two fragments is not about it).
    0 讨论(0)
提交回复
热议问题