Wednesday, April 11, 2018

One more case for guard clauses

Another case where guard clauses make the code more readable is when you have to verify some parameter state before applying your logic.

Isolating all the checks in guard clauses right at the beginning of your function makes the logic much clearer.

Example

Using nested conditionals:

 if (file != null && file.isAFile()){
   if (user != null && user.isLogged()){
     if (user.isAdmin()){
       if (page != null && page.isAnInteger && page > 0){
         text = file.read();
         return getPageFromText(text, page);
       } else {
         return "Invalid page."
       }
     } else {
       return "User does not have sufficient privileges."
     }
   } else {
     return "Invalid user."
   }
 } else {
   return "Invalid file.";
 }

Using guard clauses:

 if (file == null || !file.isAFile()){
   return "Invalid file.";
 }
 if (user == null || !user.isLogged()){
   return "Invalid user."
 }
 if (!user.isAdmin()){
   return "User does not have sufficient privileges."
 }
 if (page == null || !page.isAnInteger || page <= 0){
   return "Invalid page."
 }

 text = file.read();
 return getPageFromText(text, page);

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.