Is duplicate PHP code bad practice?

To further clarify, I am wanting to find out if it is bad practice to duplicate a method / function, say it has a different while loop or slightly different variables etc.

See below, these are two different functions, should I create one giant multi pupose function or keep them as two seperate, which is best practice?

Sometimes you can fit everything within 1 function but not sure if that should always be the case or if there is a best practice for minimizing copy / paste scenarios or it doesnt really matter?

function method1($data) {

    $mydate = $data;
    $test = $this->load->view('testpage',$mydata);

}

function method2($data) {

    $otherdata= $data;
    $test = $this->load->view('anotherpage',$otherdata);

}

In general, I’d extract the common parts and create a private/protected method (if this is in a class, as hinted at by the use of $this).

But I’m not really seeing duplication in your code. One line doesn’t make duplication.

Try this:



function method( $testpage=NULL, $my_data=array() ) 
{
    $this->load->view( $testpage, $my_data );
}


/* NOT REQUIRED
function method1($data) 
{
    $mydate = $data;
    $test = $this->load->view('testpage',$mydata);

}
function method2($data) {

    $otherdata= $data;
    $test = $this->load->view('anotherpage',$otherdata);

} 
*/

In your short example, it is better to merge them into one function.

However, and this is the big part, if the function needs to start doing more, and you have to pass in even more parameters, start considering ways to break it apart into easier maintainable groups. Last thing you want is a megalithic function that can both cook and clean at the same time.

To me this looks like you gave an example from a conroller-class. In that case I don’t think it would be smart to put several different functions from a controller-class into 1 function.