Skip to content
Advertisement

Is there a way to make this switch statement smaller and more professional?

I am working to make a Advent Calendar for Christmas and needed to use a switch statement. My biggest dilemma is the fact that each (daysAway) case opens a new class designed for that day in particular. I am working off of what Google and Stack overflow can provide. I was wondering if there was any other way to compact this?

JavaScript

I know it is a giant mess and that is what I am trying to fix! I appreciate any feedback you can give!

Advertisement

Answer

  1. Use Java 14 switch expression syntax:

    JavaScript
  2. Since the code is very simple, just collapse it on one line:

    JavaScript
  3. Use an array of Java 8 method references (notice reversed order):

    JavaScript
    JavaScript
  4. Since you said that “each (daysAway) case opens a new class designed for that day”, use an interface (e.g. Runnable) and an array of class literals:

    JavaScript
    JavaScript
  5. You can also build the class name dynamically (no array or switch statement):

    JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement