This is a general question on programming style. Let’s say I have an object Line which has some methods and private variables Point point_a_ and Point point_b_. Let’s say that at some point I need to change the position of the two points. What programming style would you prefer between the following cases? They all do the same thing (or should do: I didn’t compile, but seems pretty straightforward).
CASE 1
Class Line {
public:
Line(Point point_a, Point point_b) : point_a_(point_a), point_b_(point_b) {}
void UpdatePoints(Point point_a, Point point_b) {
point_a_ = point_a; point_b_ = point_b;
}
double Distance();
private:
Point point_a_;
Point point_b_;
};
int main (int argc, char * const argv[]) {
Point point_a(0,0,0);
Point point_b(1,1,1);
Line line(point_a,point_b);
std::cout<<line.Distance()<<"\n";
point_a.x = 1;
line.UpdatePoints(point_a,point_b);
std::cout<<line.Distance()<<"\n";
}
CASE 2
Class Line {
public:
Line(Point point_a, Point point_b) : point_a_(point_a), point_b_(point_b) {}
Point& point_a() { return point_a_; }
Point& point_b() { return point_b_; }
double Distance();
private:
Point point_a_;
Point point_b_;
};
int main (int argc, char * const argv[]) {
Point point_a(0,0,0);
Point point_b(1,1,1);
Line line(point_a,point_b);
std::cout<<line.Distance()<<"\n";
line.point_a().x = 1;
std::cout<<line.Distance()<<"\n";
}
CASE 3
Class Line {
public:
Line(Point* point_a, Point* point_b) : point_a_(point_a), point_b_(point_b) {}
double Distance();
private:
Point* point_a_;
Point* point_b_;
};
int main (int argc, char * const argv[]) {
Point point_a(0,0,0);
Point point_b(1,1,1);
Line line(&point_a,&point_b);
std::cout<<line.Distance()<<"\n";
point_a.x = 1;
std::cout<<line.Distance()<<"\n";
}
Any feedback is greatly appreciated!!
Thanks!
[EDIT] Speed is paramount in my software!
In this simple scenario I might just use public member variables.
Otherwise I would provide getters that return a const reference and matching setters.