使用多种方法使类更易读

问题描述 投票:0回答:1

我的网格超类已经变得越来越大,有许多公共方法,我试图弄清楚如何将其分解以使其变得更易于管理。方法分为几类,以下方法用于获取索引信息:

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;
    }
  }
}
java processing
1个回答
0
投票

您可以从定义一些方法的抽象类开始,然后通过添加更多方法对其进行增强(从中派生)。

本教程介绍抽象类:https://www.javatpoint.com/abstract-class-in-java

但是除非您具有从相同抽象库派生的不同类,否则我不会这样做。我认为拥有大型源代码文件没有问题。每个IDE都提供许多功能来快速导航,无论该类有100行还是3000行。

© www.soinside.com 2019 - 2024. All rights reserved.