Making the code cleaner
c++
Solution
Use something like a `std::vector` of `std::function`. It is a lot more maintenable.
Example: http://ideone.com/0voxRl
// List all the function you want to evaluate
std::vector<std::function<bool()>> functions = {
my_func1,
my_func2,
my_func3,
my_func4
};
// Evaluate all the function returning the number of function that did fail.
unsigned long failure =
std::count_if(functions.begin(), functions.end(),
[](const std::function<bool()>& function) { return !function(); });
If you want to stop when a function fail, you just have to use `std::all_of` instead of `std::count_if`. You dissociate the control flow from the function list and that is, in my opinion, a good thing.
You can improve this by using a map of function with name as key that will allows you to output which function failed:
std::map<std::string, std::function<bool()>> function_map;
Problem
Sorry if this question is not suited for SO. I have a C++ function that approximately looks like MyFun() given below. From this function I am calling some(say around 30) other functions that returns a boolean variable (true means success and false means failure). If any of these functions returns false, I have to return false from MyFun() too. Also, I am not supposed to exit immediately (without calling the remaining functions) if an intermediate function call fails. Currently I am doing this as given below, but feel like there could be a more neat/concise way to handle this. Any suggestion is appreciated. Many Thanks. ``` bool MyFun() // fn that returns false on failure { bool Result = true; if (false == AnotherFn1()) // Another fn that returns false on failure { Result = false; } if (false == AnotherFn2()) // Another fn that returns false on failure { Result = false; } // Repeat this a number of times. . . . if (false == Result) { cout << "Some function call failed"; } return Result; } ```