If a "Utilities" class is evil, where do I put my generic code?

John Gietzen picture John Gietzen · Jul 27, 2010 · Viewed 24k times · Source

I generally live by the rule that Global variables / functions are evil and that every piece of code should live in the class to which it pertains.

This is a very easy rule to follow, and I believe that I haven't ever run into an issue with this rule until now.

Today, however, I need to add a function to my assembly rather than to a specific class. That is, almost all of my classes could have a use for this particular function.

Where should I put this function (+1 overload)?

If I put it in a "Utilities" class, I feel dirty. If I tack it on to a semi-related class, and let other classes call it directly, I feel worse.

This particular piece of code basically chops a IList<PointF> into a normalized list. I feel right now that adding it as an extension method on IList<PointF> may be the best bet...

Answer

H&#229;vard S picture Håvard S · Jul 27, 2010

If this is an operation on an IList<PointF>, then it should be an extension method on IList<PointF>.

Generally, Utils and Helper type classes should be avoided. More often than not, you will find that what you may think is a utility method, is actually a rather specific method that probably belongs in a class of its own (just like you say). However, there will be domain specific cases where Util-like classes (classes which group related useful methods) are valid entities.