Sujet : Re: My hang-up about OOP (snit)
De : rich (at) *nospam* example.invalid (Rich)
Groupes : comp.lang.tclDate : 26. Jun 2024, 23:32:17
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v5i4th$2br31$1@dont-email.me>
References : 1 2 3
User-Agent : tin/2.6.1-20211226 ("Convalmore") (Linux/5.15.139 (x86_64))
Luc <
luc@sep.invalid> wrote:
And how is that better than this:
proc dog {dogname args} {
if {$args == "tail wag"} {return "$dogname Wag, wag"}
if {$args == "tail droop"} {return "$dogname Droop, droop"}
if {$args == "eats food"} {return "$dogname Nom, nom"}
if {$args == "goes to vet"} {return "$dogname Tries to run"}
}
puts [dog fido tail wag]
puts [dog lucky tail droop]
puts [dog charlie eats food]
puts [dog mitts goes to vet]
That will handle multiple dogs pretty well.
One "method," one "if." It's pretty much it, isn't it?
The Tcl 'my' manpage provides a very simple example that should help
illuminate why the 'object' method would be better than your 'dog'
example above.
The 'class' example it gives is (modified slightly below):
% oo::class create c {
variable counter
method count {} {
puts [incr counter]
}
}
::c
This creates a class command 'c' that will create objects. So lets
create two objects, o1 and o2:
% c create o1
::o1
% c create o2
::o2
Now, what we have is two objects, that each have their own "counter"
variable. The 'counter' variable is not shared between them. Watch
this below:
Make o1 count a few times:
% o1 count
1
% o1 count
2
% o1 count
3
% o1 count
4
% o1 count
5
Now, make o2 count for the first time:
% o2 count
1
o2 returns 1, not 6, so its 'counter' variable is separate from the
'counter' variable in o1 (which is presently storing the value '5').
Now make them both count once each again:
% o1 count
6
% o2 count
2
o1 knows it was at 5, and so it returns 6, and o2 knows it was at 1, so
it returns 2.
And, note, this example got this "separation" of data automatically,
from just this little bit of 'code':
% oo::class create c {
variable counter
method count {} {
puts [incr counter]
}
}
As a thought experiment, consider how you'd make your 'dog' proc
'count' (say you have circus dogs that can 'count' ...) and imagine how
to give each of four different dogs their own, independent, counter to
store their current value into.
Then, compare the code you'd need to add to the dog proc to make a
'counting dog' proc with separate counter variables for each dog to the
code necessary to achieve the same result from the counting class
above.