8/31/2023 0 Comments Switch case bahasa cwhich 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. For instance, let's add Kiwi □ to the Fruit enum.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |