Re: Mixing OO and DB

From: Robert Martin <unclebob_at_objectmentor.com>
Date: Tue, 4 Mar 2008 16:47:35 -0600
Message-ID: <2008030416473579149-unclebob_at_objectmentorcom>


On 2008-03-02 13:28:28 -0600, frebe <frebe73_at_gmail.com> said:

> On 2 Mar, 20:01, Robert Martin <uncle..._at_objectmentor.com> wrote:

>> 
>>>>   Employee e = Employee.find("Bob"):
>> 
>>>>   DataRow e = exec("Select * from EmployeeTable where name = 'Bob';);
>> 
>>> Why is the first line better than the last line?
>> 
>> It's smaller, more communicative, and can be polymorphically deployed.

>
> Both are one-liners.

True, but most forms of the top line will remain one-liners even when the SQL grows to many lines.

> It is only more communicative if the reader can't
> read SQL.

No matter how you cut it, find("bob") is easier to read than any select statement.

> The SQL can be deployed to a lot of databases.

The first line does not prevent that since it's implemented by the second line.

>> All we are doing is giving each query a name.  That name
>> is the name of the method that is implemented by the SQL.  This allows
>> the programmer to commnicate the *intent* of the query, rather than
>> it's implementation.

>
> What stops you from creating views when suitable?

Nothing.

> If you force
> programmers to put every unique SQL statement inside a method, they
> will soon hesitate writing new SQL statements, and try to reuse old
> ones that doesn't fit, but still does the job.

By the same token they might just copy and paste the previous SQL into the new position. Same motivation, same result.

>> e.g. Employee.find_all_eligible_for_retirement() is a lot better than a
>> long and complex SQL statement.

>
> create view eligible_for_retirement, is even better. But you contine
> to ignore views....

Views make nice ways to implement the simple methods I'm talking about.

>

>>> What is the benefit with hiding SQL from the bulk of the application?
>> 
>> You can provide test implementations that don't use the database, but
>> allow you to quickly test business rules.

>
> If the business rules (eligible_for_retirement) is in the database,
> the test would be pretty useless.

The business rule is not the query. The business rule is what is done with the results of the query. For example, I want to test that I can send email to all the eligible employees, and format that email nicely with their name, employee number, years of service, etc. The query is irrelevant to the job of creating and sending the emails.

-- 
Robert C. Martin (Uncle Bob)  | email: unclebob_at_objectmentor.com
Object Mentor Inc.            | blog:  www.butunclebob.com
The Agile Transition Experts  | web:   www.objectmentor.com
800-338-6716                  |
Received on Tue Mar 04 2008 - 23:47:35 CET

Original text of this message