2
4

More than 5 years have passed since last update.

golangでCleanArchitectureのusecase部を実装してみた

Last updated at Posted at 2018-09-04

この図の右下にある、ピンク色のUse Casesの部分。
クリーンアーキテクチャ(The Clean Architecture翻訳)より
cleanarchitecture
今一番パパっと手が動くのがScalaなので先にScalaで超素朴に実装するとこんな感じかなと。

scala
trait InputPort[I, O] {
    def run(param: I, outputPort: OutputPort[O]): Unit = outputPort.run(doRun(param))
    protected def doRun(param: I): UseCaseResult[O]
}

trait OutputPort[T] {
    def run(usecaseResult: UseCaseResult[T]): Unit
}

type Errors = List[String]
type UseCaseResult[O] = Either[Errors, O]

特にこのInputPortでやっているtemplate methodな部分をgolangで書くとどうやるのかなーとすぐに思いつかなかったのでトライしてみた。

こんな感じ・・・かな?

go
package usecases

type InputPort struct {
    Interactor Interactor
}

func (inputPort InputPort) Run(param interface{}, outputPort OutputPort) {
    outputPort.Run(inputPort.Interactor.Run(param))
}

type Interactor interface {
    Run(param interface{}) UseCaseResult
}

type UseCaseResult struct {
    Value interface{}
    Error error
}

type OutputPort interface {
    Run(result UseCaseResult)
}

追記:
単にこんなんでも良いような気もする。

go
type InputPort interface {
    Run(param interface{}) UseCaseResult
}

type OutputPort interface {
    Run(result UseCaseResult)
}

func Run(param interface{}, inputPort InputPort, outputPort OutputPort) {
    outputPort.Run(inputPort.Run(param))
}
2
4
2

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
2
4