refactoring - Ruby: Improve complex initialize method -
i have piece of ruby code boils down this:
class foo attr_reader :a, :b, :c def initialize build_a build_b build_c end private def build_a # complex results in @a = end def build_b # complex results in @b = end def build_c # complex results in @c = end end calling build_* in initialize method seems bit superfluous. there better way write this? of course i'm aware of lazy loading pattern:
class def @a ||= something_complex end end but, need code thread safe, can't use pattern here.
edit: main concern code, see fact build_a should called after initialisation, written @ definition of build_a instead of in initialize method.
those callbacks real pain in ass test , maintain. wouldn't solution better?:
class foo attr_reader :a, :b, :c def initialize # things belong in initialize end def self.call # or other name new.build_things end def build_things build_a build_b build_c end end the drawback use foo.call instead of foo.new. if don't want class 'feel' service object, i'd go ahead , wrap in one, foobuilder. way avoid callbacks, testing easy , code clean , readable. think it's best approach if want build_things after initialization.
Comments
Post a Comment