0

There are some methods and member variables in some classes that look so much similar and I thought I can refactor and abstract them away... but I am not sure if this is the correct way of doing this:

so for example let's say I have these two classes:

public class CaseField
{
  private int mlObjectKey = CommonIndepClass.GetNextObjectKey();
  public int ObjectKey
  {
    get
    {
      return mlObjectKey;
    }
  }

  // some other specific methods...
}

and then another class:

public class AsOfField
{
   private int mlObjectKey = CommonIndepClass.GetNextObjectKey();

   public int ObjectKey
   {
       get
       {
          return mlObjectKey;
       }
   }

   // some specific methods ... 
}

So I was thinking if it is correct to create an Abstract class and factor those methods and member variables and put them in that abstract class:

public abstract class CommonFields
{
   private int mlObjectKey = CommonIndepClass.GetNextObjectKey();

   public int ObjectKey
   {
       get
       {
          return mlObjectKey;
       }
   }

}

public class CaseField: CommonFields
{
  // just its own specific methods and member variables. 
}



public class AsOfField: CommonFields
{
  // just its own specific methods and member variables. 
}
Bohn
  • 26,091
  • 61
  • 167
  • 254
  • 1
    As a mechanism to keep your code DRY, this looks perfect and will continue to offer benefits as you continue to develop more CommonField types. – Killnine Sep 06 '12 at 14:57

1 Answers1

2

That seems not unreasonable.

An alternative is to implement this functionality using mixins. That would allow you to define one class with common functionality, but you wouldn't have to implement a common base class. See this SO answer for more details.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • hmm..thanks, I hadn't even heard about that word "mixins"... will study it..but if it got too much of learning curve, so the abstraction I had here is also correct? I was worried about those member variables, etc... – Bohn Sep 06 '12 at 14:50
  • 1
    They're called "Extension Methods" in .NET land, I believe – Eoin Campbell Sep 06 '12 at 15:04