Search code examples
c#design-patternsarchitecturebarcode-scanner

Design pattern suggestions for barcode scanner app with large case statement


I'm looking for some input as to a good design pattern/model to use for refactoring a windows CE barcode scanning application used in a manufacturing plant. Trying to make it a little more object-oriented and a little less procedural

Currently, the bulk of the app's functionality is controlled by large case statements in essentially one main method, and the values of private integers determine which path to take through the cases.

Because many scans are performed in sequence, the code essentially loops through this main method after every barcode scan, until the user exits to the menu and selects a different scan functionality.

For many transaction types, the code needs to take multiple paths through the main case statement in sequence. For example, the "packing" transaction requires the user to first scan their id badge, then scan the target container, and then scan the item to be packed in the target container, all of which are separate cases in the main method.

In this case, a very simplified example:

private int activeTrans;
private int baseTrans;
private int nextTrans;

btnPack_Click()
{
   nextTransaction = 2
   StartTransaction(1, 1)              
}

StartTransaction(int transId, int transMode)
{
  //determines the initial path(s) to take 

  switch (transMode)
  {
    case 1:  //scan parent 
      activeTrans = 4;
      baseTrans = transId;
      break;

    //a handful of other case statements representing the major types of transactions
    ...
  }

  StartBarcodeRead() //the scanner prepared to scan, once the user scans a barcode, 
                     //the HandleData method is called
}

HandleData()
{
  switch (activeTrans)
  {
    case 1:  //select target container
      DoSomeMethodForTheTargetContainer();
      activeTrans = baseTrans;

    case 2:  //pack in container
      DoThePackingMethod();

    case 3:  //scan id badge
       ValidateIdBadgeScan();
       activeTrans = baseTrans;
       baseTrans = nextTrans;

    ... //about 20 more cases for all the different transactions
}

This SEEMS to be a possible candidate for using the Command pattern, since each scanning function has the potential to be a "stack" or transactions to run in sequence, but I'm not sure. The code has been working fine - I only want to try refactoring it a bit because I can foresee the code getting more and more complex as requirements change or are added.


Solution

  • This is a non O-O problem, so looking for an O-O design pattern is inappropriate (at least at this stage of the refactoring). You need a Finite-State-Machine, so design an FSM. If particular piece of your FSM still looks too cumbersome or complex, look for an appropriate O-O design pattern for it.