John Tan
John Tan

Reputation: 1385

Immutability as applied to classes

I have been reading about immutable types, and how that it is not recommended to have a mutable struct.

What if I have a class instead:

public class Vector
{
    public double X, Y;

    public void Rotate(double angle) 
    {
        double x = this.X; double y = this.Y;
        this.X = (float)((Math.Cos(angle) * x) - (Math.Sin(angle) * y)); 
        this.Y = (float)((Math.Sin(angle) * x) + (Math.Cos(angle) * y)); 
    }
}

So this will be called as:

Vector v = new Vector(1,0);
v.rotate(Math.PI / 2.0);

In this case, should I have written like this instead?

public class Vector
{
    public double X, Y;

    public Vector Rotate(double angle) 
    {
        double x = this.X; double y = this.Y;
        return new Vector((float)((Math.Cos(angle) * x) - (Math.Sin(angle) * y)), (float)((Math.Sin(angle) * x) + (Math.Cos(angle) * y)));
    }
}

To be called as:

Vector v = new Vector(1,0);
Vector v2 = v.rotate(Math.PI / 2.0);

Upvotes: 1

Views: 41

Answers (1)

Guffa
Guffa

Reputation: 700352

Yes, an immutable class will return a new instance when you create a new version. That's how all String methods work, for example.

However, you should also make sure that the properties can't be changed from the outside. Also, there is no reason to cast the coordinates down to float when the properties are double:

public class Vector
{

    public double X { get; private set; }
    public double Y { get; private set; }

    public Vector(double x, double y)
    {
        X = x;
        Y = y;
    }

    public Vector Rotate(double angle) 
    {
        double x = this.X; double y = this.Y;
        return new Vector(((Math.Cos(angle) * x) - (Math.Sin(angle) * y)), ((Math.Sin(angle) * x) + (Math.Cos(angle) * y)));
    }
}

Upvotes: 3

Related Questions