0

I have one doubt if this is or is not a good practice.

So immagine that you need to concatenate not defined number of arrays, and then at the end print the result. So immagine that you can call calculate a lot of times. E.g.

Object[] example = new Object [0];

public Object methodAppend(Object[] a, Object[] b){
   - here append the array b to the array a 
   - return the array a
} 

public Object calculate(){

    Object[] someArray = new Object[5]
     // immagine i already have some values in the array
    for(int i=0;i<5;i++)
       example = methodAppend(example,someArray)

    return example
}

I get the wanted result. But my questions are:

  1. Is this

    example = methodAppend(example,someArray)

    a good practice?

  2. How is called when I send the result of the method again in the method?
  3. Is this one example of recursion?

Because for recursion I always thought that is when e.g. for result we call the method again.

tnx

lucidBug
  • 197
  • 1
  • 10
  • No, it's not recursion. You might call this "accumulation", but really, applying an operation repeatedly is a very common practice. Not sure why you find this to be very special. It's like adding up all the numbers in an array by using `result = result + a[i]`. – RealSkeptic Dec 08 '15 at 18:50
  • Tnx for the answer, and yes, i didnt express myself good in the question.... wanted to ask if it was a good practice to concatenate an array in this way – lucidBug Dec 08 '15 at 22:14

1 Answers1

0
  1. Is this bad practice?

Absolutely not. This pattern is widely used and accepted just like any form of x = x + someCall()

  1. How is called when I send the result of the method again in the method?

    • method call is evaluated using current value of your variable.
    • method result is set as new value of your variable
    • on next iteration, the value from last call is now current value
    • . . .
  2. Is this one example of recursion?

No. It would only be recursive, if you'd call someMethod() from within someMethod() like

public int someMethod( int i) {
  if(i < 2) {
    return 1;
  } else {
    return someMethod(i-1)+someMethod(i-2);
  }
}
Jan
  • 13,738
  • 3
  • 30
  • 55