user2253332
user2253332

Reputation: 827

Configuring if statements for better flexibility and scalability?

So I have two objects of the same type. The object looks like this:

public BatchOfStuff(int id, List<Stuff> stuffList)

Currently, my code looks like this:

if (stuffList1.Any()){
    var batchStuff1 = new BatchOfStuff(1, stuffList1);
    var transformedBatch = typeATransformer.TransformBatch(batchStuff1);
    ValidateTransformedBatch(transformedBatch);
}
if (stuffList2.Any()){
    var batchStuff2 = new BatchOfStuff(2, stuffList2);
    var transformedBatch = typeBTransformer.TransformBatch(batchStuff2);
    ValidateTransformedBatch(transformedBatch);
}

As you can see, the stuff in the two if statements are pretty much the same, the only difference being that one uses a TypeATransformer and the other a TypeBTransformer. TypeATransformer and TypeBTransformer both inherit from a base class called Transformer. It is possible that in the future, there will be TypeCTransformers and TypeDTransformers that follow the same pattern as the above. Is it possible for me to not have the duplicated code within the if statements? Thanks!

Upvotes: 0

Views: 50

Answers (1)

user1023602
user1023602

Reputation:

Wrap your duplicated code in a function, then call it twice:

 public BatchOfStuff ProcessBatch(int id, 
                                  List<Stuff> stuffList,
                                  BatchTransformer transformer)
 {
      if (stuffList1.Any())
      {
          var batchStuff = new BatchOfStuff(id, stuffList);
          var transformedBatch = transformer.TransformBatch(batchStuff);
          ValidateTransformedBatch(transformedBatch);

          return transformedBatch;
      }

      return null;
 }

 var batchStuff1 = ProcessBatch(1, stuffList1, typeATransformer);
 var batchStuff2 = ProcessBatch(2, stuffList2, typeBTransformer);

You didnt specify the transformer types - so that part is uncertain - but it will always be possible (one way or another) to reuse this code.

Upvotes: 1

Related Questions