Which is better switch statements or separate functions

Rohit Bajaj
Rohit Bajaj used Ask the Experts™
There is a web application where the client side may perform some operations on an entity called process.
So i made an Enum {process_start, process_edit, process_delete, process_complete}

And on each event i send a message to a particular user.

so i have a function like
sendNofication(userId, event) {

switch(event) {
    case process_start :
   case process_delete:

What are the pros and cons of this approach and an alternatives ?
I can think of one
instead of having various switch case statements
I can have functions corresponding to each event like :

Which is the better appraoch.
Any pros and cons one can see...

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Fabrice LambertConsulting
Distinguished Expert 2017
Choice only matter to the amount of statement you'll write within your switch / case.
- Less than 5 lines, keep it.
- More than 5 lines, make functions.

Plus functions can have a stronger meaning than a bunch of lines.
M. TariqApplication Developer
If you are seeing yourself using it in multiple places ,then using function does make more sense then switch/case.
If there are other things to process for each event, besides sending a notification, it might be better to create an 'Event' interface that contains whatever methods you need (e.g. sendNotification(), logProcess()). Then each event type (Start, Edit, Delete, Complete) can have their own class that implements the 'Event' interface. You can then just call sendNotification() on the 'Event' object, not caring what type it is. This would also make it easier to add new event types in the future. It's a little more setup in the beginning, but it's easier than managing multiple switch statements (again, only if this is just one example of multiple switch statements you need). Again, this is totally overkill if you just have the one thing to process.


In the above case where you talk about creating an Event interface..
What to do in the case where processing of each event type requires different data. in that case the parameters of sendNotification() will be different.
What to do in the case where processing of each event type requires different data.

You can try putting the data into an object and figuring it out within the different implementations, or you can have all the possible arguments in the method signature, but nullable, and each method implementation can just look for what it needs. The first option is cleaner, but might be unnecessary if it's only a difference of a couple fields.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial