mercredi 26 août 2020

Replace switch case: interface vs abstract class

I have a code that has a switch statement and want to improve the design.

There's the interface and the the abstract class way.

I want to know which way is better and why ?

I have the following class :

enum MovieChargeType {regular, new_release }

class Movie {
    public MovieChargeType type;
    public double get_price(){
          switch (type){
                  case regular: //return regular price
                  case new_release : // return new_release price }
    } 

}

So I decided to improve the design using 2 ways:

1 Way - Interfaces

Interface MovieType{
    public double get_price();
}

class RegularMovie implements MovieType{
    public double get_price(){
        // return regular price
    }
}

class NewMovie implements MovieType{
    public double get_price(){
        // return new price
    }
}

class Movie{
        public MovieType type;
        public double get_price(){
              type.get_price();
        } 
    
    }

2 Way - abstract classes:

abstract class Movie {
        public MovieChargeType type;
        public abstract double get_price();
    
    }

class RegularMovie extends Movie{
        public double get_price(){
            // return regular price
        }
    }
    
    class NewMovie extends Movie{
        public double get_price(){
            // return new price
        }
    }

I want to know which one is better in such case? I've noticed that people tend to go with interfaces but can someone explain why?

Aucun commentaire:

Enregistrer un commentaire