![]() Some could be invisible, or some are in 2D and other in 3D but are still categorised as fruit. which is actually not.įor your example, a fruit could not have a color or a sprite. Or category of things you want to identify. Haha it's ok for "mode" like you have several mode and you switch. ![]() So, how to avoid using switches?īy using polymorphism instead of switches! Look at the following example: ![]() To conclude, switch statement are bad because they are error-prone and they are not maintainable. "Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modifications.". Last but not least, because a switch statement requires us to modify a lot of classes, it violates the Open-Closed Principle from the SOLID principles. We must find an alternative to switch statements. But, the problem is deeper than a simple exception to throw. To make switch statements less error-prone, we can throw an exception when the default statement of a switch is reached. Also, while making the change, it is easy to forget to update one of the switches. But in a larger codebase, it is time-consuming to make the change. In the example, we are forced to modify the class FruitHelper, it is easy. Adding a new value in an enum requires to updates each switch statement in the code. Set break v to (1) endThe structure I described works fine for a contiguous sequence of numbers but for a sparse sequence or for strings, you'd need one more equality test at the end of the binary split which would just narrow you down to a range of options that contained only one value per range, but without adding an explicit ‘=’ test, you couldn't be sure if it was the value you wanted or one that wasn't present.For instance, let's add Kiwi □ to the Fruit enum. Implements “shortcut evaluation”), but using a flag like this has no advantage at all over a plain if/then/else chain and in fact will be slower because it executes all the tests rather than stopping at the first one. Or another way actually to replicate it is like this: I wouldn't code it like that, but if I did, I'd reverse the tests so that the cheaper integer comparison was executed first and the more expensive string compare was only done if the integer test passed (assuming Scratch stops at the first unsuccessful test in an AND sequence,i.e. Turke圓 wrote:If else is really the only way. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |