Friday, April 16, 2010

More real example about how to write clean code

DO NOT DO THIS !

    // Check to see if the employee is eligible for full benefits
    if ((employee.flags & HOURLY_FLAG) &&
          (employee.age > 65))

PREFER THIS WAY

    if (employee.isEligibleForFullBenefits())


Note: Yes yes....I am planning to combine all good samplings about writing clean code under a unique Header in My Blog.

Wednesday, April 14, 2010

Java Executor Service and Future !!!


Some jobs can be passed to another thread/pool and can be called with a given timeout value.
By the way your application business logic can continue its execution without waiting longer than expected or hanging.
Here is the task is "Callable c" and given timeout is 2000 millisecond. "future.get". So we will get a TimeoutException.

You can easily test it by running.
I have tried to simulate some blocking method with Thread.sleep ().You can replace it with your own code (exm:socket.read ()).


In the below example timeout is 2 seconds and operation takes 3 seconds.So code will get timeoutException.If you decrease the timeout will get a return object called ReturnObject.

import java.util.concurrent.*;

public class FutureTest {
    private static int nThreads = 20;

    public static void main(String[] args) {
        LinkedBlockingQueue taskQueue = new LinkedBlockingQueue(nThreads);

        ExecutorService executorService = new ThreadPoolExecutor(nThreads, nThreads,
                0L, TimeUnit.MILLISECONDS, taskQueue);


        Callable c = new Callable() {
            public Object call() throws Exception {
               Thread.sleep(3000);
               ReturnObject rt =  new ReturnObject();
                rt.setReturnName("serkan sunel");
                return rt;
            }
        };

        Future future = executorService.submit(c);
        try {
            Object returnObj = future.get(2000, TimeUnit.MILLISECONDS);
            System.out.println("returned :" + returnObj);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

    }
}





Monday, March 29, 2010

Flag Arguments & Clean Code

Flag arguments are ugly. Passing a boolean into a function is a truly terrible practice. It immediately complicates the signature of the method, loudly proclaiming that this function does more than one thing. It does one thing if the flag is true and another if the flag is false!


--Clean Code by Robert C. Martin

Concurrency Tips

Concurrency Tips Blog