Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

carrying on, why make all user models define a no-op?

   class User
     def post_created(post);  end
   end

   class TwitterUser < User
     def post_created(post)
       post.send_to_feed(twitter)
     end
   end

   class EmailUser < User
   end


A better solution would be to just use Observers. One for email, one for twitter. The user shouldn't care about how to talk with these services.


Observers are one of the worst possible solutions because they lie outside the purview of, well, everything in the system. You don't ever see them in the code. You don't know they are there. They are pieces of unicorn code that have side effects that you won't know about or see because they aren't "in the code". Horrible solution.

Code should be simple and easy to understand. Observers add significant complexity and make your code vulnerable to unnecessary bugs because the code that acts on your objects is invisible to the normal control flow of the program and those who write or maintain it.


They add (at least in Ruby) a few lines of code to a program; and take things like Email out of the User model and put them in a more appropriate place.


And you'd never know that they existed if you look at the user model...

My stance is that things like sending email should be explicit calls so they are obvious. Sending email when registering a new user, for example, should be in the if user.save branch in your controllers or, if you have a more SOAish app, in the service that creates users.

def create user = User.create(params[:user])

  if user.save
    Emailer.new_user_email.deliver
    render 'welcome'
  else
    render 'oh shit'
  end
end

Or, refactor that out a bit (ONLY IF NECESSARY!)

def create user = UserService.create_user_from(params[:user])

  if user
    render 'welcome'
  else 
    render 'oh shit'
  end
end


Inheritance is not always the right solution.


Especially when the examples are written in a language which has mixins as core functionality.


Mixins are inheritance. When people say "prefer composition over inheritance," they don't mean mixins.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: