I recently converted an old application that was using XML files as the data store to use SQL instead. To avoid a lot of changes I basically created ActiveRecord style classes that inherited from the original business objects.
For example
SomeClassRecord :SomeClass
//ID Property
//Save method
I then used this new class in place of the other one, because of polymorphism I didn’t need to change any methods that took SomeClass as a parameter.
Would this be considered ‘Bad’? What would be a better alternative?
1
I would not say this is a ‘Bad’ thing to do. But there are alternatives with their own trade-offs.
Assuming that the way the original classes were used was the ActiveRecord pattern, here are some alternatives.
-
Modify each business object’s
Save()
method to delegate the saving work to a class responsible for dealing with storage, whether it’s XML or SQL. Instead of decorating each class, you delegate the saving to a single interface, say,IDataStore
. For example:<code>public class SomeClass {IDataStore dataStore; // how this gets set can vary alsopublic void Save() {dataStore.Save(this);}}</code><code>public class SomeClass { IDataStore dataStore; // how this gets set can vary also public void Save() { dataStore.Save(this); } } </code>public class SomeClass { IDataStore dataStore; // how this gets set can vary also public void Save() { dataStore.Save(this); } }
Now the change is in the implementation of
IDataStore
. -
Continue using your business objects in the business layer, but when doing data access, map your business objects to data access objects, and use the Repository pattern. For example:
<code>public class SomeBusinessProcess {public void DoSomeWork(SomeClass someClass) {// ... do some work on someClass ...// now saveSomeClassDAO someClassDao = AutoMapper.Map<SomeClass, SomeClassDAO>(); // can use AutoMapper, for examplerepository.Save(someClassDao);}</code><code>public class SomeBusinessProcess { public void DoSomeWork(SomeClass someClass) { // ... do some work on someClass ... // now save SomeClassDAO someClassDao = AutoMapper.Map<SomeClass, SomeClassDAO>(); // can use AutoMapper, for example repository.Save(someClassDao); } </code>public class SomeBusinessProcess { public void DoSomeWork(SomeClass someClass) { // ... do some work on someClass ... // now save SomeClassDAO someClassDao = AutoMapper.Map<SomeClass, SomeClassDAO>(); // can use AutoMapper, for example repository.Save(someClassDao); }
You really can take it as far as you want, based on what your needs are.
In no way is this is not a ‘bad’ thing to do. What you did is akin to the decorator pattern. http://www.dofactory.com/Patterns/PatternDecorator.aspx
In fact I suggest that you do read up on the decorator pattern as its a useful tool to have in your design arsenal.