I am refactoring legacy codebase. Part of it is a loadProduct()
function inside a larger "everything" class. loadProduct()
loads data from a database. I want to move this loading-data part out of the larger class, because I do not think it belongs there. I am not sure exactly where I want to move it yet, but I think that just moving it out into a separate class will do great to start.
How do I do this?
i.e. Imagine this:
class Big
{
function x() {}
function y() {}
function z() {}
function w() {}
...
function loadProduct()
{
$sql = "select * from X where Y = $this->p1 and w = $this->p2";
$result = db_call($sql);
...
$this->a = $result->field_a;
}
}
What I think of so far is:
I can create a
Product
class that instantiates and returns the product data. Call it i.e.$data = new Product($p1, $p2, $p3)
.create a
ProductProvider
class, which has functionloadFromDB()
. Call it:
$pp = new ProductProvider();
$data = $pp->loadFromDB($p1, $p2, $p3);
...
include 'db.php';
class ProductProvider()
{
function loadFromDB($p1, $p2, $p3)
{
$product = null;
//code to load Product
return $product;
}
}
I think way 2 is a bit more flexible and allows me to add more functions later on, such as loading different sets of data from different sets of parameters. This flexibility may come in useful in case legacy codebase gives me surprises later on. (i.e. say as I refactor I may realize I need to move or group this data-loading piece into or with some other piece of code and code encapsulation Provider will give me should be easy to move elsewhere).
Will my 2nd example pattern be a proper* fit for my refactoring example?
- By proper fit I mean industry-accepted best practice, recommended for cases similar to mine.
everything
class, how do you pull out a certain function out of it for the purpose of refactoring. Database is currently global, but later it may be directly loaded in the class itself. – Dennis Mar 31 '14 at 19:50