Kaveh Ahmadi
Kaveh Ahmadi

Reputation: 59

What's the best constructor

Consider we have two classes Line and Point which class Line uses class Point as below:

public class Point {
   private int x;
   private int y;

   public Point(int x, int y) {
      this.x = x;
      this.y = y;
   }
}

and

public Class Line
{
   private Point start;
   private Point end;
   ...
}

I was wondering which of the constructors below is better for class Line due to OOP principles?

public Line(Point start, Point end)
{
   this.start = start;
   this.end = end;
}

or

public Line(int startX, int startY, int endX, int endY)
{
   start = new Point(startX, startY);
   end = new Point(endX, endY);
}

Upvotes: 5

Views: 178

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213271

I think it would be better to create instances of Points and then pass it to constructor, rather than leaving the constructor with one extra bit of work.

So, you should go with the first one. That way, constructor just needs to initialize the reference with the passed one, rather than to create itself.

Upvotes: 2

jonvuri
jonvuri

Reputation: 5930

Definitely the first one. It is higher-level, the intent is clearer, it is more concise, and it is more maintainable with respect to changes to the Point class.

Upvotes: 10

Related Questions