Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a method based on the value of an enumeration without falling into a code smell

Imagine I have a document (word document).

I have an enumeration which will indicate how to extract data from the document. So if I want just text, the images, or both (3 members of the enumeration).

I have a case statement based on this enumeration, but without falling into a code smell, how can I write code which isn't too repetitive? For every condition in the switch, should I have a seperate method (the easiest way), or a method accepting a paremeter (like the value of the enumeration), and then use if statements to say if(xyz) do abc, and so on.

Or is there a quicker, more efficient way?

like image 957
GurdeepS Avatar asked Jan 20 '26 01:01

GurdeepS


1 Answers

I would use a Strategy pattern coupled with a factory to create the appropriate strategy based on the value of the enumeration. EDIT As others have pointed out you could also determine the correct strategy via a Map as well. Factory is my choice because it only encapsulates the logic and doesn't require any data storage.

public interface IExtractionStrategy
{
    object Extract( Document doc );  // or what ever result is best
}

public class TextExtractionStrategy : IExtractionStrategy
{
    public object Extract( Document doc )
    {
     .... algorithm for extracting text...
    }
}

public class ImageExtractionStrategy : IExtractionStrategy
{
    public object Extract( Document doc )
    {
     .... algorithm for extracting images...
    }
}


public static class StrategyFactory
{
     IExtractionStrategy GetStrategy( ExtractionEnum strategyType )
     {
         switch (strategyType)
         {
             case ExtractionEnum.Text:
                 return new TextExtractionStrategy();
                 break;
             case ExtractionEnum.Image:
                 return new ImageExtractionStrategy();
                 break;

             ...
         }
     }
}
like image 129
tvanfosson Avatar answered Jan 23 '26 06:01

tvanfosson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!