Refectoring

Refactoring is the process of improving the structure of existing code. This does not involve change the function of the code. Some tools can perform automatic refactoring. It is critical to test during the refactoring process to ensure no errors are introduced.

Here is a list of some more common refactorings.

Rename method/field

Improve the name of a structure.

int getTotal() {
int s = 0;
for(int i=0; i<7; i++)
  for(int j=0; j<24; j++)
    s += occurances(i,j);
int getWeeklyStats() {
int sum = 0;
for(int day=0; day<7; day++)
  for(int hour=0; hour<24; hour++)
    sunm += occurances(day, hour);

Extract method

Remove logic from one method into a new separate method. This is very often used when methods become too big. Locate a logically separate section of code and create a new method, attempting to minimize the interface between the methods.

Decompose conditional

Remove evaluation logic from the bodies of conditional evaluation.

while( COUNT >= 1 || lastItem != NULL) {
  lastItem = *(lastItem->next++);
bool hasMore = COUNT >= 1;
bool moreInList = lastItem != NULL;
while(hasMore || moreInList) {
  lastItem = getNextItem();
  moreInList = lastItem != NULL;

Conditional to polymorphism

Replace conditional control with class inheritance.

if(prim.type == SPHERE)
  intersectSphere(prim);
else if(prim.type == TRIANGLE)
  intersectTriangle(prim);
else if(prim.type == CUBE)
  intersectCube(prim);
Sphere :: Primitive;
Triangle :: Primitive;
Cube :: Primitive;
//
prim.intersect();

Class structure

Pull Up

Push down