mercredi 3 avril 2019

Design patterns regarding if...else statements

I'm quite new to the field of design patterns and I'm having trouble handling a traditional scenario comprising multiple conditions.

Let's say I have a service (e.g. Printer) which has multiple attributes and depends on different parameters (e.g Department, Documenttype). When I want to verify for a specific parameter combination if an attribute is set correctly, I end up with a lot of if...else conditions.

In pseudo code it would look like this:

class Printer 
{
  AttributeA a;
  AttributeB b;
  AttributeC c;
  ...
  checkAttributeA(Department departement, Documenttype doctype);
  checkAttributeB(Department departement, Documenttype doctype);
  checkAttributeC(Department departement, Documenttype doctype);
  ...
 };

Printer::checkAttributeA(Department departement, Documenttype doctype)
{
  if (department == DepartmentA) 
  {
     if (doctype == DocumenttypeA) 
     {
        // do somthing
     } 
     else if (doctype == DocumenttypeB) {
        // do somthing else
     } 
     ...
  }
 else if (department == DepartmentB) 
  {
     if (doctype == DocumenttypeA) 
     {
        // do somthing
     } 
     else if (doctype == DocumenttypeB) {
        // do somthing else
     } 
     ...
  }
...
}

In case of the strategie pattern, I need to create a class for every condition if I got this correctly. But it not sure if this would be the right way as the number of conditions/classes would grow exponentially with every parameter. Is there a proper way to handle such scenarios?

Aucun commentaire:

Enregistrer un commentaire