No code duplication in loops

Share this topic:



Link to this posting

Postby Ursego » 21 Feb 2013, 10:48

Don't populate the variable, used for looping control, twice (before and inside the loop body). Populate it only once, inside the loop.

You can ask - why? We see that kind of duplication in most programming books! The answer is simple: we have to avoid any sort of code duplication, so there is no reason to write twice something which can be written only once to achieve the same goal.

*** BAD code: ***

PB:
Code: Select all
ll_row = dw_cust.GetNextModified(ll_row, Primary!)
do while ll_row > 0
   [do something with the modified row]
   ll_row = dw_cust.GetNextModified(ll_row, Primary!)
loop

PL/SQL:
Code: Select all
FETCH emp_cursor INTO v_row;
WHILE emp_cursor%FOUND LOOP
   [do something]
   FETCH emp_cursor INTO v_row; -- deja vu! :-)
END LOOP;

An eternal loop with 'break' ('exit when' in PL/SQL) is a very elegant solution in such a situation:

*** GOOD code: ***

PB:
Code: Select all
do while true
   ll_row = dw_cust.GetNextModified(ll_row, Primary!)
   if ll_row < 1 then exit
   [do something with the modified row]
loop

PL/SQL:
Code: Select all
LOOP
   FETCH emp_cursor INTO v_row;
   EXIT WHEN emp_cursor%NOTFOUND; -- or "IF emp_cursor%NOTFOUND THEN BREAK;"
   [do something]
END LOOP;
User avatar
Ursego
Site Admin
 
Posts: 112
Joined: 19 Feb 2013, 20:33

Return to Coding Style

Who is online

Users browsing this forum: No registered users and 0 guests


No code duplication in loops

Share this topic:


If you think that this site is not too bad, please LIKE it in Facebook. Thanks!





free counters

eXTReMe Tracker