so I’m writing DataBase class which will be an encapsulation layer between PHP Controller and MySQL View.
interface iDataBase {
public function drug($action, $drug);
public function company($action, $company);
public function activeIngredient($action, $activeIngredient);
}
At First I thought of making all setters and getters seperate like getAllDrugs(), updateDrug(), removeDrug(), getForUpdate(), getDrug() and so one, but then I realised that I was polluting database interface with too much functions, plus this is a very small-scale version, I’m considering adding much-more classes and much more functionality. So, instead of using a lot of function I just setteled for 3. $action will determine what kind of thing does user want to do with certain class. so, for now, possible actions are these: "add", "getAll", "getForUpdate", "update", "remove"
but these functions masked by $action have different things to do, so their their return result is different and second argument can also be different.
Is my solution a good practice? I’m sure many of you had the same problem, how did you solve it? Are there any possible problems?
P.S. Drug, Company, ActiveIngredient are all classes
A function should have clearly defined, narrow responsibilities with clearly defined, minimalist return types. If you start to create “god functions” which do everything and the kitchen sink depending on what arguments you pass, you’re going heavily into the territory of hard to maintain spaghetti code. You do not want a function that does A and returns B if you pass it X, but does C and returns D if you pass it Y etc…
It is a good idea to start concrete and generalize over time as you see similar patterns emerge. So, create the methods you actually need:
If you find you have shared code between these functions, unify the code behind the scenes to keep it DRY:
Don’t start the other way around, thinking you “only need X,Y and Z” which seem similar enough to be unified into one method, then later finding out there are small differences between X, Y and Z and littering your code with special cases for each. That just leads to functions which are either ginormous or so general they basically do nothing on their own.