I am developing key-value database (https://github.com/nmmmnu/HM4)
There I have code like this:
enum class Command{
INFO ,
SAVE ,
RELOAD ,
GET ,
GETX ,
COUNT ,
SUM ,
MIN ,
MAX
};
template<class PROTOCOL, class DB_ADAPTER, class CONNECTION>
class KeyValueWorkerProcessor{
PROTOCOL &protocol_;
DB_ADAPTER &db_;
CONNECTION &buffer_;
public:
KeyValueWorkerProcessor(PROTOCOL &protocol, DB_ADAPTER &db, CONNECTION &buffer) :
protocol_(protocol),
db_(db),
buffer_(buffer){}
auto operator()(Command cmd){
switch(cmd){
case Command::INFO : return do_info();
case Command::SAVE : return do_save();
case Command::RELOAD : return do_reload();
case Command::GET : return do_get();
case Command::GETX : return do_getx();
case Command::COUNT : return do_count();
case Command::SUM : return do_sum();
case Command::MIN : return do_min();
case Command::MAX : return do_max();
default : return err_NotImplemented_();
}
}
// I have lots of these:
WorkerStatus do_info();
WorkerStatus do_save();
WorkerStatus do_reload();
WorkerStatus do_get();
WorkerStatus do_getx();
WorkerStatus do_count();
WorkerStatus do_sum();
WorkerStatus do_min();
WorkerStatus do_max();
};
template<class PROTOCOL, class DB_ADAPTER, class CONNECTION>
auto do_something(PROTOCOL &protocol, DB_ADAPTER &db, CONNECTION &buffer, Command cmd){
using MyKeyValueWorkerProcessor = KeyValueWorkerProcessor<PROTOCOL, DB_ADAPTER, CONNECTION>;
MyKeyValueWorkerProcessor processor{ protocol, db, buffer };
return processor(cmd);
};
To avoid creating lots of functions with same parameters - PROTOCOL
, DB_ADAPTER
and CONNECTION
, I create templated class KeyValueWorkerProcessor
.
This save lots of boilerplate code e.g. else I need to do:
template<class PROTOCOL, class DB_ADAPTER, class CONNECTION>
WorkerStatus do_info(PROTOCOL &protocol, DB_ADAPTER &db, CONNECTION &buffer);
template<class PROTOCOL, class DB_ADAPTER, class CONNECTION>
WorkerStatus do_save(PROTOCOL &protocol, DB_ADAPTER &db, CONNECTION &buffer);
etc.
However now, I have lots of methods in my templated class KeyValueWorkerProcessor
and I definitely do not like that.
Any good way I can refactor this?
I am using C++17.