Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split big switch statement

Tags:

c++

networking

I'm making an online game and when I receive data from a client, i receive several 'structures' ( say 'my position', 'use potion 23', 'attack player 45', 'talk bla bla', logout, etc.), those structures are read securely and put into structs, pushed on a list and (later on, when the server has time) processed.

The thing is that the processing is a Big switch statement (switch on a sort of enum-"RTTI") and I have over 60 different structs which are all different.

So the .cpp containing the processing code starts to get fairly big and it won't shrink any time as I constantly add functionalities to the game (the c++ is somewhere between 4000-5000 lines).

I can see a simple solution to this, each case calls a function in another file but that will literally (note to harriyott, yes literally as my project and my drive will be flooded with new files) explode the number of files I need to know and keep track of.

I know I can cut it up (the cases) in several fileN.cpp and make '#include "file1.cpp" #include "file2.cpp" etc. in the processing file but that seems horribly wrong. And any other way that I have 'thought up' to circumvent this problem seems way too 'hacky'.

So the question is, how do you split up a big switch statement nicely?

like image 371
Valmond Avatar asked Dec 28 '22 13:12

Valmond


2 Answers

You can

  • replace the switch with a mapping from the enums to handler functions (the function implementations themselves can be in the same file, or in different files, as you prefer), or
  • (the more object oriented solution) make all the structs in question inherit from a common interface declaring a handler method, make each implement the desired functionality in its specific handler method, then call them polymorphically.
like image 186
Péter Török Avatar answered Jan 12 '23 12:01

Péter Török


It seems to me that boost::variant could make your life easier. You build your main event type as a boost::variant of classes and then use static_visitor classes to do your magic. Essentially a switch, but wrapped nicely and type-safely in logic.

like image 44
thiton Avatar answered Jan 12 '23 14:01

thiton