-2

I have following code.

Dataset function1 (){
StringBuilder sb = new StringBuilder();
sb.append('abcd');
sb.append('efgh');
for(int i=0 ; i< 8; i++){
    sb.append('ijkl');
    sb.append('monop');
    sb.append('ijkl');
    sb.append('monop');

}
Dataset ds = function2(sb);
if(ds.isempty(){
    StringBuilder sb = new StringBuilder();
    sb.append('abcd');
    sb.append('efgh');
    for(int i=0 ; i< 8; i++){
        sb.append('ijkl');
        sb.append('monop');
        sb.append('ijkl');
        sb.append('464sdfsdfsdfggfdkjkjkjkj');
        sb.append('monop');

    }
    ds = function2(sb);

})
return ds; 

}

I dont want to rewrite same code in ds.empty() brackets. Is there any better way to handle this ?

1 Answers1

3

Just put the code in an own method:

public StringBuilder GetString(boolean p_appendExtraStrings)
{
    StringBuilder sb = new StringBuilder();
    sb.append('abcd');
    sb.append('efgh');
    for(int i = 0 ; i < 8; i++)
    {
        sb.append('ijkl');
        sb.append('monop');
        sb.append('ijkl');
        if(p_appendExtraStrings)
        {
           sb.append('464sdfsdfsdfggfdkjkjkjkj');
           sb.append('monop');
        }
    }
    return sb;
}

And then you can replace your current StringBuilder code by a call of this method

Dataset function1()
{
   Dataset ds = function2(GetString(false));
   if(ds.isEmpty()
   {
      ds = function2(GetString(true));
   }
   return ds;
}
Yannick
  • 813
  • 8
  • 17
  • I would work if both string builders were same but if ds is empty , I'm writing same code with extra string appended ( sb.append('464sdfsdfsdfggfdkjkjkjkj'); ) and passing this new string builder to function2. – Rakesh Regar Jun 23 '17 at 03:54
  • Ah i see, my fault. I've updated my code with an extra parameter "p_appendExtraStrings". The extra values will be only appended if the boolean is true. So the first call is with "false" and the second with "true". I hope this correcture will solve your problem! – Yannick Jun 23 '17 at 13:17
  • It will work fine but still GetString() function is called 2 times. Time complexity is the same as previous code. Is there another method so that time complexity can be reduced ? – Rakesh Regar Jun 24 '17 at 12:37
  • You wrote "I dont want to rewrite same code in ds.empty() brackets" -> So the solution is to put the code in an own method – Yannick Jun 28 '17 at 09:03