mercredi 23 mars 2016

C# Better way to handle multiple if/else if statements

I have a class that handles incoming over-the-air messages and parses them. Depending on the output of the command, I need to handle some UI modifications such as highlighting labels, adding text to textboxes etc. The first option I was using is:

void IncomingMessageIfStatements(Message msg, Host host)
        {
            byte resp;
            if (ParseMessageOptionOne(msg, out resp))
            {
                // Do some windows form stuff
            }    

            else if (ParseMessageOptionTwo(msg, out resp))
            {
                // Do some windows form stuff
            }

            else if (ParseMessageOptionThree(msg, out resp))
            {
                // Do some windows form stuff
            }
        }

        private bool ParseMessageOptionOne(Message msg, out byte resp)
        {
            throw new NotImplementedException();
        }
        private bool ParseMessageOptionTwo(Message msg, out byte resp)
        {
            throw new NotImplementedException();
        }
        private bool ParseMessageOptionThree(Message msg, out byte resp)
        {
            throw new NotImplementedException();
        }

This works, but I will have more else if statements and it could get ugly. The next way I looked at doing is:

void IncomingMessageSwitchStatements(Message msg, Host host)
        {
            byte resp = 0;
            byte someByte = 0;
            bool output = false;
            switch (someByte)
            {
                case 1:
                    output = ParseMessageOptionOne(msg, out resp);
                    break;
                case 2:
                    output = ParseMessageOptionTwo(msg, out resp);
                    break;
                case 3:
                    output = ParseMessageOptionThree(msg, out resp);
                    break;
                default:
                    //handle exception here
                    break;
            }

            if (output && resp == 0x01)
            {
                UpdateUiFromHere();
            }
        }

        private void UpdateUiFromHere()
        {
            // handle UI updates here
        }

This looks much cleaner and works as intended. But then I started looking at Dictionary<byte, Func<bool>> and thought maybe that was a better approach to solving the handling of multiple conditions incoming (possibly 20).

Any suggestions on the best practice I should go for, given whats needed?

Aucun commentaire:

Enregistrer un commentaire