Smalltalk в примерах/Сообщения: различия между версиями

Содержимое удалено Содержимое добавлено
Строка 195:
===Self===
 
Средняя длинна метода в Smalltalk 7 строк, поэтому, для того чтобы объект сделал серьёзную работу, хорошей практикой является разделение работы между несколькими методами (надеюсьподразумевается, тычто вы хочешьстремитесь иметьреализовывать короткие методы). Как вызвать другой метод, определённый в том же объекте? Ответ: объект посылает сообщение самому себе. В Smalltalk есть для этого специальная переменная --- <i>самself</i> --- которая всегда ссылается на объект который вызвал код --- получатель сообщения. Заметьте что <i>самself</i> ссылается на получателя даже когда код был определён в суперклассе класса получателя.
 
MyClass>>processObject: anObject
МойКласс>>обработатьОбъект: аОбъект
self doThisWithObject: anObject.
сам делайЭтоСОбъектом: аОбъект.
self doThatToObject: anObject.
сам делайТоСОбъектом: аОбъект.
 
Если метод нуждается в другом методе для выполнения некоторой работы, пошлите сообщения <i>самself</i>. Фактически, если вы не знаете, какому объекту послать сообщение, хорошим правилом будет послать его <i>самself</i>.
 
<!--
Smalltalk methods average about seven lines, so for an object to do any serious work there's a good chance that you will have split the work into several methods (assuming you want to have short methods). How does a method invoke another method defined on the same object? Answer: the object sends a message to itself. Smalltalk has a special variable for just such use — self — which always refers to the object that is executing the code — the message receiver. Note that self refers to the receiver even if the the code was defined on a superclass of the receiver's class.
Smalltalk methods average about seven lines, so for an object to do any serious work there's a good chance
 
that you will have split the work into several methods (assuming you want to have short methods). How does a
method invoke another method defined on the same object? Answer: the object sends a message to itself.
Smalltalk has a special variable for just such use — self — which always refers to the object that is executing the
code — the message receiver. Note that self refers to the receiver even if the the code was defined on a
superclass of the receiver's class.
MyClass>>processObject: anObject
self doThisWithObject: anObject.
self doThatToObject: anObject.
 
If a method needs to call on a support method to do some work, send the message to self. In fact, a good rule
If a method needs to call on a support method to do some work, send the message to self. In fact, a good rule of thumb is, if you can't figure out what object to send the message to, send it to self.
-->