How to prevent duplicate data access methods that retrieve similar data?
- by Ronald Wildenberg
In almost every project I work on with a team, the same problem seems to creep in. Someone writes UI code that needs data and writes a data access method:
AssetDto GetAssetById(int assetId)
A week later someone else is working on another part of the application and also needs an AssetDto but now including 'approvers' and writes the following:
AssetDto GetAssetWithApproversById(int assetId)
A month later someone needs an asset but now including the 'questions' (or the 'owners' or the 'running requests', etc):
AssetDto GetAssetWithQuestionsById(int assetId)
AssetDto GetAssetWithOwnersById(int assetId)
AssetDto GetAssetWithRunningRequestsById(int assetId)
And it gets even worse when methods like GetAssetWithOwnerAndQuestionsById start to appear.
You see the pattern that emerges: an object is attached to a large object graph and you need different parts of this graph in different locations.
Of course, I'd like to prevent having a large number of methods that do almost the same. Is it simply a matter of team discipline or is there some pattern I can use to prevent this? In some cases it might make sense to have separate methods, i.e. getting an asset with running requests may be expensive so I do not want to include these all the time. How to handle such cases?