1

I'm working on Ruby on Rails. There is a feature in our app where doctors can "claim" cases for themselves.

I can either have the doctor perform the action and update the plate, or I can have the doctor send itself to the plate and have the plate update itself.

Should objects update itself? It just seems cleaner to me, but I'm not sure. Or maybe I'm overthinking?

First case, doctor only:

def claim(plate)
  plate.claimed = true
  plate.doctor_id = id
  plate.save
end

This is the second case (doctor sends itself to the plate):

  #doctor
  def claim(plate)
    plate.claimed_by(self)
  end

  #plate
  def claimed_by(doctor)
    self.claimed = true
    self.doctor_id = doctor.id
    self.save
  end
4

The second case allows additional business logic (such as validation) to occur in the method body, unless plate.claimed and plate.doctor_id are first-class properties, and already have validation in their own right.

The second case is more "atomic," in the sense that the plate object has more control over its own state within the claimed_by method. If something goes wrong, you're still in the method body, and have an opportunity to do some clean up.

The second case is a better example of "Tell, don't ask.". Rather than manipulating the plate object's data from the outside, you're telling the plate object what you want, and letting the plate object manipulate its own state.

  • That's a useful link. – Rory Hunter Mar 4 '14 at 16:41
  • Thank you. I was trying double dispatch from a lecture I heard. Is it safe to say that it's nice for classes to own the methods that modify themselves? – Daryll Santos Mar 4 '14 at 16:53
  • Yes, it would be safe to say that. – Robert Harvey Mar 4 '14 at 16:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.