Java coding question on iteration and generics -2
This is an extension to Java coding question on recursion and generics.
Q. Can you replace the recursion approach to iteration?
"The recursive implementation will overflow the stack for any data set of real size, your job is to implement a
non-recursive solution."
A. Since we have defined "Compute" as an interface we can provide a separate implementation for iterative approach.
package recursiontoiteration; import java.util.Queue; public class Iteration<R, N> implements Compute<R, N> { @Override public R compute(R r, Queue<N> q, Function<R, N> function) { while (q.peek() != null) { r = function.apply(r, q.poll()); } return r; } }
Now, the test class will only have a small change as shown below.
package recursiontoiteration; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; public class IterationTest { public static void main(String[] args) { Queue<Integer> q = new ArrayBlockingQueue<Integer>(5); q.add(5); q.add(10); q.add(12); Compute<Double, Integer> compute = new Iteration<Double, Integer>(); // change Double result = compute.compute(null, q, new Sum<Double, Integer>()); System.out.println(result); } }
Changing the function to Multiply from Sum is simple as well.
package recursiontoiteration; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; public class IterationTest { public static void main(String[] args) { Queue<Integer> q = new ArrayBlockingQueue<Integer>(5); q.add(5); q.add(10); q.add(12); Compute<Double, Integer> compute = new Iteration<Double, Integer>(); // change Double result = compute.compute(null, q, new Multiply<Double, Integer>()); //change System.out.println(result); } }
So, in other words, the classes are open for extension and closed for modification. This is a design principle known as the "Open Closed Principle (OCP)", which is one of the SOLID design principles. The SOLID design principles are covered in more detail in "Core Java Carteer Essentials"
Labels: Coding
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home