Reputation: 638
It's my first class, I am in the right direction ? I ask myself questions mainly on my init() method. Is alright ? I'm not sure… I'm looking for some advice, method…
oo::class create Point {
variable x y z
method init {val} {
lassign $val x y z
}
method x {} {
set x $x
}
method y {} {
set y $y
}
method z {} {
set z $z
}
method formatPoint {} {
set x [format %.4f $x]
set y [format %.4f $y]
set z [format %.4f $z]
}
}
proc distance3D {a b} {
return [expr { \
sqrt(([$a x] - [$b x])**2 \
+ ([$a y] - [$b y])**2 \
+ ([$a z] - [$b z])**2 )}]
}
set P0 [Point new]
set P1 [Point new]
$P0 init {8.2 30 40}
$P1 init {9.5 10 10}
set val [distance3D $P0 $P1]
Upvotes: 0
Views: 140
Reputation: 13252
It would probably be better to have a constructor rather than an init method:
constructor val {
lassign $val x y z
}
set P0 [Point new {8.2 30 40}]
or
constructor args {
lassign $args x y z
}
set P0 [Point new 8.2 30 40]
OOP-wise, a point without coordinates does not make much sense, and you probably don't want to "move" the point by changing the coordinates, so the coordinates should be assigned when creating the point, and the point replaced with a new one if the thing that owns the point moves.
Is it a good idea to change the coordinate values by the formatPoint method? Why not let the coordinates keep their values and provide a formatted access:
method formatPoint {} {
format {%.4f %.4f %.4f} $x $y $z
}
The coordinate access methods are a little bit off. Try
method x {} {
set x
}
instead: the unary form of set returns the value. Or
method x {} {
return $x
}
if you prefer.
The calculation yields the correct result (~36.0789), but note that you don't need to escape line endings within the braces of an expression (since the line endings are already escaped by the braces).
Upvotes: 2