Ruby inheritance and delegation

I don't know much about the proper use of inheritance and delegation, so I summarized it.

Inheritance

It is to take over the function from another class and create a new class.

Example

Create a Foo class by inheriting all the methods from the Base class

class Base
  def message
    'ok'
  end
end

class Foo < Base; end
  
foo = Foo.new
puts foo.message
# => ok

transfer

It is to delegate a specific process (responsibility) to a method of another class.

Example

Delegate the message method of the Base class to the Foo class

class Base
  def message
    'ok'
  end
end

require 'forwardable'
class Foo
  extend Forwardable
  attr_reader :mess

  def initialize
    @mess = Base.new
  end
  def_delegator :mess, :message
end
  
foo = Foo.new
puts foo.message
# => ok

Scenes that use inheritance

Same role

Whether you are a fledgling engineer or an experienced Tsuyotsuyo engineer, the role of a programmer is the same. So, let's inherit the Progurammer class and inherit the function as it is.

class Programmer
  def initialize(type, langages)
    @type = type
    @langages = Array(langages)
  end

  def type_is
    puts "I#{type}is."
  end

  def langage_is
    str = ''
    langages.each do |lang|
      str += "#{lang} "
    end
    puts "I#{str}Can handle the language of"
  end

  def klass_is
    str = case self.class.name
    when 'TsuyoTsuyo'
      'Strong engineer'
    when 'Kakedashi'
      'Fledgling engineer'
    end

    puts "I#{str}is."
  end

  private
  attr_accessor :type, :langages
end

class TsuyoTsuyo < Programmer; end

class Kakedashi < Programmer; end

tsuyo = TsuyoTsuyo.new('Backend', %w[C C++ Python Go Ruby])
tsuyo.type_is
tsuyo.langage_is
tsuyo.klass_is

kake = Kakedashi.new('Frontend', %w[HTML CSS jQuery])
kake.type_is
kake.langage_is
kake.klass_is

Scenes using delegation

I want to use some functions although the roles are different

Programmers and designers have different roles. So in this case we will use delegation and only the type_is method will be inherited from the Programmer class.

require 'forwardable'
class Programmer
  def initialize(type, langages)
    @type = type
    @langages = Array(langages)
  end

  def type_is
    puts "I#{type}is."
  end

  private
  attr_accessor :type, :langages
end

class Designer
  extend Forwardable

  def initialize(type, skills)
    @programmer = Programmer.new(type, nil)
    @type = type
    @skills = Array(skills)
  end

  def_delegator :@programmer, :type_is

  private
  attr_accessor :type, :skills
end

class IkeIke < Designer; end

ikeike = IkeIke.new('WebDesigner', %w[HTML CSS Adobe JavaScript])
ikeike.type_is #This type_is method`Programmer`Method inherited from class

Summary

Thank you for reading this far. I hope it will be an opportunity to review my code.

I usually develop web services with Rails, but I don't think there are many occasions to use delegation. It is also true that I used to say "inheritance !!" It is difficult to judge whether the inheritance relationship is good or whether it is better to use delegation, but in the future I decided to implement it including the option of using delegation.

Recommended Posts

Ruby inheritance and delegation
About object-oriented inheritance and about yield Ruby
Ruby Learning # 33 Inheritance
About Ruby inheritance
Ruby and Gem
Inheritance and interface.
[Ruby] Classes and instances
Symbols and Destructive Ruby
[Ruby] Big Decimal and DECIMAL
Ruby classes and instances
About encapsulation and inheritance
Ruby variables and methods
[Ruby] Class nesting, inheritance, and the basics of self
Ruby syntax errors and countermeasures
About Ruby hashes and symbols
Ruby C extension and volatile
Summarize Ruby and Dependency Injection
About Ruby and object model
[Ruby] Singular methods and singular classes
About Ruby classes and instances
Ruby variables and functions (methods)
Ruby methods and classes (basic)
Creating Ruby classes and instances
[Ruby] Singular methods and singular classes
[Ruby] Difference between get and post
Inheritance
[Ruby] present/blank method and postfix if.
[Ruby] Difference between is_a? And instance_of?
Ruby standard input and various methods
About Ruby single quotes and double quotes
[PHP] Inheritance, protected and reference patterns
[Ruby] then keyword and case in
[Ruby basics] split method and to_s method
About Ruby product operator (&) and sum operator (|)
Write keys and values in Ruby
[Ruby] If and else problems-with operators-
[Ruby] Boolean values ​​and logical operators
Project ruby and rails version upgrade
With ruby ● × Game and Othello (basic review)
Upgrade and switch Ruby versions on Windows 10
Note: Difference between Ruby "p" and "puts"
Make bubble sort and selection sort in Ruby
[Ruby] Simplify each using map and inject
[Java] Inheritance and structure of HttpServlet class
Explanation of Ruby Time and Date objects
Let's be lazy with inheritance and override
Memorandum (Ruby: Basic Grammar: Classes and Instances)
ruby Exercise Memo II (variable and method)
[Ruby] Classification and usage of loops in Ruby
Difference between "|| =" and "instance_variable_defined?" In Ruby memoization
[Easy] How to upgrade Ruby and bundler
Comparison of JavaScript objects and Ruby classes
Write code using Ruby classes and instances
[Ruby] Difference between print, puts and p
Differences between Ruby strings and symbols [Beginner]
Convert JSON to TSV and TSV to JSON with Ruby