I'm currently in school studying C++ and on my current project the goal is:
"Use the switch statement to determine the commission. If the sales are less than zero, display the message "The sales cannot be less than 0." If the code is not 1, 2, or 3, display the message "Invalid code" and don't ask the user for a sales amount."
I came up with two different sets of code, I was primarily wondering which one was better for me to turn in. They both work and I know there is more than one way to do this, I was just wondering which one was better and why. TIA
I'm thinking the first one, just because it's 8 lines less of code and there is less repetition. Just need a second opinion I guess. Again TIA.
The main difference is in the way that the user's input is validated. With version 1, the user's input is validated completely separate of of what being validated means.
With version 2, they are mixed together making it harder to upgrade the code in the future --- imagine having to add a more complicated validation, like username and password ? or network authentication...it'd be a mess to have everything mish mashed eh ? XD
soranz said it really well. That's the more precise reason that I preferred it, I just didn't have a good way to say it. Less repetition was the simple concept.
The idea that separate pieces of code handle different things should carry through to classes and functions too. Each class should handle one thing and each function within that class should handle one thing. Another benefit, besides the one that soranz mentioned, is that this can help to you write code that is reusable within other projects, which can be a real time saver.
I appreciate the responses, very informative, exactly what I was looking for. Great points made and I will definitely take it with me to future programs. Will for sure frequent this site at least throughout the remainder of this class.