开发者

What is the best way to structure an if statement for two conditions with an action each, and an action for both?

When i have two conditions, with an action for each condition, and an action for both conditions if one is true,

Sometimes I do this

if (cond1 or cond2)
    if (cond1)
        do act 1
    if (cond2)
        do act 2
    do always

Sometimes I d开发者_开发技巧o this

if (cond1)
    do act 1
    do always
if (cond2)
    do act 2
    do always

But I would really like to do this

if (cond1)
    do act 1
or if (cond2)
    do act 2
then
    do always

Does the last method exist in any language, or is there a preferred method for handling this situation?

Thanks.


I would suggest the following:

if (cond1)
    do act 1
if (cond2)
    do act 2
if (cond1 or cond2)
   do always


If you really need this, and it is unwieldy to extract the common things into another function, you could use a macro like this (untested, Common Lisp):

(defmacro cond-any (clauses)
  (let ((any-clause (gensym "any")))
    `(let ((,any-clause nil))
       (cond ,@(mapcar (lambda (clause)
                         (if (eq (first clause) :any-after)
                             (setf any-clause (rest clause))
                             (append clause any-clause)))
                       clauses)))))

This gives you the ability to do this:

(cond-any (:any-after do-always)
          (cond1 do-1)
          (cond2 do-2))

The keyword :any-after then means "if any of the subsequent conditions are true, append this after its then-part".


Prefer something that does not involve duplicate code as much as possible.

This alternative might be the most flexible, with minimal duplication:

var := false

if (cond1)
    do act 1
    var := true

if (cond2)
    do act 2
    var := true

if (var)
    do always

You may find that there are more times that you want var set, or that as time goes by and the number of "ifs" that you want to "do always" grows. This way avoids "complex" and/or statements.


return unless (cond1 or cond2)
if (cond1)
    do_act 1
if (cond2)
    do_act 2
do_always


Multiple If statements lead to more time consumption as each is evaluated separately. To avoid this make use of if else if ladder to reduce time. My suggestion :-

if(cond1 AND cond2)
       do act 1
       do act 2
       do always
else if (cond1 OR cond2)
       if(cond1)
           do act 1
       else
           do act 2 
       do always

In all your solutions, the number of comparisons are a minimum of 2. But in this particular solution, the minimum is 1 . So ideally this should be the best fit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜