As per [Wikipedia], "...a guard is a boolean expression that must evaluate to true if the program execution is to continue in the branch in question...".
So in your first example code, you have a default value that the function will return, "Markdown"
. And you have two guards, that will return "Not supported file type"
or "Plain text"
if those guards are met.
In your second example, you have switched those default and guard values around. You still have guards, but they now handle "happy path" results rather than the error state.
But as that same article mentions, the terms "guard code"/"guard clause"/"guard block" are commonly used to describe a guard that protects against errors, such as an unsupported file type in your example. So by moving the "Not supported file type"
code out of a guard and to the default path, you no longer have a guard clause as you correctly say.
As to what to therefore call it, guard clauses are preconditions, so I'd refer to putting a default value to protect against errors at the end of the function as a postcondition. No guard is needed for that postcondition; it simply mops up a failure at the end.
As an addendum to this, there's two further points about your code examples that others touch on in comments that are worth mentioning here for completion.
Firstly, be aware that your two code examples aren't equivalent as the second version doesn't explicitly handle !Ext
as your first example does. You avoid duplicating tests of Ext
in the second example, but you lose that !Ext
check. Depending on the language, this might affect the behaviour of the code.
Secondly, the Else
's are redundant in your code: you are creating unnecessary branches. So your two examples can be expressed as:
GetFiletype(Ext)
{
if (!Ext || Ext != "txt" && Ext != "md")
Return "Not supported file type"
If (Ext = "txt")
Return "Plain text"
Return "Markdown"
}
GetFiletype(Ext)
{
If (Ext = "txt")
Return "Plain text"
If (Ext = "md")
Return "Markdown"
Return "Not supported file type"
}
It then becomes clearer that the code is just a succession of guards with a default result at the end in each case.
!Ext
(or else the first version is needlessly verbose)Else If
to justIf
, and remove the remainingElse
(and dedent its block). (anelse
is unnecessary when then-part of if-statement ends withreturn
(orbreak
orcontinue
orgoto
)) For another, take the first one and introduce Else for the If that doesn't have one!