一个类最终将其所有方法和字段公开在同一级别下,并且变得极其无组织。
最好将它组织在专门的子类中。下面是一个凌乱类的示例。
public class MyClass
{
//[Properties]
public String value1;
public String value2;
//[Methods used by outside world]
public void job1()
{
job1_task1();
job1_task2();
utilInternal1();
utilExternal1();
}
public void job2()
{
job2_task1();
utilInternal1();
utilExternal1();
}
//[Methods used locally and always specific to a job method]
private static void job1_task1() ...
private static void job1_task2() ...
private static void job2_task1() ...
//[Methods used locally and general to jobs methods]
private static void utilInternal1() ...
//[Methods that could be added to an external class util]
public static void utilExternal1() ...
}
到目前为止,我已经将我的代码组织在子专业类中,例如Props,Jobs,Tasks,Utils.Internal,Utils.Externals。
实例类,如Jobs和Props。通过两个实例字段公开。他们将直接使用实例变量。
静态类可以直接使用,例如Tasks和Utils。他们不会直接使用实例变量。
public class MyClass
{
public Prop Props = new Prop();
public Job Jobs = new Job();
//[Properties]
private class Prop
{
public String value1;
public String value2;
}
//[Methods used by outside world]
public class Job
{
public void job1()
{
Tasks.Job1.task1();
Tasks.Job1.task2();
Utils.internal.util1();
Utils.external.util1();
}
public void job2()
{
Tasks.Job2.task1();
Utils.internal.util1();
Utils.external.util1();
}
}
//[Tasks for Jobs]
private static class Tasks
{
//[Tasks for job1]
private static class ForJob1
{
private static void task1() ...
private static void task2() ...
}
//[Tasks for job2]
private static class ForJob2
{
private static void task1() ...
}
}
private static class Utils
{
//[methods util used locally]
private static class Internal
{
private static void util1() ...
}
//[methods util generic that could be added to an external class Util]
private static class External
{
public static void util1() ...
}
}
}
我使大多数子类都静态化,这些子类包含不得直接使用类变量的方法,相反,它们将要求它们作为参数。 任务对外部类没有用,只在我们的类中具有局部意义。
private static Task
{
private static ForJob1
{
private static String task1(String value)
{
String result = value + ".";
return result;
}
}
}
这是可以接受的吗?
我还担心内存使用情况吗?