Re: C++ OO design question
indrawati.yahya@gmail.com wrote:
In a recent job interview, the interviewer asked me how I'd design
classes for the following problem: let's consider a hypothetical
firewall, which filters network packets by either IP address, port
number, or both. How should we design the classes to represent these
filters?
My answer was:
class FilterRule
{
public:
virtual bool Accept(const Packet&) const = 0; //Packet is a
representation of a network packet
};
class FilterByIP: public FilterRule { /* members here */ };
class FilterByPort: public FilterRule { /* members here */ };
class Filter
{
public:
bool Accept(const Packet&) const; //returns true if ALL
filterRules Accept() the Packet
private:
std::vector<FilterRule> filterRules;
};
You mean
std::vector< some_smart_pointer<FilterRule> > filterRules;
However, the interviewer said that he preferred this solution instead:
class Filter
{
public:
virtual bool Accept(const Packet&) const = 0;
};
class FilterByIP: public Filter { /* members here */ }
class FilterByPort: public Filter { /* members here */ }
class FilterByIPAndPort: public Filter
{
protected:
FilterByIP ipFilter;
FilterByPort portFilter;
/* other members */
};
I reasoned that with his solution, there may be too many class numbers
if down the road we decide to filter packets by methods other than IP
address and Port, but somehow he was not convinced. Oh well, I didn't
get the job, but this question continues to haunt me to this day. What
do you C++ experts think? Or is there another better solution that I
did not consider? Thank you.
I like your idea of representing a filter just as a vector of filter rules.
If you want to actually reduce that to practice, you could use duck typing
instead of inheritance. E.g.:
typedef bool (sig) (Paket const &)
typedef std::tr1::function<sig> FilterRule;
Now, FilterRule can hold any value that supports
bool operator() ( Paket const & )
In particular, the concrete classes could be:
class IpFilterRule {
...
public:
bool operator() ( Paket const & p ) {
}
};
class PortFilterRule {
...
public:
bool operator() ( Paket const & p ) {
}
};
and a Filter can now easily be represented as a std::vector< FilterRule >.
Note that there is no coupling between the classes. Should there be common
code, one can incorporate that into the classes using private inheritance.
It would be considered an implementation detail.
Also, the client code would use objects of type FilterRule (or IpFilterrule,
etc) instead of FilterRule* (or IpFilterRule*, etc).
Best
Kai-Uwe Bux