30.06.2013 Views

SQL Server Team-based Development - Red Gate Software

SQL Server Team-based Development - Red Gate Software

SQL Server Team-based Development - Red Gate Software

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

SELECT UserId ,<br />

UserName ,<br />

UserPassword ,<br />

UserStatus<br />

FROM Users<br />

WHERE UserStatus IN ( 'Inactive', 'Deleted' )<br />

GO<br />

Listing 11-18: The "Tell, don't ask" anti-pattern.<br />

345<br />

Chapter 11: <strong>SQL</strong> Refactoring<br />

Notice anything particularly wrong with this code? No? I didn't either, for a long time.<br />

However, the issue here is that we're using the actual UserStatus column values<br />

(inactive, deleted, etc.) in the code, to filter rows. We compare the column value<br />

to a scalar value, in the query, in order to decide whether a row meets the comparison<br />

condition. In effect, we're asking instead of telling.<br />

The problem with this approach only becomes apparent when one considers what<br />

would happen if, for some reason, we had to change one of the UserStatus strings, for<br />

example, changing the UserStatus from Deleted to Removed. This will essentially<br />

change the number of rows this query will return. To fix that, we'd have to change our<br />

code everywhere we referenced that string. Furthermore, what happens if a customer<br />

wants to execute some defined action for all users that are Inactive and Sleeping, or<br />

Active and Sleeping? Some developers might try to solve this with enums, but this<br />

doesn't give us a clear data meaning from the data itself; we need to decode the enum in<br />

order for the data to make sense.<br />

The real answer is to "Tell, don't ask." We need a column that describes the condition,<br />

and then in the code, just evaluates this condition to true or false. This is a DDL<br />

refactoring problem, i.e. this refactoring involves making a change to the table schema.<br />

By changing the conditions in code to actual columns in the table, the intent of the<br />

condition is clearly understandable and maintainable. Listing 11-19 shows the refactored<br />

DDL and the fixed query.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!