13
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

株式会社 RetailAI XAdvent Calendar 2022

Day 2

Ruby と Go それぞれで依存性の注入を書く

Last updated at Posted at 2022-12-01

はじめに

これは 株式会社 RetailAI X Advent Calendar 2022 の 2 日目の記事です。

昨日は @kametaro さんの記事でした。 RaftのErlang実装ことはじめ - Qiita

本日は、「 Ruby と Go それぞれで依存性の注入を書く」です。
Ruby の DI の是非は問いません。

環境

Ruby 2.6.1
Go 1.18.2
macOS Monterey ver. 12.3.1 Apple M1

Ruby

😥

class SubmachineA
  def sub_process
    # ...
  end
end

class Machine
  def main_process
    SubmachineA.new().sub_process
  end
end

Machine.new().main_process

😉

class SubmachineA
  def sub_process
    # ...
  end
end

class SubmachineB
  def sub_process
    # ...
  end
end

class Machine
  attr_reader :sub_process_getter
  def initialize(args)
    @sub_process_getter = args[:sub_process_getter]
  end
  
  def main_process
    sub_process_getter.sub_process
  end
end

Machine.new(sub_process_getter: SubmachineA.new()).main_process
Machine.new(sub_process_getter: SubmachineB.new()).main_process

Go

🥱

package main

func main() {
    NewMachine().MainProcess()
}

type SubMachineA struct{}

func NewSubMachineA() *SubMachineA {
    return &SubMachineA{}
}

func (s *SubMachineA) SubProcess(){ /* ... */ }

type Machine struct {}

func NewMachine() *Machine {
    return &Machine{}
}

func (machine *Machine) MainProcess() {
    NewSubMachineA().SubProcess()
}

😌

package main

func main() {
	NewMachine(&SubMachineA{}).MainProcess()
	NewMachine(&SubMachineB{}).MainProcess()	
}

type SubMachineA struct{}

func (s *SubMachineA) SubProcess(){ /* ... */ }

type SubMachineB struct{}

func (s *SubMachineB) SubProcess(){ /* ... */ }

type SubProcessGetter interface {
	SubProcess()
}

type Machine struct {
	subProcessGetter SubProcessGetter
}

func NewMachine(subProcessGetter SubProcessGetter) *Machine {
	return &Machine{subProcessGetter: subProcessGetter}
}

func (machine *Machine) MainProcess() {
	machine.subProcessGetter.SubProcess()
}

感想

書いている途中で、Ruby はそもそも DI を必要としない、という観点があることがわかり面白かったです。

明日は、@daisuke-yamamoto さんの、Terraform、後から来る辛みと処方箋🌶 という記事になります。

参考

この記事は以下の情報を参考にして執筆しました。

詳解Go言語Webアプリケーション開発

13
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?