Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make my static class not so static?

I have a static class that contains my database logic.

This class is used in a website, web services and as part of a middleware component.

For every method in this class I need a piece of context information from the caller. In the case of the web site this would be user information, for the web service and middleware component, this would identify the calling service.

I can't store this value in the config because this might differ per user and I don't always have a httpcontext to get this from.

I could easily add a new parameter onto every method in this class or I could change it from a static class so that it has a single non-static property but neither of those solutions seem very elegant.

So are there any other options I haven't considered?

like image 712
Chris Simpson Avatar asked Feb 19 '10 17:02

Chris Simpson


People also ask

Can static class have non static method?

A static class can only contain static data members, static methods, and a static constructor.It is not allowed to create objects of the static class. Static classes are sealed, means you cannot inherit a static class from another class.

Can we override static method?

Can we Override static methods in java? We can declare static methods with the same signature in the subclass, but it is not considered overriding as there won't be any run-time polymorphism. Hence the answer is 'No'.

Why You Should Avoid static classes?

Static classes have several limitations compared to non-static ones: A static class cannot be inherited from another class. A static class cannot be a base class for another static or non-static class. Static classes do not support virtual methods.

Can static class have non static method in Java?

What is Static Method in Java? Static method in Java is a method which belongs to the class and not to the object. A static method can access only static data. A static method can call only other static methods and can not call a non- static method from it.


2 Answers

If all the methods need some state, it sounds a lot like you should create an instance and pass that state via the constructor.

Changing the design from a bunch of static methods to an instance will also make it easier to test the class.

like image 145
Brian Rasmussen Avatar answered Nov 07 '22 15:11

Brian Rasmussen


I would add the parameters. It doesn't seem inelegant to me - you need context info, and the only way to get it in a static class is by passing it in.

like image 24
Ray Avatar answered Nov 07 '22 15:11

Ray