Let's say I want to write a Persona DAL. The two approaches I can think of are:
1) As much generic as possible, like:
GetAll(filters) {
query = 'select * from persona where ';
if (filters.id) {
addWhereToQuery(query, 'id');
}
if (filters.name) {
addWhereToQuery(query, 'name');
}
// More filters here...
return dbConn.Query(query, filters);
}
With this approach I always face some problems:
- It's hard to think a generic design that can work for future changes.
- New requirements need more customizable generic functions, for example let's suppose that now you want to be able to cast any of the columns, you could add a new argument
castOptions
and it's logic. This adds the need for stronger testing and the function becomes more messy and messy with every change.
2) A Specific approach, like:
GetAll() {
query = 'select * from persona;';
return dbConn.Query(query);
}
GetById(id) {
query = 'select * from persona where id = ?;';
return dbConn.Query(query, id);
}
GetByName(name) {
query = 'select * from persona where name = ?;';
return dbConn.Query(query, name);
}
// More methods here
I like this approach more, some problems I get are:
- Naming problems, for example I want to get all persona by sex, location and marital status, I end up writing something like
GetAllBySexAndLocationAndMaritalStatus(sex, location, maritalStatus)
. - If now I need something like the previous method but for all persona by sex, not in this location and marital status, I end up with another method like
GetAllBySexAndNotInLocationAndMaritalStatus(sex, location, maritalStatus)
.
So finally, my questions are: - What is your opinion on this? - What approach do you take to avoid this kind of problems?
Aucun commentaire:
Enregistrer un commentaire