Reputation:
I was doing some reading here about creating immutable object in java and I was wondering, is it okay to create a mutable object in certain situations?
For example, let's say we were creating a ping-pong game in C#, obviously, we would have a class that represents a ball, and the two paddles, would you write the ball class like this:
class Ball
{
private readonly int xPosition;
private readonly int yPosition;
private readonly int ballSize;
private readonly string ballColor;
public Ball(int x, int y, int size, string color)
{
this.xPosition=x;
this.yPosition=y;
this.ballSize = size;
this.ballColor = color;
}
public int getX
{
get
{
return this.xPosition;
}
}
//left out rest of implementation.
or like this:
class Ball
{
private int xPosition;
private int yPosition;
private int ballSize;
private string ballColor;
public Ball(int x, int y, int size, string color)
{
this.xPosition=x;
this.yPosition=y;
this.ballSize = size;
this.ballColor = color;
}
public int getX
{
get
{
return this.xPosition;
}
set
{
this.xPosition = value;
}
}
}
}
In a situation where our object(ball) can change position, size(smaller or larger depending on level) and color, wouldn't it be better to provide a setter property? In this case making it mutable makes sense? How would you approach this?
Upvotes: 0
Views: 324
Reputation: 3252
If you are using c#, you do not need to go thru the overhead of creating separate fields to make objects immutable. Instead you can do something like this -
class Ball
{
public Ball ( int x, int y, int size, string color)
{ ... }
public int XPos {get; private set; }
public int YPos {get; private set; }
public int Size {get; private set; }
public string BallColor {get; private set; }
}
This way, you can still write methods in the class to mutate the properties but nothing outside of the class can change their values.
Upvotes: 4