This problem has kept me from pursuing a project I'm working on because it influences the entire structure of the application. This question has been briefly touched on here, but I feel that it wasn't seen by many people and therefore wasn't very well answered.
I'm working on an application in charge of navigating and manipulating a binary search tree. This application is controlled through a selection menu, with some options leading to submenus. The most hack-ish approach to this problem is something like this:
int main(int argc, char *argv[])
{
// Create the object using the data in the file at path argv[1].
BinarySearchTree tree(argv[1]);
bool exit = false;
while (!exit) {
// Print the menu out here with std::cout statements.
// This always adds several lines that don't do much.
// Store the users input in a variable here.
// Coding a way that ensures something valid is input adds
// many more lines of clutter.
// If-elseif-else or switch statement here. More complexity with more
// submenus that look exactly like this here. You get how complex
// this will get.
}
}
Anyone who wants to type good code doesn't want their main function to be this long and messy. Breaking it into other functions sitting in my main file doesn't really help much either, it's still messy and not very object-oriented. A possible solution would be to put each menu into their own class like this.
int main(int argc, char *argv[])
{
BinarySearchTree tree(argv[1]);
MainMenu main_menu;
main_menu.run();
}
Definitely the cleanest main method, but not a viable option since my tree object can no longer be accessed from within the MainMenu methods, and I definitely don't want to pass it around endlessly within my class methods since that'd be terrible style. So finally some middle ground I came up with was like this.
int main(int argc, char *argv[])
{
BinarySearchTree tree(argv[1]);
MainMenu main_menu();
bool exit = false;
while (!exit) {
unsigned long prompt = main_menu.prompt();
// The switch statement here. Still a lot of complexity I don't like
// because this can go on for quite a while depending on how deep my
// submenus go or how much I need to do for specific commands.
}
}
Ok, all my sample code is out of the way. I don't like any of them, and I haven't found any truly better solutions on the internet. I'm an undergrad, so I don't have any practical experience in this. Is there some widely accepted best-practice in the industry that I don't know about? How would you approach this personally? Remember, this is being implemented in C++ so I'm trying to be as object-oriented as possible. However, if there's a functional way you know of that works really well that you'd like to share, I'd be open to it.