Call me anal but

return NewMouse.LeftButton == ButtonState.Pressed && OldMouse.LeftButton == ButtonState.Released;

on one line doesn't look right and isn't very readable.

If I have a line of code that has multiple logic operators, how should it be formatted?

For example

Should

return statement1 && statement2 && statement3 && statement4

be more like

return statement1 &&
statement2 &&
statement3 &&
statement 4

or do you recommend something else entirely?

Go with whatever seems readable to you.

return a == b && x == y;

Is fine with me. Others might want to see something more like

if (a == b && x == y)
    return true;

return false;

Understand that the logical operation I wrote is exactly the same in both snippets. a == b && x == y . If it evaluates to true in the second snippet, I return true. Same thing in the first snippet, if it evaluates to true, I return true. If it evaluates to false, I return false. It's just that in the first snippet, you're returning the result of the evaluation instead of some redundant (but OK) value post-evaluation.

You could also use extra variables if a line seems to long for you.

bool a = NewMouse.LeftButton == ButtonState.Pressed;
bool b = OldMouse.LeftButton == ButtonState.Released;
return a && b;

As a side remark: never use short meaningless variable names, certainly not in large programs!
In a case like this I believe it is allowed. I used the variables a and b on three lines and nowhere else.

bool a = NewMouse.LeftButton == ButtonState.Pressed;
bool b = OldMouse.LeftButton == ButtonState.Released;
return a && b;

I like the idea of that but it doesn't seem to fit the scenario well for me

public bool IsMouseButtonHit(MouseButtons b)
        {
            switch (b)
            {
                case MouseButtons.Left:
                    return NewMouse.LeftButton == ButtonState.Pressed && OldMouse.LeftButton == ButtonState.Released;
                case MouseButtons.Middle:
                    return NewMouse.MiddleButton == ButtonState.Pressed && OldMouse.MiddleButton == ButtonState.Released;
                case MouseButtons.Right:
                    return NewMouse.RightButton == ButtonState.Pressed && OldMouse.RightButton == ButtonState.Released;
                case MouseButtons.XButton1:
                    return NewMouse.XButton1 == ButtonState.Pressed && OldMouse.XButton1 == ButtonState.Released;
                case MouseButtons.XButton2:
                    return NewMouse.XButton2 == ButtonState.Pressed && OldMouse.XButton2 == ButtonState.Released;
                default:
                    // No recognisable button has been hit, so return false
                    return false;
            }
        }

This is why I wondered if I should put a each conditional statement on a new line?

Edited 6 Years Ago by DaveTran: n/a

This article has been dead for over six months. Start a new discussion instead.