Use virtual functions instead of type checking

This tip submitted by Sajan on 2010-07-06 11:45:52. It has been viewed 12908 times.
Rating of 8.3 with 97 votes



Use virtual functions as part of interfaces instead of type checking with if-else. Suppose in the scenario of creating a phone object based on type

// Psuedo code only
enum PhType { mobile, land };

if(PhType == mobile)
{
    // Process mobile phone
}
else if(PhType == land)
{
    // Process land phone
}


Above is the structural approach. Instead make use of object-oriented programming

OOPS implementation of the approach

// Psuedo code only
class Phone
{
public:
    virtual void ProcessPhone();
};

class LandPhone : public Phone
{
public: 
    void ProcessPhone();
}

class CellPhone : public Phone
{
    void ProcessPhone();
}

int main ()
{
    Phone *ph = new CellPhone();
    ph->ProcessPhone(); // This will invoke the business logic based on the object type..
}




More tips

Help your fellow programmers! Add a tip!