Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like SQLDataSet often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use SQLDataSet, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 4 | class SQLDataSet extends DataSet |
||
| 5 | { |
||
| 6 | protected $pdo; |
||
| 7 | |||
| 8 | View Code Duplication | function __construct($params) |
|
| 9 | { |
||
| 10 | if(isset($params['user'])) |
||
| 11 | { |
||
| 12 | $this->pdo = new \PDO($params['dsn'], $params['user'], $params['pass']); |
||
| 13 | } |
||
| 14 | else |
||
| 15 | { |
||
| 16 | $this->pdo = new \PDO($params['dsn']); |
||
| 17 | } |
||
| 18 | } |
||
| 19 | |||
| 20 | function _get_row_count_for_query($sql) |
||
| 35 | |||
| 36 | View Code Duplication | function _tableExistsNoPrefix($name) |
|
| 48 | |||
| 49 | View Code Duplication | function _tableExists($name) |
|
| 61 | |||
| 62 | View Code Duplication | function _viewExists($name) |
|
| 74 | |||
| 75 | function tableExists($name) |
||
| 91 | |||
| 92 | function getTable($name) |
||
| 108 | |||
| 109 | function read($tablename, $where=false, $select='*', $count=false, $skip=false, $sort=false) |
||
| 153 | |||
| 154 | View Code Duplication | function update($tablename, $where, $data) |
|
| 175 | |||
| 176 | View Code Duplication | function create($tablename, $data) |
|
| 198 | |||
| 199 | function delete($tablename, $where) |
||
| 200 | { |
||
| 201 | $sql = "DELETE FROM $tablename WHERE $where"; |
||
| 202 | if($this->pdo->exec($sql) === false) |
||
| 203 | { |
||
| 204 | return false; |
||
| 205 | } |
||
| 206 | return true; |
||
| 207 | } |
||
| 208 | |||
| 209 | function raw_query($sql) |
||
| 219 | } |
||
| 220 | ?> |
||
| 221 |
Adding explicit visibility (
private,protected, orpublic) is generally recommend to communicate to other developers how, and from where this method is intended to be used.