design patterns - Is it better for decision-making logic to live inside the class that acts on the decision or in a separate class? -


take simplified situation: i've got class job create files @ given path (let's call filecreator). files need created, however, if don't exist @ said path.

is better filecreator check whether files exist @ path , create them if don't, or create second class that's responsible checking (filechecker) , let filecreator purely creating (without regard whether exist or not)?

situation 1: decision logic sits in class dependent on decision

class filecreator   def initialize(path)     @path = path   end    def create_files     unless files_exists?(path)       #create files @ path     end   end    def files_exists?(path)      #check if files exist @ path   end end  file_creator = filecreator.new('/foo') file_creator.create_files 

situation 2: decision logic sits in own class

class filechecker   def initialize(path)     @path = path   end    def files_exists?(path)      #check if files exist @ path   end end  class filecreator   def initialize(path)     @path = path   end    def create_files     #create files @ path   end end  file_checker = filechecker.new('/foo') file_creator = filecreator.new('/foo') file_creator.create_files unless file_checker.files_exists? 

the first scenario more convenient, imagine second scenario more flexible (in sense know class responsible what, can juggle them around).

i'm quite new programming, external references thoughts or patterns on particular question appreciated (also, not sure question tagged correctly).

i keep simple possible (but no simpler ;-)

in deliberately simplified example have single class, check functionality closely related create functionality there degree of cohesiveness, can argue code belongs together.

i'd motivated refactor code separate classes under conditions. before explaining such conditions, note thought process: know can refactor should need to, , indeed can without perturbing users of create functionality; design has intrinsic flexibility, we're thinking rearranging internals of create implementation.

some possible reasons refactors 2 classes:

  1. the checks need might become more complex - eg. check permissions, space ... - might want run-time selectivity of checks, feels hierarchy of check classes might emerging, time refactor.
  2. we need reuse check in context, in other class.
  3. the check code becomes complex in own right, need refactor it's code can understand it, grow lots of implementation functions check. @ point our create class becomes cluttered, time refactor.
  4. as complexity increases see need separate testing of check, has become first-class class - needs documenting , controlling in own right.

Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -