著作一覧 |
入力値AにルールBを適用しCを作成しDに保存する。
#1.バラさない class Hole def do_all(a) # b if (a == 0) c = a + 1 elsif (a == 10) c = a * 2 elsif (a == 20) c = a * 3 else c = a end d = Persistence.new() d.write(c) d.close end end
#2.bをバラす class WithoutB def do_all(a) b = B.new(a) d = Persistence.new() d.write(b.c) d.close end end class B def initialize(a) if (a == 0) @c = a + 1 elsif (a == 10) @c = a * 2 elsif (a == 20) @c = a * 3 else @c = a end end attr_reader :c end
#3.BとDの統合 class WithoutBandD def do_all(a) B.new(a).save end end class B def initialize(a) if (a == 0) @c = a + 1 elsif (a == 10) @c = a * 2 elsif (a == 20) @c = a * 3 else @c = a end end def save() d = Persistence.new() d.write(@c) d.close end end
#4.2と同じだがDから具象性を奪う class WithoutB def do_all(a) b = B.new(a) D.instance().save(b.c) end end class B def initialize(a) if (a == 0) @c = a + 1 elsif (a == 10) @c = a * 2 elsif (a == 20) @c = a * 3 else @c = a end end attr_reader :c end class D def self.instance() D.new() end def save(c) d = get_writer() d.write(c) d.close end protected def get_writer() Persistence.new end end
#5.2と同じだがBを細分化する class WithoutB def do_all(a) b = B.create(a) d = Persistence.new() d.write(b.c) d.close end end class B def self.create(a) if (a == 0) b = B0.new(a) elsif (a == 10) b = B1.new(a) elsif (a == 20) b = B2.new(a) else b = B.new(a) end b end def initialize(a) @c = a end attr_reader :c end class B0 < B def initialize(a) @c = a + 1 end end class B1 < B def initialize(a) @c = a * 2 end end class B2 < B def initialize(a) @c = a * 3 end end
ジェズイットを見習え |
仕事だと最初はメソッドにばらすだけか、<br>あるいはUnitTestのためにPersistenceだけ<br>交換できるようにしそう。<br><br>class Hole<br> def initialize(d = Persistence)<br> @d = d<br> end<br> <br> def do_all(a)<br> c = b(a)<br> write(c)<br> end<br><br> def b(a)<br> return a + 1 if a == 0<br> return a * 2 if a == 10<br> return a * 3 if a == 20<br> return a<br> end<br><br> def write(c)<br> d = @d.new<br> d.write(c)<br> d.close<br> end<br>end<br><br>でも咳だと誘惑にまけてこのくらいにしちゃう。<br><br>class SeKi<br> def initialize(rule, store)<br> @rule = rule<br> @store = store<br> end<br> <br> def do_all(a)<br> c = @rule.apply(a)<br> @store.write(c)<br> end<br>end<br><br>class Rule<br> def apply(a)<br> return a + 1 if a == 0<br> return a * 2 if a == 10<br> return a * 3 if a == 20<br> return a<br> end<br>end<br><br>class Store<br> def write(c)<br> d = Persistence.new<br> d.write(c)<br> d.close<br> end<br>end<br><br>class FakeStore < Array<br> def write(c)<br> push(c)<br> end<br>end<br><br>def main<br> fake = FakeStore.new<br> hole = SeKi.new(Rule.new, fake)<br> hole.do_all(a)<br> p fake<br>end
長っ。削除してくださってOKです。
削除なんてもったいないので取っておきます。僕も誘惑後が好き(Bをどこまでやるについては処理量次第なんで)。