Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to use a global function inside a class ?

Question about using global functions inside classes, I'm working on a MVC system.

The following method is part of a class it calls methods in the class such as the model and the view my question is I've got a global function in there called redirect() I've set it in a functions file that's loaded in my bootstrap file, as all controllers may need access to it, is this a bad practice or would I be best to make this a method of the controller class as all the controllers extend the parent controller.

public function post($slug){

  if(!$slug){ redirect('blog'); }

  $data = $this->model->getPost($slug);
  $this->view->render('blog/single', $data);
}

Or would a static class make more sense? just seems a little over the top for a simple redirect function.

like image 669
Dave Avatar asked Dec 27 '22 12:12

Dave


2 Answers

Global functions are not necessarily bad practice. There are two things to be aware of:

Naming: You should make sure that the name of the function avoids collisions and is obvious to what it relates. Your redirect function, it would be expected that it performs a request redirect. If instead your method related to something else more specific it would need to be clear that that is the case by prepending some contextual information.

State: Global functions should be stateless. This means the function should always provide the same result for the given input. If it does different things depending upon the time of day, the value of some variable, etc... Then generally this is bad. That may see like an obvious pitfall but there are more subtle versions of that problem. The obvious exception to this rule is actually requesting the time of day...

It looks like your code there obeys these two rules and so it is perfectly acceptable to do this.

Edit There is the testability issue, as you are referencing a global function that is required in by the class (or should be), you cannot mock this. For example in your redirect example you couldn't test the class properly without triggering the redirect function and you can't use a mock version of the function to detect that the real redirect method would have been called.

like image 50
Stuart Wakefield Avatar answered Jan 31 '23 06:01

Stuart Wakefield


Using global function is bad practice, because it makes your classes untestable. You should put your desired methods to some object and pass it to classes as their dependency.

like image 44
jasir Avatar answered Jan 31 '23 07:01

jasir