dimanche 30 août 2015

Design issues and ideas

I have problems with dealing with derived classes that inherit from the same base class.

Supose i have 2 types of songs:

  • songs with lyrics that have: Title, Tags (sad,happy etc), lyrics (one line), writer
  • instrumental song: Title, Tags (same as lyric songs), instrumentals (a string), performer, BPM.

I thought it would be a good idea to implement a base class Song , since Title and Tags are fields that are common to the both types of the songs. Then, implement the class LyricSong and ImplementSong that inherit from Song

The code i wrote:

class Song
{

public:
    Song(std::string title, std::string tags);

    std::string getTitle() const { return this->_title; }
    std::string getTags() const { return this->_tags; }

    // Since i had the need in virtual functions and since all virtual functions have to be 
    // implemented, i used default string and int to be returned.
    virtual std::string getLyrics() const { return std::string(); }
    virtual std::string getLyricsBy() const { return std::string(); }
    virtual std::string getInstruments() const { return std::string(); }
    virtual std::string getPerformer() const { return std::string(); }
    virtual int getBPM() const { return 0; }

    static songContainer readSongsFromFile(std::string songsFileName);

private:
    std::string _title;
    std::string _tags;

};

//---------------------------------------------------------------------------//

class LyricSong : public Song
{

public:
    LyricSong(std::string title, std::string tags, std::string lyrics, std::string lyricsBy);

    std::string getLyrics() const { return this->_lyrics; }
    std::string getLyricsBy() const { return this->_lyricsBy; } 

private:
    std::string _lyrics;
    std::string _lyricsBy;
};

//---------------------------------------------------------------------------//    
class InstrumentalSong : public Song
{

public:
    InstrumentalSong(std::string title, std::string tags,\
                     std::string instruments, std::string performer, int BPM);

    std::string getInstruments() const { return this->_instruments; }
    std::string getPerformer() const { return this->_performer; }
    int getBPM() const { return this->_BPM; }


private:
    std::string _instruments;
    std::string _performer;
    int _BPM;
};

Issues have arised:

  • The code is cumbersome and messy.
  • Every time i'll need to add new song types , it'll force me to modify Song (add more functions and make them virtual - Polymorphic issues).
  • Will there be a way to know what type of Song i work with, in case of iterating over an array of Song pointer that point to various song types?

Are there any common design principles that can help me with this ?

Aucun commentaire:

Enregistrer un commentaire