I’ve just reviewed some code that looked like this before
public class ProductChecker
{
// some std stuff
public ProductChecker(int AccountNumber)
{
var account = new AccountPersonalDetails(AccountNumber);
//Get some info from account and populate class fields
}
public bool ProductACriteriaPassed()
{
//return some criteria based on stuff in account class
//but now accessible in private fields
}
}
There has now been some extra criteria added which needs data not in the AccountPersonalDetails class
the new code looks like this
public class ProductChecker
{
// some std stuff
public ProductChecker(int AccountNumber)
{
var account = new AccountPersonalDetails(AccountNumber);
var otherinfo = getOtherInfo(AccountNumber)
//Get some info from account and populate class fields
}
public bool ProductACriteriaPassed()
{
//return some criteria based on stuff in account class
// but now accessible in private fields and other info
}
public otherinfo getOtherInfo(int AccountNumber)
{
//DIRECT CALL TO DB TO GET OTHERINFO
}
}
I’m bothered by the db part but can people spell out to me why this is wrong? Or is it?
In a layered view of your system, it looks like
ProductCheckerbelongs to the business rules / business logic layer(s), so it shouldn’t be “contaminated” with either user interaction functionality (that belongs in the layer(s) above) or — and that’s germane to your case — storage functionality (that belongs in the layer(s) below).The “other info” should be encapsulated in its own class for the storage layers, and that class should be the one handling persist/retrieve functionality (just like I imagine
AccountPersonalDetailsis doing for its own stuff). Whether the “personal details” and “other info” are best kept as separate classes or joined into one I can’t tell from the info presented, but the option should be critically considered and carefully weighed.The rule of thumb of keeping layers separate may feel rigid at times, and it’s often tempting to shortcut it to add a feature by miscegenation of the layers — but to keep your system maintainable and clean as it grows, I do almost invariably argue for layer separation whenever such a design issue arises. In OOP terms, it speaks to “strong cohesion but weak coupling”; but in a sense it’s more fundamental than OOP since it also applies to other programming paradigms, and mixes thereof!-)