Skip to content
Advertisement

Design pattern to reduce cyclomatic complexity


I have to send invoices to cutomers through the related customer’s API.
Each customer chooses how to be contacted (email, fax, sms…).
My problem is that each time I add a new “contact type” I increase the cyclomatic complexity of my script.
Here is my code :
JavaScript

As you can see the switch statement of InvoiceSender::send is increased each time I add a new “contact type”.
Do you know which design pattern could solve this problem ?

Advertisement

Answer

Create an interface like SendInvoiceInterface with a send and a shouldSend method. Then create 3 implementations:

  • EmailInvoiceSender
  • FaxInvoiceSender
  • SMSInvoiceSender

Next inject these all into your InvoiceSender as an array. Then instead of the switch-case you can loop over all the senders and ‘ask’ them if they shouldSend. If that evaluates to true you can call send on them.

This way the logic stays inside each sender itself instead of the growing switch-case.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement