Skip to main content
gamedev.net
🔒 Locked

[java] Rules for using static classes?

Started by moregames 11 replies 700+ views
Original Post
moregames
moregames
Are there any rules for when to create classes with static methods and fields? I tend to create instances of classes that really could be static, because all they provide is functionality. Basically, can someone formulate a rule for when to use sub-classing and when to use static classes? Thanks
WayfarerX
WayfarerX
Good question.

Beyond obvious uses like implementing a Singleton pattern, I use static members for things like enumerations, constants, conditional-compilation flags, etc.
When writing functions, I put try to put functions that modify an object as member functions of that object, and functions that perform quick, frequently used operations on simple parameters as static.

Example: In my 3D math library, my Vector * Matrix function is a member of the Vector class since it modifies the Vector.
Whereas in my fixed-point math library, all the functions are static functions that operate on the parameters and return a result.

So I guess my basic rule is if the function uses something outside it''s own scope, I make it a member function. Of course there are all sorts of little situations where this might or might not be optimal (like for instance, a static function that performs sqrt() or sin() via a static look-up table, or a function that accepts 2 parameters of different types and modifies them both), so it still needs to be evaluated on a case-by-case basis.

"So crucify the ego, before it''s far too late. To leave behind this place so negative and blind and cynical, and you will come to find that we are all one mind. Capable of all that''s imagined and all conceivable."
- Tool

"There is no reason good should not triumph at least as often as evil. The triumph of anything is a matter of organization. If there are such things as angels, I hope that they're organized along the lines of the mafia." -Kurt Vonnegut
moregames
moregames
WayfarerX thanks for your reply.

Creating instances of a class is time consuming, so are there any drawbacks to using static classes when it comes to performance etc.?

I will share a real case scenario that perhaps someone can help share some genious thoughts upon. I have:

1. A character class
2. A class that implements DB functions
3. Pool of connections to the database.

A new instance of the character class (nr 1) is created for each player that connects to the server. Each character instance creates its _own_ instance of the DB class (nr 2). The DB class provides a bunch of functions that relate to the character class (i.e. storing and loading character attributes etc.). The DB class retrieves a single DB thread from a pool (nr 3), uses it and returns it.

Couldnt the DB class (nr 2) just be static? It only provides methods and doesnt keep any variables of its own. What problems would/could arise? Perhaps someone has a better model or design. Any thoughts are welcome.

I will explain further if needed.


Edited by - moregames on November 28, 2001 3:09:02 PM
AdmiralBinary
AdmiralBinary
Sometimes if you have classes which have only one instance, it may be a good idea to use a namespace instead. I''m not sure on this one, and I''m ready to be corrected if I''m wrong.

"That''s what I think anyway." - Mr. Bean

---------------

I finally got it all together...
...and then forgot where I put it.
bstepa
bstepa
Does the DB class manage the connection pooling? It sounds like it is solely responsible for retrieving and releasing database connections. If the class will only be responsible for retrieving and releasing database connections then a singleton implementation might be overkill and just having static functions should be sufficient. If the class is also responsible for database connection pool management, than a singleton is probably a good idea.

On a side note, singletons will get you in trouble if accessed from different threads. If the singleton manages the connection pool, you''ll have to make sure it''s thread safe (mutex etc).

Brendon
WayfarerX
WayfarerX
AdmiralBinary, Java forum buddy, no namespaces.

moregames, I would keep it in an instance in this case. Yes, creating objects is slow, but when you''re dealing with one-time creation like you are here it''s really negligible. Object creation only really gets bad inside loops or frequently called functions (and newer JITs will smooth that away anyway).
I would do this: create an Interface that defines the methods you need (ie: saveCharacter(Character c, Connection con), etc),
and then sub-class it with a implementation for the specific database you''re using. That way if you ever change your underlying database (ever try to port from SQL Server to Oracle? removing all those semi-colons is a bitch), all you have to do is make a new sub-class of your interface and you''re ready to go. This isn''t possible with static functions, and to change to a different implementation you have to find and change every call to your static class to another.
This also sounds like a good place for an Abstract Factory pattern to create these objects for you.

Remember, objects aren''t just for storing data, they are also for abstraction. In a situation like this where your DB function class could possibly save to many different types of storage (SQL DB, flat file, memory & disk caches, etc) it just screams for polymorphism.

"So crucify the ego, before it''s far too late. To leave behind this place so negative and blind and cynical, and you will come to find that we are all one mind. Capable of all that''s imagined and all conceivable."
- Tool

"There is no reason good should not triumph at least as often as evil. The triumph of anything is a matter of organization. If there are such things as angels, I hope that they're organized along the lines of the mafia." -Kurt Vonnegut
AdmiralBinary
AdmiralBinary
quote:

I'm not sure on this one, and I'm ready to be corrected if I'm wrong.


Well, looks like I was

quote:

AdmiralBinary, Java forum buddy, no namespaces.


Sorry! I didn't notice the "Java Development" bit at the top of the page...

(Writes on a blackboard 100 times: )
C++ is NOT the only programming language.
C++ is NOT the only programming language.
C++ is NOT the only...


---------------

I finally got it all together...
...and then forgot where I put it.

Edited by - AdmiralBinary on November 28, 2001 3:44:03 PM
WayfarerX
WayfarerX
quote:
Original post by AdmiralBinary
Sorry! I didn''t notice the "Java Development" bit at the top of the page...

(Writes on a blackboard 100 times: )
C++ is NOT the only programming language.
C++ is NOT the only programming language.
C++ is NOT the only...




LOL, it''s cool man, done it myself a couple of times.


"So crucify the ego, before it''s far too late. To leave behind this place so negative and blind and cynical, and you will come to find that we are all one mind. Capable of all that''s imagined and all conceivable."
- Tool

"There is no reason good should not triumph at least as often as evil. The triumph of anything is a matter of organization. If there are such things as angels, I hope that they're organized along the lines of the mafia." -Kurt Vonnegut
moregames
moregames
The DB Class (nr2) as i described it does not handle the connections etc. It just implements a bunch of functions that all character instances use. Example would be a function to update character attributes.

The DB Class retrieves a connection from a seperate Pool Manager, I dont know if this bit would be problematical if it were a static class?
Arild Fines
Arild Fines
Whats a static class anyway? AFAIK, only inner classes can be static.

Psalm 137:9: "Happy shall he be, that taketh and dasheth thy little ones against the stones."
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]
Kaijin
Kaijin
When he refers to a static class, the class isn''t actually ''static'' but it contains only static methods and a private constructor so in effect it is.

i.e.

    
public class StaticClass {
// Stops the class from being instanciated

// by an outside class

private StaticClass() {}

// Static mehtods

public static void methodOne() {}
public static void methodTwo() {}
}


- Kaijin
Arild Fines
Arild Fines
I was being pedantic.

Psalm 137:9: "Happy shall he be, that taketh and dasheth thy little ones against the stones."
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]
Jim_Ross
Jim_Ross
For the example of a DB and a Character class. I would really make the DB class an interface instead of a real class. If a Character object gets an instance of DB in order to save it, the DB object has to know all about the Character object and its use is limited. If, instead, it were an interface you could use that functionality for many classes.

interface DB {

public void save();
public Object load();
}

class Character implements DB {

Character() { ... }

public void save() {
DBConn = DBPool.getConn();
DBConn.query("update blah where pkey= " +this.pkey);
}
...
}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.