6

Occasionally, I'm confronted with the problem that I have to provide some constructors in order to initialize objects with different sets of data. These sets can be mathematically transformed into each other, for example:

        public Element(int x, int y, int width, int height)
        {
            setValues(width, height, x, y);
        }

        public Element(int RectTop, int RectLeft, int RectRight, int RectBottom)
        {
            setValues(RectRight - RectLeft, Math.Abs(RectBottom - RectTop), RectLeft, -RectTop);
        }

With such an desired overloading, which actually isn't any because of the same signatures, it is probable that the wrong constructor is invoked, e.g. you provide the Rect-Values and the first constructor is invoked. Assuming, we would have different types, we could achieve it by swapping types with good knowledge that this is a bad practice. But that's simply not the case in this easy example with four times int type.

Can you think of some elegant alternatives to achieve the desired behavior that we have the convenience of overloading, but with the same signature?

  • 1
    I don't understand your question. What behavior are you trying to achieve, and what does "logical failure at runtime is hard-wired" mean? What do you consider "elegant?" – Robert Harvey Jun 5 '13 at 17:38
  • 2
    As a wild guess, I think the OP wants two constructors with the same signature - Element(int, int, int, int) where the ints might be top, left, bottom, right or top, left, width, height. – Dan Pichelman Jun 5 '13 at 17:41
  • What exactly is Element supposed to model, besides what is simply a Rectangle? – Alexander - Reinstate Monica Sep 4 '19 at 2:09
  • An elegant alternative would be to switch to Objectice-C or Swift or any other language supporting named arguments. For example in Swift: let elem = Element(top: 0, left: 0, right: 200, bottom: 50) – gnasher729 Sep 5 '19 at 19:39
15
public Element(Point topLeft, Size size)

public Element(Point topLeft, Point bottomRight)

You could also use factory methods

public static Element FromLeftTopWidthSize(int left, int top, int width, int height)

public static Element FromLeftTopRightBottom(int left, int top, int right, int bottom)

Or you can use a fluent interface

Element.Top(10).Left(28).Right(112).Bottom(101);

Element.Top(10).Left(28).Width(102).Height(73);

You can easily use interfaces to force Left after Top, Right or Width after Left, Bottom after Right, and Height after Width. (see below)

Or, you can do the most sensible thing of all and not allow the different choices. Just choose one and stick to it.


Example of a Progressive Fluent Interface:

public class ElementBuilder : ITopSyntax, ILeftSyntax, IRightSyntax, IWidthSyntax
{
    private int _top;
    private int _left;
    private int _right;

    public ElementBuilder(int top)
    {
        _top = top;
    }

    ILeftSyntax ITopSyntax.Left(int left)
    {
        _left = left;
        return this;
    }

    IRightSyntax ILeftSyntax.Right(int right)
    {
        _right = right;
        return this;
    }

    IWidthSyntax ILeftSyntax.Width(int width)
    {
        _right = width + _left;
        return this;
    }

    Element IRightSyntax.Bottom(int bottom)
    {
        return new Element(_left, _top, _right, bottom);
    }

    Element IWidthSyntax.Height(int height)
    {
        return new Element(_left, _top, _right, _top + height);
    }
}

internal interface ILeftSyntax
{
    IRightSyntax Right(int right);
    IWidthSyntax Width(int width);
}

internal interface IRightSyntax
{
    Element Bottom(int bottom);
}

internal interface IWidthSyntax
{
    Element Height(int height);
}

internal interface ITopSyntax
{
    ILeftSyntax Left(int left);
}
| improve this answer | |
  • 6
    Your first suggestion is perfect, +1 for that. Meh on the other suggestions; the factory methods are OK, but the fluent interface doesn't have the same guarantee of consistent object initialization that a constructor does. – Robert Harvey Jun 5 '13 at 17:53
  • @RobertHarvey: It does if the only methods that return an Element are Bottom and Height. – pdr Jun 5 '13 at 17:54
  • 4
    That would be a bit counter-intuitive; it requires hidden knowledge of the fluent interface, and good fluent interfaces don't require a specific method order if such an order is not implied by the methods. – Robert Harvey Jun 5 '13 at 17:56
  • 1
    OK, so I read up on progressive fluent interfaces and builder objects. It's a pretty cool technique, although it seems like a bit of overkill here. – Robert Harvey Jun 5 '13 at 18:12
  • 1
    @RobertHarvey Theoretically, you could design the types so that you can do only the right thing in any order. E.g. Element.Left(10).Right(20) would return something like ElementBuilderWithLeftRight. Though this leads to combinatorial explosion of types, so it's most likely not worth it. – svick Jun 5 '13 at 18:14
2

One way to do it would be to write a constructor that accepts a Rectangle object.

public Element(Rectangle r) { ...

Which you can then call thusly:

var element = new Element(new Rectangle(x, y, width, height));

Of course, now you're back where you started, since Rectangle asks for the very same parameters that your first overload does.

If you're committed to providing a constructor overload for the slight variation in math, you could simply add a boolean flag to make the signature unique. Something like:

public Element(int RectTop, int RectLeft, int RectRight, int RectBottom, bool isRect)

It's a bit of a hack, and it doesn't matter what you pass in to the bool parameter, but it does guarantee that particular overload will be called.

| improve this answer | |
  • 5
    +1 for the rectangle object, but the bool flag is just yuck – jk. Jun 5 '13 at 19:11
  • The bool flag wouldn't be my first choice, either. pdr's solution with point and size is better. – Robert Harvey Jun 5 '13 at 20:13
0

As the accepted answer (pdr) explains, the entities which you are looking for already exist in the framework, so you could easily replace two coordinates with a Point class, or two dimensions with a Size class. And the Factory approach is also a nice solution, but unfortunately that makes inheritance impossible or difficult.

In case you can't find a more appropriate class and need to stick with the primitive types, you can still wrap your primitive types into wrapper classes:

public class Car
{
    //public Car(string make) {...}
    //public Car(string model) {...}
    public Car(Make make) {...}
    public Car(Model model) {...}
}

public class Make
{
    private string Name;
    public Make(string name) { this.Name = name; }
    public override string ToString()
    {
        return this.Name;
    }
}
public class Model
{
    private string Name;
    public Model(string name) { this.Name = name; }
    public override string ToString()
    {
        return this.Name;
    }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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