| Autor |
Mensagem |
![[Post New]](/templates/default/images/icon_minipost_new.gif) 10/07/2005 23:09:59
|
Operador Nabla
JavaBaby
![[Avatar]](/images/avatar/339a18def9898dd60a634b2ad8fbbd58.png)
Membro desde: 23/02/2004 04:22:27
Mensagens: 98
Offline
|
Ao escrever meus programinhas utilizando OO, sempre tenho a tendência --- ou vício --- de sempre implementar relações de pertinência (ou agregação, se preferirem) entre classes, sem avaliar se uma relação de herança seria mais apropriada.
Que dicas vocês poderiam me dar a respeito? Como eu poderia "julgar" se, na minha aplicação, uma relação de herança entre classes é --- ou não --- mais conveniente que uma relação de pertinência?
This message was edited 2 times. Last update was at 11/07/2005 22:35:25
|
"Vocação: cada um semeie com a sua, colham-se os frutos para todos." |
|
|
 |
|
|
![[Post New]](/templates/default/images/icon_minipost_new.gif) 10/07/2005 23:24:59
|
Mauricio Linhares
Moderador
![[Avatar]](/images/avatar/97af07a14cacba681feacf3012730892.jpg)
Membro desde: 09/01/2005 23:28:22
Mensagens: 3717
Localização: João Pessoa, Paraíba - Brasil
Offline
|
Rapaz, cada caso é um caso diferente, tudo vai sempre depender do contexo, não dá pra dizer que vai ser sempre herança nem vai ser sempre agregação.
|
Meu blog sobre desenvolvimento | My Last.fm | @mauriciojr
Screencast de Introdução a linguagem Objective-C |
|
|
 |
![[Post New]](/templates/default/images/icon_minipost_new.gif) 11/07/2005 02:31:32
|
ZehOliveira
GUJ Ranger
Membro desde: 12/12/2003 22:13:49
Mensagens: 964
Localização: Maceio-AL
Offline
|
Todas as vezes que eu tive que fazer uma escolha dessa, eu juntei o bom senso e as perguntinhas mágicas "é um?" e "tem um?" para resolver a questão.
As duas abordagem são válidas, depende muito do contexto. Mas, em minha opinião, é muito mais fácil estragar um domínio de objetos fazendo mal uso de herança do que usando composição.
This message was edited 2 times. Last update was at 11/07/2005 02:33:24
|
|
|
 |
![[Post New]](/templates/default/images/icon_minipost_new.gif) 13/07/2005 23:22:19
|
Operador Nabla
JavaBaby
![[Avatar]](/images/avatar/339a18def9898dd60a634b2ad8fbbd58.png)
Membro desde: 23/02/2004 04:22:27
Mensagens: 98
Offline
|
Depois de analisar o meu código (e o contexto no qual ele se aplica), decidi optar pela herança, mas agora surgiu outra dúvida.
Digamos que eu tenha duas classes, ClasseA e ClasseB. Na minha cabeça, um objeto ClasseB é um caso particular de um objeto ClasseA e, conseqüentemente, a minha tendência seria fazer ClasseB herdar de ClasseA.
Por outro lado, no que diz respeito ao código, um objeto ClasseB contém menos informação, isto é, menos métodos e atributos, que um objeto ClasseA. Levando isso em conta, talvez fosse melhor fazer ClasseA herdar de ClasseB.
O que eu posso fazer? Quem deve herdar de quem?
PS: Atualmente, no meu código, guardo em ClasseA um atributo que é um objeto ClasseB (relação de agregação). Um método de ClasseA retorna um outro objeto ClasseA, com o mesmo atributo ClasseB do objeto original e com todos os demais atributos nulos.
|
"Vocação: cada um semeie com a sua, colham-se os frutos para todos." |
|
|
 |
![[Post New]](/templates/default/images/icon_minipost_new.gif) 14/07/2005 11:41:41
|
maresp
Virtual Machine Man
![[Avatar]](/images/avatar/c89e78d64107fd0f1188b.jpg)
Membro desde: 28/05/2003 16:27:10
Mensagens: 553
Localização: Indaiatuba/SP
Offline
|
Se vc tem classes que possuem métodos em comum mas que no mundo real não tem relação de herança crie uma interface e faça com que suas classes implemente-a.
|
|
|
 |
![[Post New]](/templates/default/images/icon_minipost_new.gif) 14/07/2005 12:22:14
|
pcalcado
Moderador
![[Avatar]](/images/avatar/110eec23201d80e40d0c4a48954e2ff5.jpg)
Membro desde: 08/03/2004 17:19:35
Mensagens: 5174
Localização: Sydney - Australia
Offline
|
Ola,
Num otimo porem defasado livro, Arthur Riel descreve heuristicas para um projeto OO. Um resumo das heuristicas eh encontrado aqui.
Destas, as que se aplicam ao caso:
Object Oriented Heuristics wrote:
Chapter 5
The Inheritance Relationship
Heuristic #5.1
Inheritance should only be used to model a specialization hierarchy.
Heuristic #5.2
Derived classes must have knowledge of their base class by definition, but
base classes should not know anything about their derived classes.
Heuristic #5.3
All data in a base class should be private, i.e. do not use protected data.
Heuristic #5.4
Theoretically, inheritance hierarchies should be deep, i.e. the deeper the
better.
Heuristic #5.5
Pragmatically, inheritance hierarchies should be no deeper than an average
person can keep in their short term memory. A popular value for this depth is
six.
Heuristic #5.6
All abstract classes must be base classes.
Heuristic #5.7
All base classes should be abstract classes.
Heuristic #5.8
Factor the commonality of data, behavior, and/or interface as high as
possible in the inheritance hierarchy.
Heuristic #5.9
If two or more classes only share common data (no common behavior) then that
common data should be placed in a class which will be contained by each sharing
class.
Heuristic #5.10
If two or more classes have common data and behavior (i.e. methods) then those
classes should each inherit from a common base class which captures those data
and methods.
Heuristic #5.11
If two or more classes only share common interface (i.e. messages, not
methods) then they should inherit from a common base class only if they will be
used polymorphically.
Heuristic #5.12
Explicit case analysis on the type of an object is usually an error, the
designer should use polymorphism in most of these cases.
Heuristic #5.13
Explicit case analysis on the value of an attribute is often an error. The
class should be decomposed into an inheritance hierarchy where each value of
the attribute is transformed into a derived class.
Heuristic #5.14
Do not model the dynamic semantics of a class through the use of the
inheritance relationship. An attempt to model dynamic semantics with a static
semantic relationship will lead to a toggling of types at runtime.
Heuristic #5.15
Do not turn objects of a class into derived classes of the class. Be very
suspicious of any derived class for which there is only one instance.
Heuristic #5.16
If you think you need to create new classes at runtime, take a step back and
realize that what you are trying to create are objects. Now generalize these
objects into a class.
Heuristic #5.17
It should be illegal for a derived class to override a base class method with a
NOP method, i.e. a method which does nothing.
Heuristic #5.18
Do not confuse optional containment with the need for inheritance, modelling
optional containment with inheritance will lead to a proliferation of classes.
Heuristic #5.19
When building an inheritance hierarchy try to construct reusable frameworks
rather than reusable components.
Chapter 6
Multiple Inheritance
Heuristic #6.1
If you have an example of multiple inheritance in your design, assume you have
made a mistake and prove otherwise.
Heuristic #6.2
Whenever there is inheritance in an object-oriented design ask yourself two
questions: 1) Am I a special type of the thing I'm inheriting from? and 2) Is
the thing I'm inheriting from part of me?
Heuristic #6.3
Whenever you have found a multiple inheritance relationship in a
object-oriented design be sure that no base class is actually a derived class
of another base class, i.e. accidental multiple inheritance.
Chapter 7
The Association Relationship
Heuristic #7.1
When given a choice in an object-oriented design between a containment
relationship and an association relationship, choose the containment
relationship.
Note que mesmo Riel deixa bem claro que essas heuristicas sao guias, nao leis. Nao eh preciso seguir 100% delas (e algumas eu realmene nao concordo).
Herança de implementaçao eh util mesmo quando classes nao tem muito em comum (e isso eh um ponto favoravel a herança multipla). Interfaces definem contratos e comortamento esperado, mas muitas vezes voce precisa simplesmente reaproveitar codigo. Nesse caso geralmente um refactoring com Extract SuperClass ajuda.
|
Phillip Calçado "Shoes"
http://fragmental.tw/
http://blog.fragmental.com.br/
"It is unfortunate that much of what is called 'object-oriented programming today is simply old style programming with fancier constructs." - Alan Kay |
|
|
 |
|
|