Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm creating a model for Math Problems. This contains always two properties, and has a CorrectResult method which returns the addition of the two numbers. The propeties data types can be decimal, int, double, or a Fraction.Here's the UML for fraction:

A fraction contains a numerator and denominator, has a property called decimal where returs (double)Numerator / Denominator. And also I put some operators.

enter image description here

Here is the model for the binary problem.

enter image description here

First, I was thinking in create this class into a generic class. But later I realized that for flexibility later, I will need this situations, I mean Mixed datatypes.

enter image description here enter image description here

I guess I can create interfaces which contains information about the datatypes and the correct method. I'm not sure, I'm a bit lost in this situation.

Can you orient me how can I fix this scenario?

share|improve this question

1 Answer

The obvious OOP answer is to use sub-classes. In the case of types that are currently primitives, you would have to wrap them in another type which you control that also extends from a common base class.

As an example, if you created NumericValue as a base class, BinaryProblem's Number1 and Number2 properties would take NumericValue instead of decimal. You would then have Fraction extend from NumericValue and create a wrapper for decimal that did the same.

An alternative solution is to add implicit operators to your Fraction class. If you had an implicit operator that converts Fraction to decimal, the following code would work just fine:

var  frac = new Fraction {Numerator = 1, Denominator = 2, DecimalValue = 0.5d};
var  dec = 0.25d;
var  binaryProb = new BinaryProblem {Number1 = frac, Number2 = dec};

The problem, of course, is that it ultimately does a type conversion for you, so Number1 on binaryProb would now be a decimal. If that is not a problem, and you really would like to use primitives wherever possible, then this may be preferable.

share|improve this answer
So do you think I'm complicated things? Is preferible to write four clases or only one? – Darf Zon Jan 23 '12 at 23:44
Absolutely preferable to create many small classes with focused responsibility. It eases maintainability and refactorability. See this article: en.wikipedia.org/wiki/Single_responsibility_principle – Lars-Erik Jan 25 '12 at 10:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.