Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle a syntactically valid but logically invalid argument passed to the constructor?

I need to make a class Expr having public interface like this:

class Expr{
    //...
public:
   Expr(const char*);
   int eval();           //Evaluates the expression and gives the result
   void print();
};

In the design, if user enters an invalid string to construct an Expr object like "123++233+23/45", would it be right to construct the Object initially and notify the error when eval() is called on that object.

Or the error should be checked at that point itself and en exception be thrown, though that would lead to serious increase in runtime. And the user may write code furthur with assumption that Object is created and will discover the error at runtime only..

Such problems arise always in creating a class, is there a rather standard way to handle such errors made at user's part????

like image 967
bhuwansahni Avatar asked Mar 14 '12 08:03

bhuwansahni


2 Answers

The only standard part about how you do this is thorough documentation.

I prefer throwing the errors as early as possible, or using a factory for objects of this type - objects that require specific arguments to be initialized. If you use a factory, you can return a NULL or a nullptr or whatever.

I don't see the point in constructing the object and returning an error only when eval() is called. What's the point? The object is invalid anyway, why wait until you use it?

and an exception be thrown, though that would lead to serious increase in runtime.

Have you profiled this? Don't not use exceptions because you assume increase in runtime.

like image 150
Luchian Grigore Avatar answered Nov 07 '22 17:11

Luchian Grigore


class illogical_expression_exception : public virtual exception {};

class Expr{
    //...
    int result; // store evaluated result.
public:
   explicit Expr(const char*);
   int getResult();           // Evaluate & Parse in the Constructor. 
   void print();
};

/* in constructor */

if ( ! checkExpression(expr) ) throw illogical_expression_exception();

/* in main() */
try{ Expr my_expr("2+2*2"); }
catch(const illogical_expression_exception& e){ 
   cout << "Illogical Expression." << endl; 
}
like image 30
ApprenticeHacker Avatar answered Nov 07 '22 16:11

ApprenticeHacker