Use virtual functions instead of type checking

This tip submitted by Sajan on 2010-07-06 11:45:52. It has been viewed 18923 times.
Rating of 5.3 with 198 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!