I have an Entity Student
with following properties – (name
, joinedOn
, birthday
, age
, batch
, etc.) and a function fetchStudents(<params>)
.
I want to fetch students based on multiple filters.
In my method I have two ways to pass filters.
- Pass all filters as params to the method
- Make a class StudentCriteria with filters as fields and then pass
the object of this class
While working in java I always go with the second option but recently I'm working in php and I was advised to go with the first way. I am unable to figure out which way is better in maintaining the code, reusability and performance wise. Thanks.
Best Answer
I personally don't like having too many optional arguments if I can get away with it. I can find it quite hard to read and when you end up passing things like
where the method declaration is actually something like (of course real parameter names would be better named)
It's hard to know from reading this what exactly the values are and also what you are setting or leaving out. Every time I want to call that method I have to be very careful to set the right parameters in the right place.
A possible alternative is to use something like the Builder pattern where you are building up the criteria you wish to add explicitly. For those parameters which are required you make part of the constructor. For those optional ones you have a method to add.
Something like:
I guess you could then use it like
// do stuff
Each method would be responsible for adding the filter if valid. So I guess in the case of the name if it was an empty name you would not add it as a filter etc as it wasn't required, or throw an exception etc etc
If it came down to it, where there are many properties I prefer the object option. If some are required at least make them part of the constructor. If you at least made the optional ones method based you could add validity checking on the data at that point, or leave it up to the user of the object to do.
Just my 1 1/2 cents.