views:

538

answers:

7

I have been reading that creating dependencies by using static classes/singletons in code, is bad form, and creates problems ie. tight coupling, and unit testing.

I have a situation where I have a group of url parsing methods that have no state associated with them, and perform operations using only the input arguments of the method. I am sure you are familiar with this kind of method.

In the past I would have proceeded to create a class and add these methods and call them directly from my code eg.

UrlParser.ParseUrl(url);

But wait a minute, that is introducing a dependency to another class. I am unsure whether these 'utility' classes are bad, as they are stateless and this minimises some of the problems with said static classes, and singletons. Could someone clarify this?

Should I be moving the methods to the calling class, that is if only the calling class will be using the method. THis may violate the 'Single Responsibilty Principle'.

A: 

They're fine as long as you design them well ( That is, you don't have to change their signature from time to time).

These utility methods do not change that often, because they do one thing only. The problem comes when you want to tight a more complex object to another. If one of them needs to change or be replaced, it will be harder to to if you have them highly coupled.

Since these utility methods won't change that often I would say that is not much problem.

I think it would be worst if you copy/paste the same utility method over and over again.

This video How to design a good API and why it matters by Joshua Bloch, explains several concepts to bear in mind when designing an API ( that would be your utility library ). Although he's a recognized Java architect the content applies to all the programming languages.

OscarRyz
+2  A: 

Utility classes are ok..... as long as they don't violate design principles. Use them as happily as you'd use the core framework classes.

The classes should be well named and logical. Really they aren't so much "utility" but part of an emerging framwework that the native classes don't provide.

Using things like Extension methods can be useful as well to align functionality onto the "right" class. BUT, they can be a cause of some confusion as the extensions aren't packaged with the class they extend usually, which is not ideal, but, still, can be very useful and produce cleaner code.

Keith Nicholas
+1  A: 

You could always create an interface and use that with dependency injection with instances of classes that implement that interface instead of static classes.

The question becomes, is it really worth the effort? In some systems, the answer in yes, but in others, especially smaller ones, the answer is probably no.

Matthew Scharley
This is what I would suggest too. If the utility method is complex or computationally expensive, I would suggest using dependency injection to inject it as a service object of some kind. Otherwise I wouldn't worry about it.
Jamie Penney
The injection doesn't remove the dependency. It just make it easier to handle.
OscarRyz
The only way to **remove** a dependency is to remove it. I don't see your point.
Matthew Scharley
+7  A: 

From a theoretical design standpoint, I feel that Utility classes are something to be avoided when possible. They basically are no different than static classes (although slightly nicer, since they have no state).

From a practical standpoint, however, I do create these, and encourage their use when appropriate. Trying to avoid utility classes is often cumbersome, and leads to less maintainable code. However, I do try to encourage my developers to avoid these in public APIs when possible.

For example, in your case, I feel that UrlParser.ParseUrl(...) is probably better handled as a class. Look at System.Uri in the BCL - this handles a clean, easy to use interface for Uniform Resource Indentifiers, that works well, and maintains the actual state. I prefer this approach to a utility method that works on strings, and forcing the user to pass around a string, remember to validate it, etc.

Reed Copsey
Good point. System.Uri is a good example of converting a static utility method like this to an object.
Jamie Penney
It's also very relevant to their specific question, given their example ;)
Reed Copsey
A pretty bad example as System.Uri is known to be littered with problems related to original string representation and conversions to/from absolute relative paths. This is what happens on every abstraction design and API formulation, you never ever get it right out of the box, and with MSFT framework designers it takes ages to get it right and often causes more complication than with static methods that are easy and known to be functional in nature. But that's a problem with 'framework' and 'design guidelines' mania approach in general..
rama-jka toti
Could someone please explain what is meant by "They basically are no different than static classes (although slightly nicer, since they have no state)." Perhaps I'm missing how a "utility" class would be declared. Based on the example it looks like a static class. What "state" is Reed referring to?
Michael Petito
It's usually just a static class with no fields or properties, hence no "state" that's saved, but rather just a series of methods used as utilities.
Reed Copsey
+1  A: 

I really, really try to avoid them, but who are we kidding... they creep into every system. Nevertheless, in the example given I would use a URL object which would then expose various attributes of the URL (protocol, domain, path and query-string parameters). Nearly every time I want to create a utility class of statics, I can get more value by creating an object that does this kind of work.

In a similar way I have created a lot of custom controls that have built in validation for things like percentages, currency, phone numbers and the like. Prior to doing this I had a Parser utility class that had all of these rules, but it makes it so much cleaner to just drop a control on the page that already knows the basic rules (and thus requires only business logic validation to be added).

I still keep the parser utility class and these controls hide that static class, but use it extensively (keeping all the parsing in one easy to find place). In that regard I consider it acceptable to have the utility class because it allows me to apply "Don't Repeat Yourself", while I get the benefit of instanced classes with the controls or other objects that use the utilities.

Godeke
A: 

I agree with some of the other responses here that it is the classic singleton which maintains a single instance of a stateful object which is to be avoided and not necessarily utility classes with no state that are evil. I also agree with Reed, that if at all possible, put these utility methods in a class where it makes sense to do so and where one would logically suspect such methods would reside. I would add, that often these static utility methods might be good candidates for extension methods.

Matt Wrock
A: 

Use them sparingly, you want to put as much logic as you can into your classes so they dont become just data containers.

But, at the same time you can't really avoid utilites, they are required sometimes.

In this case i think it's ok.

FYI there is the system.web.httputility class which contains alot of common http utilities which you may find useful.