There are many situations where it is necessary to extend certain functionality of an existing class. There may be several specializations of a certain behavior.
Of course, this can be done simply by changing the original class, perhaps by placing a if
for each new situation that arises.
But this is not a good practice from a modeling point of view. The code gets confused and the chance of new errors appear is great.
In an ideal class model you would never need to change an existing class to add a new feature or more specific behavior. Just extend a class.
Although there are several practical examples, not all work out of context. I’ll work with a few below.
Practical example of constructor
Suppose you have the class Pessoa
:
class Pessoa
def initialize(nome)
@nome = validarNome(nome)
end
def validarNome(nome)
...
end
end
And now a specialization PessoaFisica
:
class PessoaFisica < Pessoa
def initialize(nome, cpf)
super(nome)
@cpf = validarCpf(cpf)
end
def validarCpf(cpf)
...
end
end
And one more level of expertise Funcionario
:
class Funcionario < PessoaFisica
def initialize(nome, cpf, pis)
super(nome, cpf)
@pis = validarPis(pis)
end
def validarPis(pis)
...
end
end
In the examples above, the superclass constructor takes care of the validation of the attribute it has.
Subclasses add new attributes and invoke the constructor of the respective superclass by delegating the initialization and validation of inherited attributes.
This is a way to maintain existing functionality, add new features and ensure the correct behavior of the program by reusing what already exists, without duplicating code.
Example of "decorative method"
Imagine you have a class that returns a message:
class GeradorMensagem
def getMensagem
"Olá mundo!"
end
end
Now you need to create a specialization of this message to display on a web page. Could do something like:
class GeradorMensagemHtml < GeradorMensagem
def getMensagem
"<div>" + super + "</div>"
end
end
Example of specialized behavior
Given a class Cliente
thus:
class Cliente
def limiteCredito
#consulta limite de crédito
end
end
There may be a ClienteEspecial
which, in addition to the normal limit, has a special value. The limit would then be the sum of both. Let’s see how this can be implemented with reuse:
class ClienteEspecial < Cliente
def limiteCreditoEspecial
#consulta limite de crédito especial
end
def saldo
limiteCredito + limiteCreditoEspecial
end
end
I worked little with Ruby, but in Java and AS3 a situation that is necessary, when we create a constructor in the class "daughter", we need to run the constructor of the class "father", for example a class (parent) for connection to a database usually opens the connection in the constructor, for the connection to be opened in the daughter class it is necessary to call the
super
. I believe it’s the equivalent in Ruby.– Guilherme Nascimento