Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Java utility package

A common operation in my current project is converting a string version of an IP address into an integer representation, and it's easily handled by a single static method. I would normally try to keep this as close to the code that uses it as possible, but it's also needed in completely different parts of the application.

Since it seemed harmful to have classes in very different packages referring to each other for this one utility function, I created a util package and moved the static methods (one for int to String, one for String to int) into an Ip class in that package.

I recognize that this is probably a sign that I should rethink the project's organization, but is there anything harmful about adding a package to hold project-wide utility functions? Is there a standard way to handle this situation in Java?

like image 553
derekerdmann Avatar asked Aug 25 '11 12:08

derekerdmann


1 Answers

It's a generic problem, not just Java.

"Since it seemed harmful" - what's the harm? Coupling? Single point of failure?

You have an example of exactly what you did in the JDK itself: java.util has lots of classes that are used all over the place.

I think your design is defensible. Keep it that way until experience tells you a better place to put that class.

The one thing you should guard against is cyclic dependencies. Don't have anything in your util package depend on any of its dependencies. Break cycles with interfaces if you must.

like image 194
duffymo Avatar answered Oct 04 '22 11:10

duffymo