LoginSignup
0
0

More than 1 year has passed since last update.

これって純粋で副作用がない関数なの?

Last updated at Posted at 2021-05-19

あるStructの関数を実装していて、この関数は純粋なのか、副作用があるのか良くわからなくなって来た!
正解はわからないのだけど、気持ち悪さを無くしたいという自己満足なお話

struct Size {
    let w: Int
    let h: Int
    //w と hを x で文字列連結
    func toString() -> String {
       return "\(w) x \(h)"
    }
}
Size(w:160,h:120).toString() // 160 x 120

正解はわからないのだけど、感じた違和感

なにが違和感かというと、多分関数に渡された引数が無くて、関数外のプロパティにアクセスしているから、、、なのかなー。
実装だけ見ると、副作用は無い事はわかるんですけど、下記のように

struct Size {
    let w: Int
    let h: Int
    //w と hを x で文字列連結
    static func toString(_ item: Size) -> String {
        return "\(item.w) x \(item.h)"
    }
}
Size.toString(Size(w:160,h:120)) // 160 x 120

渡された引数のみで演算して結果を返す方が、純粋関数っぽいかなーっと。

Rxだとこんな感じに実装しそうだな

ちょっと遠回りして考えて見たりして

struct Size {
    let w: Observable<Int>
    let h: Observable<Int>
    let stringValue: Observable<String>
    init(w: Int, h: Int) {
        w = Observable.just(w)
        h = Observable.just(h)
        stringValue = Observable.combineLatest(w,h) { return "\($0) x \($1)"  }
    }
}
Size(w:160,h:120).stringValue.bind { print($0) } // 160 x 120 

これって、やってることってComputed propertyだなーと思いました。

結果、僕の中で違和感がなくなったので良しとするかwww

struct Size {
    let w: Int
    let h: Int
    //w と h を x で文字列連結
    var stringValue: String {
       "\(w) x \(h)"
    }
}
Size(w:160,h:120).stringValue // 160 x 120

以上、ポエムでした!

0
0
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
0
0