3

In Clean Code, Uncle Bob states that switch statements almost always break Single Responsibility and Open/Closed Principles. So does this mean that I should rarely (the only case he proposes is when switch is buried in an Abstract Factory to create polymorphic objects) use Switch Statements and therefore Enumerations? This brings the question that are Switch Statements really necessary to have in an OO Language?

Swift language for instance seems to favour enumerations (they can carry data and so on). Minimising their usage would be a major decision. Swift being an OO Language, do the same rules apply?

Pink
  • 521
  • 4
  • 13
  • example, there is no one definite way to do programming. What will you do if not switch? If else madness? and how that will not break any rule? – Lu_ Feb 09 '18 at 07:11
  • 4
    Don't fight the language design because of one author who wrote a book targeted at other languages. – BallpointBen Feb 09 '18 at 07:14
  • 3
    He has a fair point. Each switch case tends to be responsible for a different problem. The main issue I face with enum's is the Open/Closed problem. Whenever I add a case to the enum, I have to refactor every single place that enum is switched. Adding a default case simply hides the problem instead of dissolving it. Plus, he is a credible author and he seems to be targeting all OO Languages. @Lu_ We can usually avoid or minimise if-else with a little bit of thinking. Switch kind of forces us to dispatch all cases from a single source. – Pink Feb 09 '18 at 07:35
  • 2
    This has been discussed before: https://stackoverflow.com/q/4417070, https://stackoverflow.com/q/505454. – Martin R Feb 09 '18 at 07:42
  • Fair enough. Thank you for the links. Although I am not 100% clear, I am clearer :] – Pink Feb 09 '18 at 08:16

0 Answers0