magic models, meh
on December 01, 2007 @ 10:59 AM
While catching up on RSS feeds this morning I followed a few interesting links and again came across a link to Dr. Nic’s Magic Models . In the past I felt uneasy about this gem, but now I just don’t think it should be used for real projects, although I’m sure it was a fun exercise for the author to write.
The idea seems to be based on removing declarative statements about your model in your model. You would normally write:
1 2 3 4 5 6 |
class Person < ActiveRecord::Base has_many :memberships has_many :groups, :through => :memberships belongs_to :family validates_presence_of :firstname, :lastname, :email end |
The author finds an issue with this, to him it seems unncessary. So he ponders the question:
Why do I have write my own has_many, belongs_to, and validates_presence_of commands if all the data is in the database schema?
I think this is the wrong question to ask, but I can see where the author came up with the question. As I read through the entire page on magic models I see my code beginning to vanish. Something like:
1 2 3 4 5 6 |
class Person < ActiveRecord::Base has_many :memberships has_many :groups, :through => :memberships belongs_to :family validates_presence_of :firstname, :lastname, :email end |
to…
1 2 |
class Person < ActiveRecord::Base end |
to…
# no more code , the person.rb model file has been deleted |
This progression bothers me because in the end you end up without any self-documenting code, and you’ve moved application logic from your application into your database. It seems that I’d rather have a database constraint (like not allowing null fields) reinforce self-documenting declarations in the model such as:
validates_presence_of :firstname, :lastname, :email |
And why would you want to kill declarative relationships in your application?
1 2 3 |
has_many :memberships has_many :groups, :through => :memberships belongs_to :family |
to …
# ... nothing here ... |
Self-documenting code is useful especially when you’re describing how one object relates to another object in your application.
It seems much more appealing to see that in a model rather then having to go fish in the database schema. Leave application logic in the application. There are times you need to use database constraints (among other things) to reinforce your application logic, but you shouldn’t remove self-documenting clean code just because you can.
This is just my developer preference, but I think it’s a good preference to have. I don’t want to unnecessarily spread application logic outside of my application code for the sake of being clever.


0 comments
Jump to comment form | comments rss [?]