Logo

TODAY I LEARNED

Defining classes using full name vs wrapping them inside modules

In Ruby, we can write classes inside modules. We usually do this to have classes namespaced to the module, so we don't risk two different classes having the same name. This is important since Ruby won't complain about re-defining a class, it would just open it and add new methods to it.

We could write classes using their full name, like this:

class Pokemon::Game::SpecialAttack < Pokemon::Game::Attack
  # ...
end

or, we could wrap the whole thing using modules, like this:

module Pokemon
  module Game
    class SpecialAttack < Attack # Ruby looks for SpecialAttack inside Pokemon::Game automatically!
      # ...
    end
  end
end

Both methods work the same, except the one above can only reference Attack using its whole name. On the other hand, it looks somewhat easier to read than nesting modules inside other modules. Which style do you prefer?

Learned by kevin-perez on Mar 4, 2022

973983 adforcodereview v3 0211021 c02 021121