What is the best way to reorganize two classes with a lot of conditional logic?

I have an Event class that contains the start and end time of an event. Each Event object can have several related ChildEvent objects representing each repetition of the parent event. Each of these classes must take different actions depending on how they are edited, for example.

Removing only one event:

  • Event: before the removal of the first parent, the parent of all other children
  • ChildEvent: just delete as usual

Deleting an event and all subsequent events:

  • Event: delete all child events and then delete itself
  • ChildEvent: delete all future siblings, and then delete itself

Editing only one event:

  • Event: make the first child the parent of all other children, then update
  • ChildEvent: update yourself as usual

Editing an event and all subsequent events:

  • Event: update all child events and then update itself
  • ChildEvent: update all future siblings, then update yourself

Currently, I achieve this by checking conditions and taking appropriate actions, but it starts to get confused (there are other conditions with corresponding behaviors). I am curious to know how more experienced programmers can handle it (I use ruby). Any ideas?

+3
source share
3 answers

Sounds like a case for a template to encapsulate your logic.

+3
source

?

previous next (, ).

(delete):

  • previous next Event previous
  • next previous next

(delete-all):

  • next previous
  • recurse on next
  • next

(edit):

  • previous next previous
  • next previous next

(edit-all):

  • , next previous
  • recurse on next
  • next
0

. Events ChildEvents EventType Event s.

EventType  # Has many Events
---------
name
# ...

Event      # Belongs to EventType
-----
event_id
start_time
end_time
# ...

.

...

Event.find(:first, :conditions => [
  'event_type_id = ? AND start_time > ?',
  event.type.id,
  event.start_time],
  :order => 'ASC'
)

...

events_to_delete = Event.find(:all, 
  :conditions => [
    'event_type_id = ? AND start_time >= ?', 
    event.event_type.id,
    event.start_time
  ])

Event.destroy( all_events_to_delete.map { |event| event.id } )
0

Source: https://habr.com/ru/post/1713052/


All Articles