tags:

views:

107

answers:

2

Hi

I am wondering is there any better way to design loops. AS you see function1 and function2 has almost similar code expect getting Hash Map.

*Current Code 1 *

//Field
 ResultSet rs = null;
 HashMap<Object, Object> hashMap1;
 HashMap<Object, Object> hashMap2;



if(somecondition)
{
   function1()
}
else
{
   function2();
}

void function1()
{
    while(rs.next)
    {
       hashMap1 = someClass.getData1();
       hashMap2 = someClass.getData2();
       // compareHashMap
   }

}

void function2()
{
    while(rs.next)
    {
       hashMap1 = someClass.getModfiedData1();
       hashMap2 = someClass.getModfiedData2(); 
        // compareHashMap
    }
 }

Another Way( short and sweet) 2

while(rs.next)
{
     if(somecondition)
     {
         hashMap1 = someClass.getData1();
         hashMap2 = someClass.getData2();
     }
     else
     {
       hashMap1 = someClass.getModfiedData1();
       hashMap2 = someClass.getModfiedData2();  
     }
     // compareHashMap
 }

Questions:

If there are 10000 records or more in DB is it better to go with 1 ?

Is there any alternate desgin or I go wiht No 2?

Thanks

+2  A: 

I think an easier way would be to make "somecondition" a property that you set on someClass, and then have a single method that you call to getthe data. Something like

someClass.someCondition = somecondition

while(rs.next)
{
    hashMap1 = someClass.getMyData1();
    hashMap2 = someClass.getMyData2();
}

or, you could pass the variable into the function

while(rs.next)
{
    hashMap1 = someClass.getMyData1(somecondition);
    hashMap2 = someClass.getMyData2(somecondition);
}
Kibbee
+3  A: 

Well in the first example, you check a condition once and then iterate over N records. In example 2, you are iterating over N records as well as performing N condition checks. If this is a condition that needs to be examined for each individual record, then the second loop is the one to be used. Otherwise if it is a condition that only needs to be checked once...why add the unneeded overhead of checking the condition N times?

Judicium