I have a Cube class. The cube can be constrained so that the width=height=length
. I've coded this functionality but as you can see, my code results in a circular/infinite loop - the width sets the height which sets the width which sets the height and so on
.
How can I make my Cube class constrained and avoid this infinite loop? Is my only solution to use a boolean variable propagate
(see below)?
public class Cube {
public bool isConstrained {get; set;} // if constrained then width=height=length
// Causes a circular problem. How can I avoid this? Maybe create a variable private bool propagate = false; ??
public double width
{
get { return width; }
set
{
width = value;
if (isConstrained)
{
height = value;
length = value;
}
}
}
public double height
{
get { return height; }
set
{
height = value;
if (isConstrained)
{
width = value;
length = value;
}
}
}
public double length
{
get { return length; }
set
{
length = value;
if (isConstrained)
{
height = value;
width = value;
}
}
}
}
My only solution is this:
private bool propagate = true;
public double length
{
get { return length; }
set
{
length = value;
if (isConstrained && propagate)
{
propagate = false;
height = value;
width = value;
propagate = true;
}
}
}
Currently even just your getters will give a stack overflow - you don't have any fields backing your data, because you're not using automatically-implemented properties. Additionally, your properties don't have conventional names, which is definitely worth fixing.
You should just use private fields to back the properties, and set those accordingly within your property setters. That way no property will call another, and all will be well... except for the design being a bit troublesome to start with. (When changing one property changes another, that can be surprising.)
So something like:
private int width;
private int height;
private int length;
private bool constrained;
...
public int Width
{
get { return width; }
set
{
width = value;
if (constrained)
{
height = value;
length = value;
}
}
}
See more on this question at Stackoverflow