Commit 38aae031a41d7bda93d5fddcf7f3d61243ad510e

[pt_BR] done with 5.6; added dirty workaround for accents in st's comments explicitly calling \textit.

Commit diff

PortugueseBook/Model/Model.tex

 
8080
8181\begin{code}{@TEST}
82823 + 4 --> 7 "envia '+ 4' para 3, resultando em 7"
8320 factorial --> 2432902008176640000 "envia factorial, resultando em um numero grande"
8320 factorial --> 2432902008176640000 !\textit{"envia factorial, resultando em um número grande"}!
8484\end{code}
85%FIXME: "numero" sem acento! sessão "code" não aceita unicode ou 'latex escapes'
8685%FIXME: word wrapping da última frase está ruim
8786
8887A representação de \ct{20 factorial} certamente é diferente da representação de \ct{7}, mas porque ambos
172172\needlines{7}
173173\begin{method}[dist:]{a distância entre dois pontos}
174174Point>>>dist: aPoint
175 "Responde a distancia entre aPoint e o receptor."
175 !\textit{"Responde a distância entre aPoint e o receptor."}!
176176 | dx dy |
177177 dx := aPoint x - x.
178178 dy := aPoint y - y.
182182\begin{code}{@TEST}
1831831@1 dist: 4@5 --> 5.0
184184\end{code}
185%FIXME: "distancia" sem acento! sessão "code" não aceita unicode ou 'latex escapes'
186185
187186O motivo principal para preferir encapsulamento baseado em instância ao invés de encapsulamento
188187baseado em classe é que a primeira permite a coexistência de implementações diferentes da mesma abstração.
251251
252252\needlines{5}
253253\begin{code}{@TEST | aColor |}
254aColor := Color blue. "Metodo blue no lado da classe"
254aColor := Color blue. !\textit{"Método blue no lado da classe"}!
255255aColor --> Color blue
256aColor red --> 0.0 "Metodo de acesso red, no lado da instancia"
257aColor blue --> 1.0 "Metodo de acesso blue, no lado da instancia"
256aColor red --> 0.0 !\textit{"Método de acesso red, no lado da instância"}!
257aColor blue --> 1.0 !\textit{"Método de acesso blue, no lado da instância"}!
258258\end{code}
259%FIXME: termos sem acento! sessão "code" não aceita unicode ou 'latex escapes'
260259
261260Você define uma classe preenchendo o modelo oferecido no \subind{system browser}{lado da instância}.
262261Quando você aceita este modelo, o sistema cria não só a classe que você definiu, como também
508508
509509\begin{method}[MagnitudeLessThan]{\ct{Magnitude>>><}}
510510Magnitude>>>< aMagnitude
511 "Responde se o receptor e menor que o argumento."
511 !\textit{"Responde se o receptor é menor que o argumento."}!
512512 ^self subclassResponsibility
513513\end{method}
514%FIXME: comentário sem acento (... receptor é ...)
515514
516515\noindent
517516Em contraste, o método \mthind{Magnitude}{>=} é concreto; ele é definido em termos de \ct{<}:
518517
519518\begin{method}[Magnitude>=]{\ct{Magnitude>>>>=}}
520519>= aMagnitude
521 "Responde se o receptor e maior ou igual ao argumento."
520 !\textit{"Responde se o receptor é maior ou igual ao argumento."}!
522521 ^(self < aMagnitude) not
523522\end{method}
524%FIXME: comentário sem acento (... receptor é ...)
525523O mesmo é verdadeiro para outros métodos de comparação.
526524
527525A classe \clsind{Character} é uma subclasse de \ct{Magnitude}; ela sobreescrever o método
529529
530530\begin{method}[CharacterLessThan]{\ct{Character>>><}}
531531Character>>>< aCharacter
532 "Responde true se o valor do receptor < o valor de aCharacter."
532 !\textit{"Responde true se valor do receptor < valor de aCharacter."}!
533533 ^self asciiValue < aCharacter asciiValue
534534\end{method}
535%FIXME: comentário sem acento (... receptor é ...)
536535
537536%---------------------------------------------------------
538537\subsection{Traits}
629629Uma vez que diferentes objetos podem ter métodos diferentes para responder à mesma mensagem,
630630o método deve ser escolhido \emph{dinamicamente}, quando a mensagem é recebida.
631631\begin{code}{@TEST}
6323 + 4 --> 7 "envia a mensagem + com argumento 4 para o inteiro 3"
633(1@2) + 4 --> 5@6 "envia a mensagem + com argumento 4 para o ponto (1@2)"
6323 + 4 --> 7 "envia a mensagem + com argumento 4 para o inteiro 3"
633(1@2) + 4 --> 5@6 "envia a mensagem + com argumento 4 para o ponto 1@2"
634634\end{code}
635635\noindent
636636Como conseqüência, nós podemos enviar a \emph{mesma mensagem} para diferentes objetos, cada qual
725725
726726\begin{method}[defaultColor]{Um método implementado localmente}
727727EllipseMorph>>>defaultColor
728 "responde o estilo de cor/preenchimento padrao para o receptor"
728 !\textit{"responde o estilo de cor/preenchimento padrão do receptor"}!
729729 ^ Color yellow
730730\end{method}
731%FIXME: "padrao" sem acento
732731\cmindex{EllipseMorph}{defaultColor}
733732
734733Em contraste, se nós enviarmos a mensagem \ct{openInWorld} para \ct{anEllipse}, o método não
737737
738738\begin{method}[openInWorld]{Um método herdado}
739739Morph>>>openInWorld
740 "Adiciona este morph ao mundo. Se em um MVC, entao oferece uma Morphic window para ele."
740 !\textit{"Adiciona este morph ao mundo. Se em um MVC, então oferece uma Morphic window para ele."}!
741741 self couldOpenInMorphic
742742 ifTrue: [self openInWorld: self currentWorld]
743743 ifFalse: [self openInMVC]
744744\end{method}
745%FIXME: "entao" sem acento
746745\cmindex{Morph}{openInWorld}
747746
748747\begin{figure}[htb]
754754\end{figure}
755755
756756%---------------------------------------------------------
757\subsection{Returning self}
757\subsection{Retornando si mesmo}
758758
759Notice that \ct{EllipseMorph>>>defaultColor} (\mthref{defaultColor}) explicitly returns \ct{Color yellow} whereas \ct{Morph>>>openInWorld} (\mthref{openInWorld}) does not appear to return anything.
759Note que \ct{EllipseMorph>>>defaultColor} (\mthref{defaultColor}) retorna explicitamente
760\ct{Color yellow} onde \ct{Morph>>>openInWorld} (\mthref{openInWorld})
761não parece retornar qualquer valor.
760762
761Actually a method \emph{always} answers a message with a value\,---\,which is, of course, an object.
762The answer may be defined by the \ct{^} construct in the method, but if execution reaches the end of the method without executing a \ct{^}, the method still answers a value: it answers the object that received the message.
763We usually say that the method ``answers \self'', because in Smalltalk the pseudo-variable \self represents the receiver of the message, rather like \ct{this} in \ind{Java}.
764\index{variable!pseudo}
765\index{return}
766\seeindex{caret}{return}
763Na verdade, um método \emph{sempre} responde à uma mensagem com um valor\,---\,que é, obviamente, um objeto.
764A resposta pode ser definida pelo operador \ct{^} dentro do método, mas se a execução chegar ao
765fim do método sem executar um \ct{^}, o método ainda assim retorna um valor: o objeto que recebeu
766a mensagem é retornado.
767Nós, em geral, dizemos que o método ``retorna \self'', porque em \st a pseudo-variável \self representa
768o receptor da mensagem, tal qual \ct{this} em \ind{Java}.
769\index{variável!pseudo}
770\index{retorno}
771\seeindex{circunflexo}{retorno}
767772
768This suggests that \mthref{openInWorld} is equivalent to \mthref{openInWorldReturnSelf}:
773Isto sugere que \mthref{openInWorld} é equivalente à \mthref{openInWorldReturnSelf}:
769774
770775\needlines{5}
771\begin{method}[openInWorldReturnSelf]{Explicitly returning self}
776\begin{method}[openInWorldReturnSelf]{Retornando self explicitamente}
772777Morph>>>openInWorld
773 "Add this morph to the world. If in MVC,
774 then provide a Morphic window for it."
778 !\textit{"Adiciona este morph no mundo. Se em um MVC,
779 então oferece um Morphic window para ele."}!
775780 self couldOpenInMorphic
776781 ifTrue: [self openInWorld: self currentWorld]
777782 ifFalse: [self openInMVC].
778 ^ self "Don't do this unless you mean it!"
783 ^ self !\textit{"Não faça isso, a não ser que voce realmente queira!"}!
779784\end{method}
785Por que não é bom escrever \ct{^ self} explicitamente?
786Bem, quando você retorna algo explicitamente, você está comunicando que o retorno é de interesse ao remetente.
787Quando você explicitamente retorna \self, você está dizendo que espera que o remetente use o objeto retornado.
788Este não é o caso aqui, portanto, é melhor não retornar \self explicitamente.
780789
781Why is writing \ct{^ self} explicitly not a good thing to do?
782Well, when you return something explicitly, you are communicating that you are returning something of interest to the sender.
783When you explicitly return \self, you are saying that you expect the sender to use the returned value.
784This is not the case here, so it is best not to explicitly return \self.
785
786This is a common idiom in \st, which Kent Beck refers to as ``Interesting return value'' \cite{Beck97a}:
790Este é um idioma comum em \st, que Kent Beck chama de ``Valor de retorno interessante \footnote{``\emph{Interesting return value}''}'' \cite{Beck97a}:
787791\index{Beck, Kent}
788792
789\important{Return a value only when you intend for the sender to use the value.}
793\important{Retorne um valor somente quando sua intenção é que o remetente use-o.}
790794
791795%---------------------------------------------------------
792\subsection{Overriding and extension}
793
794If we look again at the \ct{EllipseMorph} class hierarchy in \figref{openInWorldLookup}, we see that the classes \ct{Morph} and \mbox{\ct{EllipseMorph}} both implement \ct{defaultColor}.
795In fact, if we open a new morph (\ct{Morph new openInWorld}) we see that we get a blue morph, whereas an ellipse will be yellow by default.
796\index{method!overriding}
797\index{method!extension}
798\seeindex{overriding}{method, overriding}
799\seeindex{extension}{method, extension}
800
801We say that \ct{EllipseMorph} \emph{overrides} the \ct{defaultColor} method that it inherits from \ct{Morph}.
802The inherited method no longer exists from the point of view of \ct{anEllipse}.
803
804Sometimes we do not want to override inherited methods, but rather \emph{extend} them with some new functionality, that is, we would like to be able to invoke the overridden method \emph{in addition to} the new functionality we are defining in the subclass.
805In \st, as in many object-oriented languages that support single inheritance, this can be done with the help of \super sends.
806
807The most important application of this mechanism is in the \ct{initialize} method.
808Whenever a new instance of a class is initialized, it is critical to also initialize any inherited instance variables.
809However, the knowledge of how to do this is already captured in the \ct{initialize} methods of each of the superclass in the inheritance chain.
810The subclass has no business even trying to initialize inherited instance variables!
811
812It is therefore good practice whenever implementing an initialize method to send \ct{super initialize} before performing any further \ind{initialization}:
796\subsection{Sobreescrita e extensão}
797
798Se nós olharmos novamente a hierarquia da classe \ct{EllipseMorph} na \figref{openInWorldLookup},
799veremos que as classes \ct{Morph} e \mbox{\ct{EllipseMorph}} implementam \ct{defaultColor}.
800
801De fato, se nós abrirmos um novo morph (\ct{Morph new openInWorld}) nós veremos um morph azul, por outro
802lado, uma elipse será amarela por padrão.
803\index{método!sobreescrevendo}
804\index{método!extensão}
805\seeindex{sobreescrevendo}{método, sobreescrevendo}
806\seeindex{extensão}{método, extensão}
807
808Nós dizemos que \ct{EllipseMorph} \emph{sobreescreve} o método \ct{defaultColor} que é herdado por \ct{Morph}.
809O método herdado não mais existe do ponto de vista do \ct{anEllipse}.
810
811As vezes, nós não queremos sobreescrever métodos herdados, mas sim, \emph{extender} eles com alguma
812funcionalidade nova. Ou seja, nós gostariamos de poder invocar o método sobreescrito \emph{além} da nova
813funcionalidade que estamos definindo na subclasse.
814Em \st, assim como em várias linguagens orientadas à objeto que suportam herança singular, isso pode
815ser feito com a ajuda de \emph{super sends}.
816
817A aplicação mais importante deste mecanismo está no método \ct{initialize}.
818Sempre que uma instância de uma classe é inicializada, inicializar qualquer variável de instância herdada é crítico.
819Porém, o conhecimento de como fazer isso já existe nos métodos \ct{initialize} de cada superclasse
820na cadeia da hierarquia.
821A subclasse não deve sequer tentar inicializar variáveis de instância herdadas!
822
823É, portanto, boa prática enviar \ct{super initialize} antes de processar qualquer \ind{inicialização} posterior
824ao implementar um método \emph{initialize}.
813825\index{super!initialize}
814826
815827\needlines{6}
816828\begin{method}[morphinit]{Super initialize}
817829BorderedMorph>>>initialize
818 "initialize the state of the receiver"
830 "inicializa o estado do receptor"
819831 super initialize.
820832 self borderInitialize
821833\end{method}
822834
823\important{An \ct{initialize} method should always start by sending \ct{super initialize}.}
835\important{Um método \ct{initialize} deve sempre começar enviando \ct{super initialize}.}
824836
825837%---------------------------------------------------------
826\subsection{Self sends and super sends}
838\subsection{\emph{Self sends} e \emph{super sends}}
839
840Nós precisamos de \super \subind{super}{send}{}s para compor o comportamento herdado que
841de outra forma seria sobreescrito. A forma usual de compor métodos, sejam herdados ou não,
842por outro lado, é por meio de \self \subind{self}{send}{}s.
827843
828We need \super \subind{super}{send}{}s to compose inherited behaviour that would otherwise be overridden.
829The usual way to compose methods, whether inherited or not, however, is by means of \self \subind{self}{send}{}s.
844Como \self sends diferem de \super sends?
845Como \self, \super representa o receptor da mensagem.
846A única coisa que muda é a busca do método.
847Ao invés da busca iniciar na classe do receptor, ela inicia na superclasse da classe do método
848onde o \super send acontece.
830849
831How do \self sends differ from \super sends?
832Like \self, \super represents the receiver of the message.
833The only thing that changes is the \ind{method lookup}.
834Instead of lookup starting in the class of the receiver, it starts in the superclass of the class of the method where the \super send occurs.
850Note que \super \emph{não} é a superclasse!
851É um erro comum e natural pensar isso.
852Também, é um erro pensar que a busca do método inicia na superclasse do receptor.
853Nós veremos precisamente como isso funciona no próximo exemplo.
835854
836Note that \super is \emph{not} the superclass!
837It is a common and natural mistake to think this.
838It is also a mistake to think that lookup starts in the superclass of the receiver.
839We shall see with the following example precisely how this works.
855Considere a mensagem \ct{initString}, que nós podemos enviar para qualquer morph:
840856
841Consider the message \ct{initString}, which we can send to any morph:
842857\begin{code}{@TEST | anEllipse | anEllipse := EllipseMorph new.}
843858anEllipse initString --> '(EllipseMorph newBounds: (0@0 corner: 50@40) color: Color yellow) setBorderWidth: 1 borderColor: Color black'
844859\end{code}
845The return value is a string that can be evaluated to recreate the morph.
860O valor de retorno é uma string que pode ser executada para recriar o morph.
846861
847How exactly is this result obtained through a combination of \self and \super sends?
848First, \ct{anEllipse initString} will cause the method \ct{initString} to be found in the class \ct{Morph},
849as shown in \figref{initStringLookup}.
862Como exatamente isso é o resultado obtido por meio da combinação de \self e \super sends?
863Em primeiro lugar, \ct{anEllipse initString} fará com que o método \ct{initString} seja
864encontrado na classe \ct{Morph}, como mostrado na \figref{initStringLookup}.
850865
851866\begin{figure}[htb]
852867\begin{center}
877877Morph>>>initString
878878 ^ String streamContents: [:s | self fullPrintOn: s]
879879\end{method}
880The method \cmind{Morph}{initString} performs a \self send of \ct{fullPrintOn:}.
881This causes a second lookup to take place, starting in the class \ct{EllipseMorph}, and finding \mthind{BorderedMorph}{fullPrintOn:} in \ct{BorderedMorph} (see \figref{initStringLookup} once again).
882What is critical to notice is that the \self send causes the method lookup to start again in the class of the receiver, namely the class of \ct{anEllipse}.
880O método \cmind{Morph}{initString} executa um \self send de \ct{fullPrintOn:}.
881Isso faz com que uma segunda busca de método aconteça, iniciando na classe \ct{EllipseMorph},
882e encontrando \mthind{BorderedMorph}{fullPrintOn:} em \ct{BorderedMorph}
883(veja a \figref{initStringLookup} novamente).
884O que é importante notar é que o \self send faz com que a busca do método inicie novamente na
885classe do receptor, ou seja, na classe do objeto \ct{anEllipse}.
883886
884\important{A \self send triggers a \emph{dynamic} method lookup starting in the class of the receiver.}
887\important{Um \self send ativa uma busca de método \emph{dinâmica} iniciando na classe do receptor.}
885888
886889\needlines{4}
887\begin{method}[fullPrintOn]{Combining \super and \self sends}
890\begin{method}[fullPrintOn]{Combinando \super e \self sends}
888891BorderedMorph>>>fullPrintOn: aStream
889892 aStream nextPutAll: '('.
890893 !\textbf{super fullPrintOn: aStream.}!
891894 aStream nextPutAll: ') setBorderWidth: '; print: borderWidth;
892895 nextPutAll: ' borderColor: ' , (self colorString: borderColor)
893896\end{method}
894At this point, \ct{BorderedMorph>>>fullPrintOn:} does a \super send to extend the
895\ct{fullPrintOn:} behaviour it inherits from its superclass.
896Because this is a \super send, the lookup now starts in the superclass of the class where the \super send occurs, namely in \ct{Morph}.
897We then immediately find and evaluate \ct{Morph>>>fullPrintOn:}.
897Neste ponto, \ct{BorderedMorph>>>fullPrintOn:} faz um \super send para extender
898o comportamento de \ct{fullPrintOn:} herdado de sua superclasse.
899Uma vez que isso é um \super send, a busca do método inicia na superclasse da classe onde
900o \super send acontece, ou seja, em \ct{Morph}.
901Nós, então, encontramos e executamos imediatamente \ct{Morph>>>fullPrintOn:}.
898902
899Note that the \super lookup did not start in the superclass of the receiver.
900This would have caused lookup to start from \ct{BorderedMorph}, resulting in an infinite loop!
903Note que a busca do método em \super não iniciou na superclasse do receptor.
904Isso faria com que a busca do método iniciasse em \ct{BorderedMorph}, resultando em um \emph{loop}
905infinito!
901906
902\important{A \super send triggers a \emph{static} method lookup starting in the superclass of the class of the method performing the \super send.}
907\important{Um \super send ativa uma busca de método \emph{estática} iniciando na superclasse da classe do método executando o \super send.}
903908
904If you think carefully about \super send and \figref{initStringLookup}, you will realize that \super bindings are static: all that matters is the class in which the text of the \super send is found.
905By contrast, the meaning of \self is dynamic: it always represents the receiver of the currently executing message. This means that \emph{all} messages sent to \self are looked-up by starting in the receiver's class.
909Se você pensar cuidadosamente sobre o \super send e a \figref{initStringLookup}, você verá que
910a ligação das chamadas de métodos \super são estáticas: tudo o que importa é a classe na qual
911o texto do \super send é encontrado.
912Em contraste, o significado de \self é dinâmico: ele sempre representa o receptor da mensagem sendo executada.
913Isso significa que \emph{todas} as mensagens enviadas a \self são buscadas iniciando na classe do receptor.
906914
907915%---------------------------------------------------------
908\subsection{Message not understood}
916\subsection{Mensagem não entendida}
909917
910What happens if the method we are looking for is not found?
911\index{message!not understood}
918O que acontece se um método que nós buscamos não for encontrado?
919\index{mensagem!not understood} %FIXME: deixa "not understood" mesmo?
912920
913Suppose we send the message \ct{foo} to our ellipse.
914First the normal method lookup would go through the inheritance chain all the way up to \clsind{Object} (or rather \clsind{ProtoObject}) looking for this method.
915When this method is not found, the \ind{virtual machine} will cause the object to send \ct{self doesNotUnderstand: #foo}.
916(See \figref{fooNotFound}.)
921Suponha que nós enviemos a mensagem \ct{foo} para nossa elipse.
922Primeiro, a busca de método iria percorrer normalmente a cadeia de herança completamente até a classe
923\clsind{Object} (ou melhor, \clsind{ProtoObject}) procurando por este método.
924Quando ele não for encontrado, a \ind{máquina virtual} fará com que o objeto envie \ct{self doesNotUnderstand: #foo}.
925(Veja a \figref{fooNotFound}.)
917926
918927\begin{figure}[htb]
919928\begin{center}
920929\ifluluelse
921930 {\includegraphics[width=\textwidth]{fooNotFound}}
922931 {\includegraphics[width=0.8\textwidth]{fooNotFound}}
923\caption{Message \lct{foo} is not understood\label{fig:fooNotFound}}
932\caption{Mensagem \lct{foo} não é entendida\label{fig:fooNotFound}}
924933\end{center}
925934\end{figure}
926935
927Now, this is a perfectly ordinary, dynamic message send, so the lookup starts again from the class \ct{EllipseMorph}, but this time searching for the method \ct{doesNotUnderstand:}.
928As it turns out, \ct{Object} implements \ct{doesNotUnderstand:}.
929This method will create a new \ct{MessageNotUnderstood} object which is capable of starting a Debugger in the current execution context.
930
931Why do we take this convoluted path to handle such an obvious error?
932Well, this offers developers an easy way to intercept such errors and take alternative action.
933One could easily override the method \mthind{Object}{doesNotUnderstand:} in any subclass of \ct{Object} and provide a different way of handling the error.
934
935In fact, this can be an easy way to implement automatic delegation of messages from one object to another.
936A \ct{Delegator} object could simply delegate all messages it does not understand to another object whose responsibility it is to handle them, or raise an error itself!
936Agora, isso é uma mensagem dinâmica perfeitamente normal como todas as outras. Portanto, a busca
937de método inicia novamente a partir da classe \ct{EllipseMorph}, mas desta vez, procurando pelo
938método \ct{doesNotUnderstand:}.
939Acontece que \ct{Object} implementa \ct{doesNotUnderstand:}.
940Este método irá criar um novo objeto \ct{MessageNotUnderstood} que é capaz de iniciar um \emph{Debugger}
941%FIXME: depurador??
942no contexto de execução atual.
943
944Por que nós tomamos este caminho tortuoso para lidar com um erro tão óbvio?
945Bem, isso oferece aos desenvolvedores uma forma fácil de interceptar tais erros e definir ações alternativas.
946Pode-se facilmente sobreescrever o método \mthind{Object}{doesNotUnderstand:} em qualquer
947subclasse de \ct{Object} e oferecer uma forma diferente de lidar com este erro.
948
949De fato, esta pode ser uma maneira fácil de implementar delegação automática de mensagens de um objeto
950para outro. Um objeto \ct{Delegator} poderia simplesmente delegar todas as mensagens que ele não entende
951para outro objeto cuja responsabilidade é lidar com eles, ou ele mesmo ativar um erro!
937952
938953%=========================================================
939954\section{Shared variables}
toggle raw diff