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# best practices we must avoid such according to Coding Guidelines for C# 3.0, 4.0 and 5.0 by Dennis Doomen:
AV1008 - Avoid static classes
With the exception of extension method containers static classes very often lead to badly designed code. They are also very difficult, if not impossible, to test in isolation unless you’re willing to use some very hacky tools. Note If you really need that static class, mark it as static so that the compiler can prevent instance members and instantiating your class. This relieves you of creating an explicit private constructor.
I found these two for C# answer and Java answer when to use and avoid static classes, but just by curiosity - both C# and Java are OOP languages, why it's this complete difference then in best practices?
Update: I can't copy so much pages here from the Java book, but bottom line is:
If you declare a member class that does not require access to an enclosing instance, always put the static modifier in its declaration, making it a static rather than a nonstatic member class. If you omit this modifier, each instance will have an extraneous reference to its enclosing instance. Storing this reference costs time and space, and can result in the enclosing instance being retained when it would otherwise be eligible for garbage collection (Item 6). And should you ever need to allocate an instance without an enclosing instance, you’ll be unable to do so, as nonstatic member class instances are required to have an enclosing instance. A common use of private static member classes is to represent components of the object represented by their enclosing class.
So is it about performance only?
Please note that this question is more about Static classes and OOP, not difeerences between Java and C#.
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?
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.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?
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.
member class
and enclosing
, which is Java-specific feature (how it is implemented).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With