Using C++, I have a text mode and a GUI mode implemented using FLTK chosen by command line option and I see a lot of redundancy in the codes except for an extra parameter in the GUI case which I need to pass in the main window widget. I’m wondering if there are ways to remove the redundancy? Maybe I have some design issue completely wrong? I’d appreciate the help and please let me know if there are additional information needed. I have thought of using optional parameter, but cannot take a NULL reference.
Here’re a skeleton of the codes that are really similar (Not exact, but should be close enough to see the general structure). There may be some more if/else loops or functions nested before I have the one different call with the extra Window& parameter, but this is basically the structure, which actually continue a few levels down.
Thanks for any help!
int Game::init(){
if (graphics){
std::unique_ptr<Window> window = std::unique_ptr<Window>(new Window(...))
return Fl::run();
} else {
play_game();
return 0;
}
}
void Window::init(Fl_Widget* w, void *uData){
Window* window = (Window*) uData;
Window->game.play_game(window);
//Window has a private game& that is constructed to be equal to the game above.
}
void Game::play_game(){
while(!over()){
foo();
bar();
}
}
void Game::play_game(Window& window){
while(!over()){
foo();
bar(window);
}
}
void Game::bar(){
if(!a()){
b();
} else {
c();
}
}
void Game::bar(Window& window){
if(!a()){
b();
} else {
c(window);
window.redraw();
}
}
A similar but different question deals with how I deal with the static function in FLTK, I have similar code somewhere that is like this:
void Game::c(){
if(check_this()){
do_this();
}
}
void Game::c(Window& window){
Fl::run();
}
static void Window::call_back(Fl_Widget* w, void* uData){
Window* window = (Window *) uData;
if(window->game.check_this()){
window->do_this();
}
}
Parameter is not the way to go. Subclassing
Gameis the way to go. Any method that needs access to the window is virtual and overridden appropriately in the window-specific subclass.