本文介绍了Java(匿名与否)内部类:使用它们是否合适?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一些项目和一些书中被称为使用内部类(匿名或不是静态或非静态) - 除了在某些限制条件下,例如 EventListener s或 Runnable s - 是最佳做法。他们甚至在我的第一个行业项目中都是禁止。

In some of my projects and in some books was said to not use inner class (anonymous or not, static or not) - except in some restricted conditions, like EventListeners or Runnables - is a best practice. They even were 'forbiden' in my first industry project.

这真的是最佳做法吗?为什么?

Is this really a best practice? Why?

(我不得不说我经常使用它们......)

(I have to say that I'm using them a lot...)

- - 编辑---

我无法在所有这些答案中选择正确的答案:大部分都是正确的部分:我仍然会使用内部类,但我会尝试使用他们不那么经常!

-- EDIT ---
I can't pick a right answer in all these responses: there's part of rightness on mostly all of them: I'll still use inner classes, but I'll try to use them less often !

推荐答案

在我看来,Java代码中90%的内部类是与单个类关联的实体,因此作为内部类,或者因为Java不支持Lambdas而存在的匿名内部类被推入。

In my view, 90% of inner classes in Java code are either entities that are associated with a single class and were thus "shoved in" as inner classes, or anonymous inner classes that exist because Java does not support Lambdas.

我个人不喜欢看到复杂的内部类。它们增加了源文件的复杂性,它们使它更大,在调试和分析等方面处理它们很难。我喜欢将我的项目分成许多包,在这种情况下我可以使大多数实体成为顶级类限制在包中。

I personally don't like seeing complex inner classes. They add complexity to the source file, they make it bigger, they're ugly to deal with in terms of debugging and profiling, etc. I like separating my project into many packages, in which case I can make most entities top-level classes that are restricted to the package.

这给我留下了必要的内部类 - 例如动作监听器,虚假的功能编程等等。这些通常是匿名的,而我我不是粉丝(在很多情况下会更喜欢Lambda),我和他们住在一起却不喜欢他们。

That leaves me with necessary inner classes - such as action listeners, fake "functional" programming, etc. These are often anonymous and while I'm not a fan (would have preferred a Lambda in many cases), I live with them but don't like them.

我没有做任何C#in几年,但我想知道在引入Lambdas时,内部类的流行程度或C#等价物的流行是否会被删除。

I haven't done any C# in years, but I'm wondering if the prevalence of inner classes or whatever the C# equivalent is dropped when they introduced Lambdas.

这篇关于Java(匿名与否)内部类:使用它们是否合适?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 23:56