immutability - C# Immutable Classes and Gaming Objects -


i doing reading here creating immutable object in java , wondering, okay create mutable object in situations?

for example, let's creating ping-pong game in c#, obviously, have class represents ball, , 2 paddles, write ball class 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         {                         {                 return this.xposition;             }         }         //left out rest of implementation. 

or 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         {                         {                 return this.xposition;             }              set             {                 this.xposition = value;             }         }       } } 

in situation our object(ball) can change position, size(smaller or larger depending on level) , color, wouldn't better provide setter property? in case making mutable makes sense? how approach this?

if using c#, not need go thru overhead of creating separate fields make objects immutable. instead can -

    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, can still write methods in class mutate properties nothing outside of class can change values.


Comments