Manually setting object's position or have the object do it all?
I'm stuck thinking about the best way to go about setting a line segment's position, I have a class Line(length, angle, previous) being called from a class Polygon.. Right now I have:
public class Line extends Sprite {
public function Line(length:Number, angle:Number, previous:Line = null) {
if (previous != null) {
this.x = previous.end.x;
this.y = previous.end.y;
} else {
this.x = 0;
this.y = 0;
}
/**/
}
}
Now, is this the best practice or should I be doing:
Polygon.addLine(length:Number, angle:Number):void {
var previous = (_line.length == 0) ? null : _line[_line.length - 1]; // Array containing all Lines
var line:Line = new Li开发者_运维百科ne(length, angle, previous);
line.x = (_line.length == 0) ? 0 : previous.end.x;
line.y = (_line.length == 0) ? 0 : previous.end.y;
/**/
}
One thing to add, Line is only used by Polygon in this application.
Edit: Completely rewrote my answer based on your comments...
Ok, so you always have a Line
class and the question is where to put the logic to add a line to a polygon.
Your Line
CTor assumes that there is an optional predecessor Line
object. If you change that so the CTor takes an optional Point
, there will be less coupling. Other classes, that might come in the future, can also construct lines using a starting point, length and angle. So the CTor approach looks good from that perspective.
Also, a polygon is basically a bunch of connected lines (and arcs as your comment suggests) so the logic for calculating the end point of a line seems to really belong into the Line
class. Again, this way possible other users of Line
won't have to duplicate Polygon
's code.
As already mentioned, there is a third way:
You can for example create a LineFactory
class that creates a Line
object based on start point, length and angle. That factory function would then do the calculation and set the start and in the end set end points of the line.
精彩评论