Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factoring/Refactoring a program

What does the term 'poorly factored' and 'refactoring' a program mean? Can you give a simple example to understand the basic difference ?

like image 474
user22324 Avatar asked Apr 08 '11 20:04

user22324


2 Answers

Refactoring is a general technique that can refer to many tasks. It usually means cleaning up code, removing redundancy, improving code quality and readability.

A very simple example of poorly factored code:

do_task1("abc");
do_task2(123);
do_task3(7.43);
...
//100 lines later:
do_task1("abc");
do_task2(123);
do_task3(7.43);
...
//80 lines later:
do_task1("abc");
do_task2(123);
do_task3(7.43);

See how the same set of 3 lines is repeated over and over and over?

Refactoring this code might give:

procedure do_tasks1to3(x,y,z)
    do_task1(x);
    do_task2(y);
    do_task3(z);
end

do_tasks1to3("abc",123,7.43);
...
//100 lines later:
do_tasks1to3("abc",123,7.43);
...
//80 lines later:
do_tasks1to3("abc",123,7.43);

The refactored code makes use of a procedure to perform the repetitive tasks, and if a do_task4 ever needs to be added, it only needs to be done inside the procedure, not in 4 separate places like before.

There are other ways to refactor this, and of course if you ever needed to have variance to the do_taskn functions this might not work, but this is usually how you'd start...

like image 141
FrustratedWithFormsDesigner Avatar answered Oct 21 '22 10:10

FrustratedWithFormsDesigner


Poorly factored means containing redundancies, or organized in a way that makes core dependencies difficult to see. The term initially comes from math:

Factoring: Finding what to multiply together to get an expression.

There are many ways to factor an expression, just as there are many ways to write a program achieving the same result. As we all know form algebra, finding a suitable factoring can make the whole equation much easier to solve.

like image 43
ddimitrov Avatar answered Oct 21 '22 10:10

ddimitrov