[pro] Style issue about predicates

Daniel Weinreb dlw at itasoftware.com
Fri Jan 14 16:42:16 UTC 2011


If you have a function that is a predicate, in the sense that
the function's contract says that its value should be interpreted
as being either false or true, do you think it's better to code
it so that it always returns "t" for the true case?

Since Common Lisp is quite clear that when a value
is being considered in the context of being true/false,
nil means false and everything else means true.
So from a language point of view, even considering
the "intent" of the definition and not just the spec,
there is no need to return t.

Furthermore, the contract of the function should
make it clear that the returned value is an a
true/false context.  This should be in the doc
string, or at least in a comment, and the function
name should end in "p" (or always "-p" but let's
please not get into that in this email thread).
So the caller should know.

All that said, it's possible that a programmer will
fail to heed the contract, simply look at the code,
and take advantage of the returned value in
more than true/false context.  If you want to prevent
that, you can do something like:

(defun ...
...
(when (fn1 arg2 arg2)
  t))

It seems that it might depend on the circumstance: how likely
do you think it is that a programmer would commit such
a mistake?  The more potentially valuable the returned value
is, the more likely.  On the other hand, if it's so valuable,
maybe you should actually make that part of the contract
rather than making the function have the contract of
a predicate.

Is this good, bad, don't care, depends on the circumstance?

-- Dan





More information about the pro mailing list