Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an object's methods act on itself?

I'm not sure where to put some methods.

Let's say I want to send an email.

Which of the following options should I choose:

email = new Email("title", "adress", "body");
email.send();

or

email = new Email("title", "adress", "body");
Postman.send(email);

Because how can an email send itself? And isn't it better to have a central object that handles all emails because then he can regulate things like sending all emails at a specific time, sort mails, remove mails etc.

Also if I want to delete an user, how should I do:

user.delete();

or

administrator.delete(user);

Please share your thoughts about how to know where to put the methods.

like image 237
ajsie Avatar asked Dec 08 '22 01:12

ajsie


2 Answers

I disagree with Arseny. An email can send itself, and that's exactly where the code should live. That's what methods are: actions that can be performed on the object.

However, note that your approaches are not mutually incompatible. An email's send action could easily just contain the code to add itself to the Postman's send queue, and if you do want to regulate the actions, that might be a good idea. But that's no reason not to have a send method for the email class.

like image 178
Daniel Roseman Avatar answered Dec 09 '22 13:12

Daniel Roseman


All sensible methods that act on emails should be in the email class, for the convenience of users of your class. But email objects should not contain any fields except those related to the content of the email itself (single responsibility principle).

Therefore, I'd suggest this:

class Email
  def email(postman)
    postman.send(self)
  end
end

In statically typed languages, the type of the postman argument should definitely be an interface.

like image 39
Michiel de Mare Avatar answered Dec 09 '22 15:12

Michiel de Mare