如何组合两个具有相同计算但运行(读取和写入)类的不同字段的方法。 一个非常简化的aircode例如:如何将两种方法结合在一起计算但字段不同
class TileCalculator
{
int length;
int width;
int tileLength;
int tileWidth
int cols;
int rows;
void calculateColumns()
{
this.cols = this.width/this.tileWidth;
}
void calculateRows()
{
this.rows = this.length/this.tileLength;
}
}
由于上述两种方法做同样的计算(一个或多个),但只是用他们的输入和输出不同的领域它似乎明智的把它们结合在一起,但我不知道如何。
更新:我想我可能已经过于简单化了,直至答题者正试图解决具体案例。一个更现实的例子是:
void calculateCols()
{
int tileCols = width/tileWidth;
int remainder = width%tileWidth;
if (remainder==0) {
// there is an exact number of whole tiles
fullTileCols = tileCols;
firstT = tileWidth;
usedTileCols = tileCols;
} else {
// there is a remainder
fullTileCols = tileCols - 1;
firstT = (remainder+tileWidth)/2;
usedTileCols = tileCols + 1;
}
}
void calculateRows()
{
int tileRows = length/tileLength;
int remainder = length%tileLength;
if (remainder==0) {
// there is an exact number of whole tiles
fullTileRows = tileRows;
firstCut = tileLength;
usedTileRows = tileRows;
} else {
// there is a remainder
fullTileRows = tileRows - 1;
firstCut = (remainder+tileLength)/2;
usedTileRows = tileRows + 1;
}
}
我不是说重新设计不是答案,但你可以看到有涉及这么简单return
值大概是不会削减它的多个领域。这就是为什么我使用字段而不是简单的函数,而且当前设置的可维护性是我关心的。
如果您的公式是要复杂得多,你可以定义一个表示数学的方法matical函数并传递参数。现在,这真的不值得。 – Zong
只需创建第三个函数并传递将结果存储为参数的位置。 – Babblo
@宗正立计算更复杂,有多个返回值。请参阅更新的示例。 – Caltor