在Java中使用匿名类被认为是坏样式还是好? [英] Is usage of anonymous classes in Java considered bad style or good?

查看:123
本文介绍了在Java中使用匿名类被认为是坏样式还是好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道匿名类保存输入,当谈到实现Listener和类似的东西。

I know anonymous classes save typing when it comes to implementing Listener and similar stuff. They try to be a replacement for some usages of closures.

但是社群对这种语言特征的价值有什么看法呢?它有意义,你经常使用它吗?它是否使代码更清晰,更易于理解和更易于维护?

But what does the community think about the value of this language-feature? Does it make sense and do you use it regularly? Does it make the code clearer, more understandable and more maintainable? Or do anonymous classes make the code less readable?

您的意见是什么,请提供实例/参数以方便您的意见?

What is your opinion, and please have examples/arguments handy to support your opinion?

推荐答案

我倾向于使用匿名内部类,在我不需要有一个完整的类只是执行一些任务的情况下。例如,如果我想实现一个 ActionListener Runnable ,但我不认为有一个内部类必要。例如,对于启动一个简单的 Thread ,使用匿名内部类可能更易读:

I tend to use anonymous inner classes in situations where I don't need to have a full-blown class just to perform some task. For example, if I want to implement an ActionListener or Runnable, but I don't think having an inner class would be necessary. For example, for starting a simple Thread, using an anonymous inner class might be more readable:

public void someMethod()
{
    new Thread(new Runnable() {
        public void run()
        {
            // do stuff
        }
    }).start();
}

在某些情况下,例如上面的例子,对于一次性任务,因为要执行的代码全部写在一个地方。使用内部类将离域代码:

In certain cases, such as the example above, it can increase readability, especially for one-time tasks, as the code that is to be executed is all written in one spot. Using an inner class would "delocalize" the code:

public void someMethod()
{
    new Thread(new MyRunnable()).start();
}

// ... several methods down ... //

class MyRunnable implements Runnable
{
    public void run()
    {
        // do stuff
    }
}


$ b b

然而,如果有相同的事情要重复的情况,它应该是一个单独的类,不管是普通类还是内部类。

That said, however, if there is going to be cases where the same thing is going to be repeated, it should indeed be a separate class, be it a regular class or an inner class.

我倾向于在程序中使用匿名内部类,我只是尝试事情,而不是将其作为实际应用程序的中心功能。

I tend to use anonymous inner classes in programs where I am just trying things out rather than have it as a central feature of an actual application.

这篇关于在Java中使用匿名类被认为是坏样式还是好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆