java - 用许多方法分解一个类以提高可读性
问题描述
我的网格超类已经变得很大,有许多公共方法,我试图弄清楚如何将它分解以变得更易于管理。方法分为几类,以下方法用于获取索引信息:
class grid{
int tot, cols, rows;
float gw, gh, w, h,gx,gy,gcx,gcy;
ArrayList<cell> cells = new ArrayList<cell>();
grid(float width, float height, int cols, int rows){
this.gx = 0;
this.gy = 0;
this.gw = width;
this.gh = height;
this.cols = cols;
this.rows = rows;
w = gw/float(cols);
h = gh/float(rows);
}
// how to move these methods somewhere else?
int rc(int row, int col){ // get index at row# col#
int val = 0;
for(int i = 0; i < cells.size(); i++){
if(cells.get(i).row == row && cells.get(i).col == col){
val = i;
}
}
return val;
}
int col(int inst){
if(altFlow == 1){
return floor(inst/rows);
} else {
return inst%cols;
}
}
int[] listRow(int indexIn){
int stIndex = cols*indexIn;
int[] arrayOut = new int[cols];
for(int i = 0; i < cols; i++) arrayOut[i] = i+stIndex;
return arrayOut;
}
}
我的想法是使用组合,但我仍然需要主类中的每个函数的方法?这是最好的方法吗?
class grid{
gridInfo gi;
...
//still need one of these for each method?
int col(int inst){
return gi.col(inst);
}
}
class gridInfo(){
grid parent;
...
int col(int inst){
if(altFlow == 1){
return floor(inst/parent.rows);
} else {
return inst%parent.cols;
}
}
}
解决方案
您可以从定义一些方法的抽象类开始,然后通过添加更多方法来增强它(从它派生)。
本教程解释抽象类:https ://www.javatpoint.com/abstract-class-in-java
但是我不会这样做,除非你有从同一个抽象基派生的不同类。我认为拥有大型源代码文件没有问题。每个 IDE 都提供了许多快速导航的功能,无论该类有 100 行还是 3000 行。
推荐阅读
- java - Intellij json片段问题与文本块
- r - 如何在 R 上的 data.frame 中添加新的多行?
- android - 错误:格式指定类型“int”,但参数的类型为“size_t”(又名“无符号长”)[-Werror,-Wformat]
- arrays - 如何在不知道c中大小的情况下遍历数组
- python - 在 django 中导入静态文件时出现问题?
- python - 如何随后将函数参数传递给 lambda 函数
- python - ESL 学校的 Django 模型
- php - 使用 MySQL 在选择/查看时翻转表内容?
- content-management-system - 使用带有 Moqui 的 Jackrabbit 的 JCR 内容 - 没有为 {http://www.jcp.org/jcr/1.0} 数据找到匹配的属性定义):
- java - java.lang.NoClassDefFoundError:解析失败:Lorg/spongycastle/util/Strings Android Studio