Reducing Duplicate Code
Posted: Thu May 20, 2010 2:28 am
In my current project, I have many places where I have duplicate code that looks similar to the following two snippets
Here the code is 99% the same except one updates an existing entry, and one inserts a new entry. How do I reduce this duplicate code? Is it worth the extra code and complexity to write a method that can handle both cases, then wrap that method into these two methods? This particular situation only has these two methods, but in my Forum code, there are several more like this. Minor differences, but a majority of the code is the same. Maybe this duplication means something is wrong with my design?
Code: Select all
public function insertPage($title, $body) {
$table = $this->getPageTable():
$data['title'] = $title;
$data['body'] = $body;
$data['last_update'] = time();
$result = $table->insert($data);
return $result;
}
public function updatePage($title, $body, $id) {
$table = $this->getPageTable();
$data['title'] = $title;
$data['body'] = $body;
$data['last_update'] = time();
$where = $table->getMySQL()->quoteInto('id = ?', $id);
$result = $table->update($data, $where);
return $result;
}