Got it! This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.nbsp; Note: This appears on each machine/browser from which this site is accessed.
Here is the decision tree code fragment (without the other code).
Note how the code exactly models the decision tree which reflects the specification of the logic to be used.
5. Extra unneeded code
If ch1 is 'y' the (outer) then branch is executed. If ch1 is not 'y' then it must be (and assumed) 'n' (by assumption of the program). Thus, there is no need to check again, as the following fragment does.
This code also gives the impression that in the outer else part, something else might happen. It takes close inspection to see that the code has extra unneeded constraints.
6. Features not covered
One might be tempted to write the following, using conjunctions.
This code is much less clear. Does it cover all the cases. Does it correctly model the tree. And there are 12 operators used rather than the 3 in the decision tree and in the first (and best) code presented.
7. Features not covered
Using else-if parts does not help much.
Have we covered all the cases? Is it correct? Have we missed anything. If not, the last else if could be changed to just an else, making the code even less clear.
8. Compound conditions
It is often better and more clear to use if then else statements rather than logical operations on relational conditions.
If you use logical operations on relational conditions, you should be very familiar with DeMorgan's Laws for negating such expressions.
Make it correct first. And correct in that it models closely the original specification - textual and diagram.
Make it easy to maintain - refactor when necessary.
Never try to make it faster. Rules and reasoning will be covered later.
The ways above, other than the first, are slower, require more operations to execute, and are more difficult to understand and reason about (in terms of correctness).
10. Refactored code
Here is one way to refactor the original code. Make sure you understand how the original can be converted to the following. Note that the inferior code (with 12 operators) are more difficult to refactor. If one did refactor those, one would end up with the original (best) code.
Note: The very last printf of the period also includes the newline "\n" which now appears only once.
Note: There are other ways to remove the remaining redundancy - not covered here.