What is the practical applicability of the super word in Ruby?

Asked

Viewed 841 times

7

There are several explanations on the Internet about it. But I still can’t understand what the practical applicability of the word is super in ruby. Okay, I know it’s meant to call the method with the same name in the superclass. Okay. But then, why would I want to do that? I have less than a year of work in the area, so I haven’t seen that word used in practice yet. Could someone give an example or something like?

  • 1

    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.

2 answers

6


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

2

Redefining, overwriting and super

  • Redefining Methods

Redefining one method consists of replacing one method with another. And the original method is simply lost.

Example:

class Rectangle
  def initialize(length, breadth)
    @length = length
    @breadth = breadth
  end

  def perimeter
    2 * (@length + @breadth)
  end

  def area
    @length * @breadth
  end
end

When called the methods area and Perimeter we shall, respectively, 20 and 18.

But if we break class Rectangle defining these same methods but not implementing them:

class Rectangle
  def perimeter
  end

  def area
  end
end

The tests fail.

And because almost all Ruby methods can be redefined, one should be very careful especially with base classes like Object, Array and etc since an unthinkable reset can break the entire Application, so as a general rule:

Never reset methods, especially if these are defined by the language. Even!

  • Overwriting Methods

Overwriting, in the context of a class consists of defining a method in a subclass that already exists in the superclass, without prejudice to affecting its original implementation.

Example:

class MyArray < Array 
  def map
    'in soviet russia...'
  end
end

In the example above we create a subclass Myarray, deriving from Array, and override the method Array map.().

When testing this code, with both objects, we will see that only the behavior of Myarray.map is damaged, leaving the original intact and fully functional.

  • Super Powered

The most common use of inheritance is to override methods of a class for it to do something the most that its counterpart in the superclass, rather than overwriting it altogether to do something else completely (as in the above examples)

This allows us to reuse the behavior that already exists in the superclass and then modify it to suit the needs of the subclass.

Most Object-Oriented languages offer a means for a superscripted method to invoke the method instead. In Ruby this is done through the keyword super.

When using super the method will invoke its counterparty of the same name, but from the context of the superclass.

Example:

class Animal
  def move
    "I can move"
  end
end

class Bird < Animal
  def move
    super + " by flying"
  end
end

puts Animal.new.move
puts Bird.new.move

In the above example we define the behavior of a class Animal which describes how it moves. A bird is also an animal and by deriving the class Bird of Animal we say that all birds also move.

But birds move in a different way, flying, so we change the behavior of Bird. invoking move in the context of the superclass, thus complementing the characteristic of flying birds.

Source: Rubymonk

  • Very good Bruno, very important even the tip about "Never set methods" +1

  • And although it’s something written for Ruby, it’s a rule that I believe is valid for all languages, at least at a high level. If something was designed to do X, don’t make it happen to do X. Derive make XX. Derive restricts you? Adapt

  • I get it, it really makes sense, really should be valid for any language. Maybe it’s worth to merge this the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.