Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Ruby people say they don't need interfaces?

Does ruby have something different to other OOP languages (eg: PHP) that makes interfaces useless? Does it have some kind of replacement for this?

Edit:

Some clarifications:

  • In other languages (eg: PHP), you don't "need" interfaces (they are not mandatory at code level). You use them to make a contract, to improve the architecture of the software. Therefore, the affirmation 'in ruby you don't need interfaces / in other languages you need interfaces because XXX' is false.

  • No, mixins are not interfaces, they are a complete different thing (PHP 5.4 implements mixins). Have you even used interfaces?

  • Yes, PHP is OOP. Languages evolve, welcome to the present.

like image 463
HappyDeveloper Avatar asked Oct 31 '11 18:10

HappyDeveloper


People also ask

Are there interfaces in Ruby?

Interfaces in Ruby with modulesThe simplest way to emulate interfaces in Ruby is to declare a module with methods that raise a “not implemented” exception. Now, we can use that module to communicate what needs to be implemented on the objects in order to support CSV transformations.

Why does Python not have interfaces?

Python does not have interfaces, but the same functionality can be achieved with the help of abstract base classes and multiple inheritance. The reason for not having interfaces is that Python does not use static typing, so there's no compile-time type checking.


1 Answers

I'm a 'Ruby person', and I would like interfaces, or something like them.

Not to enforce a contract - because enforcing anything isn't very Ruby, and kind of defeats the point of a dynamic language, and anyway there's no "compilation" step to enforce it at - but to document contracts that client subclasses can choose to conform to (or not, although if they choose not to they can't complain if the code doesn't work).

When I'm faced with this problem, ie, when I'm writing a class or module I expect subclasses to provide methods for, I usually document the methods I expect subclasses to provide like this:

module Enumerable
  def each
    raise NotImplementedError, "Subclasses must provide this method"
  end
end

It's not ideal, but it's a reasonably rare case and it works for me.

like image 195
Russell Avatar answered Sep 23 '22 02:09

Russell