Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice for a class to have only static fields and methods?

Tags:

oop

class

static

I have a class that consists only of static member variables and static methods. Essentially, it is serving as a general-purpose utility class.

Is it bad practice for a class to contain only static member variables and static methods?

like image 495
Stephen Watkins Avatar asked Dec 21 '09 21:12

Stephen Watkins


People also ask

Is it bad practice to use static methods?

Static methods are bad for testability. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous. Overriding a static method is not that simple for some languages.

Can a class have only static methods?

Utility Class, also known as Helper class, is a class, which contains just static methods, it is stateless and cannot be instantiated.

Is using static variables bad practice?

Static variables are generally considered bad because they represent global state and are therefore much more difficult to reason about. In particular, they break the assumptions of object-oriented programming.

Is it a good practice to use static methods in Java?

It's much easier to refactor methods that are static. It discourages unnecessary references to field members that make the coupling tight. It's also easier to understand calling code because it explicitly passes any objects it interacts with. Save this answer.


1 Answers

No, I don't think so at all. It is worse practice to have a class full of instance methods which don't actually depend on a particular instance. Making them static tells the user exactly how they are intended to be used. Additionally, you avoid unnecessary instantiations this way.

EDIT: As an afterthought, in general I think its nice to avoid using language features "just because", or because you think that that is the "Java way to do it". I recall my first job where I had a class full of static utility methods and one of the senior programmers told me that I wasn't fully harnessing the OO power of Java by making all of my methods "global". She was not on the team 6 months later.

like image 52
danben Avatar answered Sep 19 '22 15:09

danben