Course Content
C++ Conditional Statements
C++ Conditional Statements
Guard Clause
As applications become increasingly complex, the potential for bugs and errors also grows. To combat this, developers have turned to various techniques and practices to ensure code quality. One such technique that has gained prominence in recent years is the Clause Guard Technique.
Remember the chapters that discuss the use of nested if
statements? While they are sometimes necessary to ensure correct behavior, there are situations where it's better to avoid them.
For example, we want to create application that will check:
- If user is student;
- If user has premium;
- If user is connected.
If and only if all these requirements are satisfied, produce the output:
Otherwise, log in the console the specific step where the initialization process fails.
You can achieve the desired outcome using nested if
statements, but this approach can make the code hard to understand and difficult to modify when you need to add new conditions. Look at the code snippet.
without_guard_clause
#include <iostream> int main() { // You can change them to false and see how output will change bool isStudent = true; bool isPremium = true; bool isConnected = true; if (isStudent) { if (isPremium) { if (isConnected) { std::cout << "Is student\nIs premium\nIs connected"; } else std::cout << "You don't have premium\n"; } else std::cout << "You are not connected\n"; } else std::cout << "You are not a student\n"; }
To apply the guard clause technique effectively, it's important to remember that we can terminate program execution at any moment by using the return
keyword. In this approach, we reverse our conditions, meaning that if a user is not a student, we immediately display a message and terminate the program. This is done to avoid nested if
tree and unnecessary execution of code when it serves no purpose.
with_guard_clause
#include <iostream> int main() { // You can change them to false and see how output will change bool isStudent = true; bool isPremium = true; bool isConnected = true; if (!isStudent) { std::cout << "You are not a student\n"; return 0; } if (!isPremium) { std::cout << "You don't have premium\n"; return 0; } if (!isConnected) { std::cout << "You are not connected\n"; return 0; } std::cout << "Is student\nHas premium\nIs connected"; }
The Clause Guard Technique is a powerful tool in the arsenal of software developers striving for code reliability, flexibility and safety. By implementing it developers can reduce the amount of errors, improve code maintainability, and enhance overall software quality.
Thanks for your feedback!