Is there a language which will support the following concept or is there a pattern to achieve something similar with existing one?
Concept
I want to define a Rectangle
with the following properties: Length
, Height
, Area
, Perimeter
; where Area = Length * Height
and Perimeter = (2 * Length) + (2 * Height)
.
Given the statement above, if I want to create a Rectangle
by giving it a Length
and a Height
, it should of course automatically fill out the rest of the properties.
However, it should go further and automatically allow you to create a Rectangle
with any two properties (say Height
and Perimeter
) because that is also mathematically enough to create the same Rectangle
.
Example
To help explain the idea, take this example:
//Declaration
Rectangle
{
Height, Length, Area, Perimeter;
Area = Height * Length;
Perimeter = (2 * Length) + (2 * Height);
}
//Usage
main()
{
var rectangleA = new Rectangle(Height, Length);
var rectangleB = new Rectangle(Height, Area);
Assert(rectangleA == rectangleB);
}
Notice how I didn't need to define constructors for
Rectangle
. Notice I did not need specify the specific logic needed if aRectangle
was created usingHeight
andArea
.
Edit: Should be rectangle and not a square for a proper example.
What you are looking for is a language with an integrated computer algebra system. It has to be able to resolve equations with respect to different variables.
While it would be possible to implement something like this, I doubt that it would make sense because in many cases there will be either no solution or multiple solutions.
Even your simple example will not work if only area and perimeter are given because there will usually be two solutions. (I assume that your class actually represents a rectangle and not a square, otherwise you should not have separate variables for length and height.)
Example:
Input: area = 2, perimeter = 6
Solution 1: length = 2, height = 1
Solution 2: length = 1, height = 2
Another remark not really related to your question: Your class obviously contains redundant member variables. This is a bad thing for various reasons, the most important being the possibility of inconsistencies. Unless you have very strict performance constraints, you should store only two of them, say length and width, and provide methods to calculate the others when needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With