I’m trying to handle mouse clicks in an application, but the logic is becoming very confusing because there are many conditionals. For example, I need to know the following:
-if the control key was held down
-if it was the left or the right mouse button
-if it was the middle or the side of the graphics object that was clicked on
-if the graphics object was already selected or not prior to the click
and most likely more conditionals in the future.
At the moment it’s quite confusing trying to write the rules due to the excessive nested conditionals. It’s not too bad; I just feel like there must be a better way.
I’ve read a lot about how to replace nested conditionals with polymorphism, but I can’t figure out whether or not that would apply here.
EDIT: I don’t know if it matters, but I’m using C++.
Here’s an example:
if (leftMouseClick)
{
if (!controlClicked)
{
if (!clickedOnRightOfNote)
{
if (!isAlreadySelected())
{
// stuff
}
else
{
// stuff
}
else
{
if (!isAlreadySelected())
{
// stuff
}
else
{
// stuff
}
and so forth…
Split out the actual doing something from the if tree
Write the simplest most readable version first – then think about how to make it better
Then inside doEditShape() you can handle other special cases