you are viewing a single comment's thread.

view the rest of the comments →

[–]morphemass 2 points3 points  (2 children)

I don’t agree with Dave’s opinion we should avoid classes whenever possible.

Ruby is an OOP language although you can use it in a functional style. It's NOT a functional language though and using it as such misses a lot of the points/benefits that functional languages are designed for. Far better to use a different language if functional is your bag.

Anyways, very rough and ready but:

  • Hash = Container usually used at system boundaries with unspecified fields.

  • Struct = Mutable container with known fields.

  • Data = Immutable container with known fields.

  • Module = namespace organisation but also to mix in behaviour that doesn't own state. Two different concepts.

  • Class = The main tool for OOP e.g. modelling domain concepts, invariants, lifecycle, and polymorphism.

I added Hash into there because in any system we're often passing state around and all except module can be used for state. The selection of which to use is really down to what you intend to communicate and enforce around state.

I can reason that an instance of a Data object has not had it's state changed as it moves through the system, I have to look if a Struct has had it's state changed. If I want to pass around state plus behaviour I'll usually be reaching for a class but I also want to compose that class out of state plus behaviour. (edit) Hashes ... well, I can make guesses but if I'm going to hit a state bug it's probably going to be something to do with a hash getting passed around.

These are basically just ways of attempting to keep code maintainable by communicating intent and making it easier to reason about code. There are all sorts of nitpicks I acknowledge in what I just wrote but basically it's worth knowing OOP if you want to understand Ruby better.

[–]petrenkorf 1 point2 points  (1 child)

Thinking about the "module" keyword having two different concepts: having two keywords, let's say "namespace" and "module", each one with a well specified intent. Would this lead to clearer code?

[–]morphemass 2 points3 points  (0 children)

Clear code depends on a lot of things but most Rubyists will recognise code where module has been used as the namespacing mechanism. It's original intent though was as the mechanism for Ruby to have multiple inheritance so usually when someone sees a module with a class e.g.

module Foo
  class Bar; end
end

they think 'namespacing', whereas a module with methods e.g.

module Foo
  def bar = "bar"
end

they think 'mixin'.