是否应该将Java中的静态嵌套类重构为单独的类? [英] Should I refactor static nested classes in Java into separate classes?
问题描述
我继承了包含静态嵌套类的代码,如下所示:
I have inherited code which contains static nested classes as:
public class Foo {
// Foo fields and functions
// ...
private static class SGroup {
private static Map<Integer, SGroup> idMap = new HashMap<Integer, SGroup>();
public SGroup(int id, String type) {
// ...
}
}
}
通过阅读SO的内容(例如 Java内部类和静态嵌套类)我相信这等效于两个单独文件中的两个单独类:
From reading SO (e.g. Java inner class and static nested class) I believe that this is equivalent to two separate classes in two separate files:
public class Foo {
// Foo fields and functions
// ...
}
和
public class SGroup {
static Map<Integer, SGroup> idMap = new HashMap<Integer, SGroup>();
public SGroup(int id, String type) {
// ...
}
}
如果这是正确的话,那么维护静态嵌套类结构是否有任何优势?或者我应该重构吗?
If this is correct is there any advantage to maintaining the static nested class structure or should I refactor?
推荐答案
Jorn语句是正确的,通常以以下经验法则表现出来:
Jorn statement is correct and it's usually manifests itself as the following rule of thumb:
嵌套类应该设为私有,这意味着对宿主类的持有辅助逻辑仅此而已.如果您不能将它们设为私有,则可能不应嵌套.
Nested classes should be made private, Meaning that the hold auxiliary logic for the hosting class and nothing more. If you cant make them private- thet probably should not be nested.
例外是,当您定义一个嵌套类以允许轻松访问托管类的状态时,在这种情况下,您应该考虑简单地合并两个类以增加内聚力.
The exception is when you define a nested class to allow easy access to the state of the hosting class, in that case you should consider simply merging both classes to increase cohesion.
这篇关于是否应该将Java中的静态嵌套类重构为单独的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!