Bad practice to use Runnable as callback / subroutine?

橙三吉。 提交于 2019-12-10 01:36:29

问题


Is it's considered bad practice to use Runnable as a callback?

Considering that Runnable is meant to be used with threads (see it's JavaDoc), I'm wondering if this is okay - or whether I should make my own interface for this purpose.

What I'm talking about is something like:

public class KeyBinding {
    public KeyBinding(KeyStroke stroke, Runnable handler) {
        //...
    }
}

回答1:


Actually, Runnables can be used for any purpose.

"The general contract of the method run is that it may take any action whatsoever"(Runnable javadoc)

Generally, it should not be bad practice, definitely better practice than creating an extra unnecessary interface in your own code.




回答2:


Don't use Runnable as a callback; it might cause confusion: people and code quality tools sometimes expect it to be used with threads only.

I did myself use Runnable as a callback — I thought it seemed fairly well suited for use as a generic callback. A month later someone found my code snipped:

doneCallback.run();

and he noticed that the doneCallback was a Runnable, and that invoking .run() directly resulted in a warning in our code quality analysis program (Sonar). So, to fix the warning?, or because he thought the intention was to create a thread?, he forked a new thread, and called run() via that thread instead.

However, forking a thread there, broke stuff.

To avoid confusion, now I'm instead creating a generic callback interface that's not related to threads in any way. I'm just adding a class Callback with a method call. I think I'd better not use java.util.concurrent.Callback because that one is related to threads too.



来源:https://stackoverflow.com/questions/22723599/bad-practice-to-use-runnable-as-callback-subroutine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!