Introducing Fowler’s Table Data Gateway to refactor poorly designed systems

design-patternslegacymaintenancerefactoringvb.net

I am developing an application, which currently has about 150,000 lines of code. The previous developer didn't really use any discipline when writing code. Application is in production but is continually developed.

I have read Martin Fowler's book (Patterns of Enterprise Application Architecture) and it talks about 'Transaction Scipt' and 'Data Access Objects'. These are the patterns used i.e. there is a class called Person, which contains everything Person related and a class called Order with everything Order related. The functions are not reusable because they contain everything i.e. data access logic, business logic etc. For example, Person.GetPerson will connect to the database find the person, check the age of the person, get all the orders linked to the person etc.

I am thinking about introducing what Martin Fowler terms a Table Data Gateway. I am seeing this as a longer term refactor project. The problem is that this will mean inconsistency to begin with i.e. data access logic will be contained in the new Gateway, but also in the Transaction Script classes (where the other developer put it)? Is it a bad idea to go against the original developers style of coding?

Best Answer

According to Patterns of Enterprise Application Architecture, you can use a Table Data Gateway with the Transaction Script pattern (see the "When To Use It" section of the Table Data Gateway pattern). So your approach seems like a pretty conservative way to move towards better code without radically changing the original style all at once - which is a good thing.

The refactoring should be pretty straightforward as well - you are just going to pull the database logic in the Person class into a PersonGateway class. Admittedly you can't simultaneously refactor all the Transaction Script classes, but that's unavoidable. You probably won't even have to break their API, so I wouldn't worry too much about the fact that for a while some scripts will use gateway classes and some won't.

I think making that change is a better approach than not making it.