tags:

views:

87

answers:

3

What do you guys find preferable?

private Point location;

public int LocationX { get { return location.X; } }
public int LocationY { get { return location.Y; } }

or

private Point location;

public Point Location { get { return location; } }

The problem with the second approach is that both X and Y can be mutated by the class' client, which in this case is not something I'd want to. Should I make a wrapper around Point so I can return an immutable Point?

Thanks

A: 

The Law of Demeter doesn't get much love in the .NET world, but if you're worried about mutability it might be a good additional justification for the first option.

marijne
+2  A: 

is that both X and Y can be mutated by the class' client,

If Point is a struct (and it should be) this is not a problem. The client only gets a copy.

What do you guys find preferable?

For a decent, immutable value-type Point, the single property would be fine. \

If this is about System.Drawing.Point, hide it away. A wrapper maybe but what about a complete replacement?

Henk Holterman
+6  A: 

I would prefer the second approach, as the X and Y members are not mutable (Point is a structure, and thus, a value type). That is, you cannot change the location, because you can't modify the X or Y property of the Location property of your class, since Point is a value member. If you want to change that, you'll have to instantiate a new Point instance.

Look at the following example, the compiler will prevent you from changing the X or Y member of the Location property:

class Program
{
    private class MyType
    {
        private readonly Point _location;

        public MyType(Point location)
        {
            _location = location;
        }

        public Point Location
        {
            get
            {
                return _location;
            }
        }
    }

    static void Main( string[] args )
    {
        var someInstance = new MyType (new Point (5, 6));

        someInstance.Location.X = 5; // <- compiler error: cannot modify the expression because it is not a variable.
    }
Frederik Gheysels