views:

179

answers:

6

I have just one method that I need several different classes to access and it just seems lame to make a utility class for just one method. The classes that need to use this method are already inheriting an abstract class so I can't use inheritance. What would you guys do in this situation?

+1  A: 

What do you mean you can't use inheritance?

If you write the method in the abstract class, you can also write the implementation (not everything in an abstract class needs to be abstract).

But generally, it's advisable to have some sort of 'GeneralUtils' class; cause you end up with a few of these functions.

Noon Silk
I meant I can't create a base/abstract class with the method that these classes can share because they are already inheriting from a different base class.
Allensb
Ohh; okay, makes sense.
Noon Silk
+11  A: 

[I]t just seems lame to make a utility class for just one method

Just do it, it will grow. It always does. Common.Utilities or something of that nature is always necessary in any non-trivial solution.

JP Alioto
+6  A: 

Keep in mind that a class is just a small, focused machine. If the class only has one method then it's just a very small, focused machine. There's nothing wrong with it, and centralizing the code is valuable.

STW
Jim Lewis
A: 

I'd need more info to give a definite answer. However a well-named class with a single well-named method could work wonders for readability (as compared to an inheritance based solution for instance)

Since you use the term utility method, I'd say create a static class with the static method and be done with it.

Gishu
+2  A: 

There is a cheat that you can use :-)

Create an Interface that your classes can "implement" but, create an extension method on that interface, your classes then magically get that method without having to call the utility class...

public Interface IDoThisThing {}

public static void DoThisThingImpl(this IDoThisThing dtt)
{
  //The Impl of Do this thing....
}

Now on your classes you can just add the IDoThisThing

public class MyClass, MyBaseClass, IDoThisThing
{
  //...
}

and they Get that thing :-)

Note, this is only syntatic sugar around effectively a utility class, but it does make the client code very clean (as just appears as a method on your class).

Tim Jarvis
A: 

can use extension methods...

namespace ExtendMe
{
    public interface IDecorate { }

    public static class Extensions
    {
        public static void CommonMethod(this IDecorate o) { /* do stuff */ }
    }

    public class Blah :IDecorate {}

    public class Widget : IDecorate {}

    class Program
    {
        static void Main(string[] args)
        {
            new Blah().CommonMethod();
            new Widget().CommonMethod();
        }
    }
}
Keith Nicholas