I have a class with a validId($id)
method that is called by the constructor and by public function load($id)
. The method queries the database to see if the id exists and returns true/false.
The constructor optionally takes an $id
(if no $id, then the object will be empty).
The constructor checks the $id with validId($id)
, and if it passes, then it calls load($id)
.
I should not take validId()
out of load()
because load()
is public and the input has to be checked!
The same goes for the constructor.
How do I avoid calling validId()
twice? I was thinking I could add a parameter to load($id,$check_id)
, but that would be ridiculous. You can’t give clients the option to not validate data!
I could add a protected property like $id_is_valid
that gets set to true by validId($id)
. But how do I know the value that was valid is the same one being received by my load()
method?
I’m using PHP.
Hopefully this isn’t a stupid question.
If the constructor calls load($id)
(which calls validId
by itself), why does it has to call validId
first? Let it call load($id)
unconditionally, make sure load($id)
returns some status to show if the id was valid or not, so the constructor can act accordingly.
This suggestion will work, but it is still not the cleanest one. Better create an additional, private method load_unchecked($id)
and call this from the constructor as well as from load
. This gives you the control you want.