views:

74

answers:

2

Suppose I have a function that performs some task (this is in Python pseudocode):

def doTask():
    ...

But I have several optional features on the platform which results in having code that looks like this:

def doTask():
    ...
    if FEATURE_1_ENABLED:
        ...
    if FEATURE_2_ENABLED:
        ...
    ...

Unfortunately, this gets rather messy with many different optional features that coincide with one another. What kinds of design patterns solve this issue?

+1  A: 
interface Feature{

  void execute_feature();

}

class Feature1 implements Feature{
  void execute_feature(){}
}
class Feature2 implements Feature{
  void execute_feature(){}
}

public static void main(String argv[]){

List<Feature> my_list = new List<Feature>();
my_list.Add(new Feature1());
my_list.Add(new Feature2());

for (Feature f : my_list){
  f.execute_feature();
}

}

I think it's called strategy pattern

Syntax might not be exact

Eric
+4  A: 

This is what Command and Strategy are all about. As well as Composition.

class Command( object ):
    def do( self ):
        raise NotImplemented

class CompositeCommand( Command, list ):
    def do( self ):
        for subcommand in self:
            subcommand.do()

class Feature_1( Command ):
    def do( self, aFoo ):
        # some optional feature.

class Feature_2( Command ):
    def do( self, aFoo ):
        # another optional feature.

class WholeEnchilada( CompositeCommand ):
    def __init__( self ):
        self.append( Feature_1() )
        self.append( Feature_2() )

class Foo( object ):
    def __init__( self, feature=None ):
        self.feature_command= feature
    def bar( self ):
        # the good stuff
        if self.feature:
            self.feature.do( self )

You can compose features, delegate features, inherit features. This works pretty well for an expandable set of optional features.

S.Lott