Reputation: 11
I have problems with the encapsulation, and I don't where the problem is. Why can the line be altered after it has been created? This tells me something is wrong in my "line-class" and needs to be encapsulated. Advise would be much appreciated.
When calling "pa.X = 4
" and "startpos.Y = 7
" this should not change the line for me, but it does. I expect that all the lines are unchanged when the program has finished.
Dotclass:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dot
{
class Dot
{
private int x;
private int y;
public Dot()
{
this.X = 0;
this.Y = 0;
}
public Dot(int x, int y)
{
this.X = x;
this.Y = y;
}
public int X
{
get
{ return x; }
set { x = value; }
}
public int Y
{
get { return y; }
set { y = value; }
}
}
}
Lineclass:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dot
{
class Line
{
private Dot startdot;
private Dot enddot;
private double length;
public Line(Dot pa, Dot pb)
{
this.startdot = pa;
this.enddot = pb;
}
public double Size()
{
double a = (double)(enddot.X - startdot.X);
double b = (double)(enddot.Y - startdot.Y);
return length = Math.Sqrt(a * a + b * b);
}
public Dot Position()
{
return startdot;
}
}
}
Main:
using System;
namespace Dot
{
class Program
{
public static void Main()
{
Dot pa = new Dot();
Dot pb = new Dot(-10, -10);
Console.WriteLine("Dot pa, position = (" + pa.X + ", " + pa.Y + ")");
Console.WriteLine("Dot pb, position = (" + pb.X + ", " + pb.Y + ")");
Line line = new Line(pa, pb);
Print("Run 1 off line", line);
pa.X = 4;
Print("Run 2 off line", line);
Dot startpos = line.Position();
startpos.Y = 7;
Print("Run 3 off line", line);
}
private static void print(string text, Line line)
{
double length = line.Size();
Dot startPos = line.Position();
Console.WriteLine("\n" + text);
Console.WriteLine("Längd = {0 :f4} length", length);
Console.WriteLine("Position = ({0},{1})", startPos.X, startPos.Y);
Console.ReadLine();
}
}
}
Upvotes: 1
Views: 56
Reputation: 186668
Why can the line be altered after it has been created?
The reason is that class Dot
is a reference type, and you want a value type, struct
:
// please, notice "struct"
public struct Dot {
// you don't need separate fields, but properties
public int X {get; set;}
public int Y {get; set;}
public Dot(int x, int y) {
X = x;
Y = y;
}
}
....
EDIT: I suggest turning public Dot Position()
into property as well:
class Line {
...
public Dot Position {
get {
return startdot;
}
set {
startdot = value;
}
}
}
and so you can "control the angles":
line.Position = new Dot(line.Position.X, 5);
Upvotes: 4