1

I have written a class in java which for a countdown clock. My class looks like this:

public class CountDown implements Runnable {

    ...

    @Override
    public void run() {

        // The functionality of the clock.

    }

    ...

}

Now, when I want to run a countdown from another class, I use this code

(new Thread(new CountDown(10))).start;

My question is:

Would it be better if I changed the class like this:

public class CountDown {

    ...

    public void start() {

        new Thread(new Runnable(){

            @Override
            public void run(){

                // The functionality of the clock.

            }

        ).start();

    }

    ...

}

And then call it from another class like this:

new CountDown(10).start();
Thanasis1101
  • 1,614
  • 4
  • 17
  • 28
  • 1
    First, please God, don't do the second as it's an abomination. – Hovercraft Full Of Eels Jan 19 '17 at 22:52
  • @Hovercraft Full Of Eels Ok. An explanation would be good though. – Thanasis1101 Jan 19 '17 at 22:57
  • 1
    1) you're making the class implement Runnable when it is not in fact Runnable. 2) You're making the code rigid by unnecessarily forcing implementation details on it. Now there is no way to use CountDown with newer concurrency constructs for instance. 3) The calling class has no control of or access to the Thread object... – Hovercraft Full Of Eels Jan 19 '17 at 22:59
  • 1) That was by mistake. I edited it now. 2, 3) I plan to add a stop method and then call this from the other class. Because I only want the other classes to be able to only start or stop the clock. – Thanasis1101 Jan 19 '17 at 23:07
  • ??? your stop method has nothing to do with this design question, and can and **should** be incorporated in the *true* Runnable. – Hovercraft Full Of Eels Jan 19 '17 at 23:09
  • My goal was to make it more simple for another class to start and stop the countdown, and not having to use Threads. But, ok. I'm convinced now that it is not good to hide the thread inside the class. Thank you for your time ! – Thanasis1101 Jan 19 '17 at 23:14

1 Answers1

2

I believe your first code snippet is the preferred solution, because you are not committing to a particular implementation. Thread is not the only implementation of Runnable (e.g. TimerTask, FutureTask, etc).

By having your CountDown use Thread in the implementation, you take away a great amount of control from anyone who uses your CountDown. See "implements Runnable" vs. "extends Thread"

ordonezalex
  • 2,645
  • 1
  • 20
  • 33