我第一次遇到这种情况是这样的:一个 Box
类,其中包含一个包含项目的列表。所有这些项目都有一个 int Weight
实例变量。现在,要获取 Box
的重量,是否应该使用实例变量 weight
来跟踪它?或者您应该使用方法 calculateWeight()
来获取权重?
public class Box {
private ArrayList<Item> list; // Item objects in the list, all Item objects have a weight
private int weight; // Should I: use an instance variable as is seen here <- ?
public int calculateWeight() { // or use a method to calculate the weight each time?
int sum = 0;
// for all items get the weight and add it together
return sum;
}
}
现在在这个例子中,对我来说使用方法而不是实例变量更有意义,因为否则 Box
的实例变量 weight
必须每次添加或删除项目时都会更新。
但现在我正在开发一个可读性分数计算器(JetBrains 上的项目),我发现我应该做什么不太明显。可读性分数计算器获取文本并查找句子、单词、字符、音节等的数量,并使用简单的公式来计算可读性分数。目前,我一直在通过调用构造函数内部计算每个句子、单词、字符等的方法来将所有数量的句子、单词、字符等存储在实例变量中,但我不确定这是否是一个好的做法(感觉有点困惑)大部头书)。另一种方法是不将它们存储在实例变量中,而只在每次需要时使用这些方法来获取金额。这就是代码现在的样子:
public abstract class ReadabilityScoreCalculator {
protected String name;
protected String text;
protected int wordCount;
protected int sentenceCount;
protected int charCount;
protected int syllableCount;
protected int polySyllableCount;
protected double score;
protected int age;
public ReadabilityScoreCalculator(String text, String name) {
this.text = text;
this.name = name;
this.wordCount = this.countWords();
this.sentenceCount = this.countSentences();
this.charCount = this.countCharacters();
this.syllableCount = this.countSyllables();
this.polySyllableCount = this.countPolySyllables();
this.score = this.calculateAndReturnScore();
this.age = this.getAgeGroup();
}
private int countWords() {
return this.getArrayOfWords().length;
}
private String[] getArrayOfWords() {
return this.text.split("[ ]+");
}
private int countSentences() {
return this.text.split("[.!?]").length;
}
private int countCharacters() {
String textWithoutSpaces = this.removeSpaces();
return textWithoutSpaces.length();
}
private String removeSpaces() {
return this.text.replaceAll("[ ]+", "");
}
private int countSyllables() {
String[] words = this.getArrayOfWords();
int amountOfSyllables = Arrays.stream(words)
.mapToInt(word -> this.countSyllablesInWord(word))
.reduce(0, (previousCount, amountOfSyllablesInWord) -> previousCount + amountOfSyllablesInWord);
return amountOfSyllables;
}
private int countSyllablesInWord(String word) {
int amountOfSyllablesInWord = 0;
for (int i = 0, n = word.length(); i < n; i++) {
char character = word.charAt(i);
if (this.isCharVowel(character)) {
if (this.isCharVowel(word.charAt(i - 1)) || this.areWeAtTheLastCharAndDoesItEqualE(i, word)) {
continue;
}
amountOfSyllablesInWord++;
}
}
return (amountOfSyllablesInWord == 0) ? 1 : amountOfSyllablesInWord;
}
private boolean isCharVowel(char character) {
String charAsString = String.valueOf(character);
return charAsString.matches("(?i)[aeiouy]");
}
private boolean areWeAtTheLastCharAndDoesItEqualE(int index, String word) {
int wordLength = word.length();
char currentCharacter = word.charAt(index);
return (index == (wordLength - 1) && currentCharacter == 'e');
}
private int countPolySyllables() {
String[] words = this.getArrayOfWords();
int amountOfPolySyllables = Arrays.stream(words)
.mapToInt(word -> this.countSyllablesInWord(word))
.filter(amountOfSyllablesInWord -> amountOfSyllablesInWord > 2)
.reduce(0, (previousCount, amountOfPolySyllablesInWord) -> previousCount + amountOfPolySyllablesInWord);
return amountOfPolySyllables;
}
private double calculateAndReturnScore() {
return this.calculateScore();
}
abstract double calculateScore();
public void setScore(double score) {
this.score = score;
}
public void printResults() {
System.out.println(this.name + ": " + this.score + " (about " + this.age + " year olds).");
}
public void setAgeGroup() {
this.age = this.getAgeGroup();
}
private int getAgeGroup() {
int ageGroup = 0;
switch(this.roundUpAndParseToInt(this.score)) {
case 1:
ageGroup = 6;
break;
case 2:
ageGroup = 7;
break;
case 3:
ageGroup = 9;
break;
case 4:
ageGroup = 10;
break;
case 5:
ageGroup = 11;
break;
case 6:
ageGroup = 12;
break;
case 7:
ageGroup = 13;
break;
case 8:
ageGroup = 14;
break;
case 9:
ageGroup = 15;
break;
case 10:
ageGroup = 16;
break;
case 11:
ageGroup = 17;
break;
case 12:
ageGroup = 18;
break;
case 13:
ageGroup = 24;
break;
case 14:
ageGroup = 24;
break;
}
return ageGroup;
}
public int roundUpAndParseToInt(double number) {
return (int) Math.ceil(number);
}
}
其中之一是否被视为良好实践?还是真的要视情况而定?我可以看到该方法的计算成本更高,但提供了更多的确定性。我上面的代码的任何其他问题也可能会被指出。
编辑:这是一个抽象类,calculateScore()
方法应该由继承自该类的类填充。因此,可以使用多个不同的公式来计算可读性分数。
最佳答案
一般来说,忽略使用基于计算的实例变量,而使用检索方法。更重要的是你的代码文档本身是否简洁并且易于维护。
通过使用实例变量,每次修改它们各自的属性时都需要更新它们,这可能会降低修改这些变量的方法的可读性。
例如,下面是一些修改list
并更新weight
成员变量的简单方法:
public void addItem(Item item) {
this.list.add(item);
this.weight += item.weight;
}
public Item removeItem(int i) {
Item item = this.list.remove(i);
this.weight -= item.weight;
return item;
}
public void setList(ArrayList<Item> list) {
this.list = list;
this.weight = this.calculateWeight();
}
由于您正在执行方法名称中未描述的附加操作,因此这些方法不是自文档化的。您可以将它们称为 addItemAndUpdateWeight()
之类的名称,但如果还有更多成员变量需要更新怎么办? addItemAndUpdateMemberVariables()
太模糊了,很快这些方法就会变得非常困惑并且难以维护。
您可以添加一个辅助函数来更新您的成员变量,但您仍然需要在每个此类方法中调用它,并且每次添加新的成员变量时,您都必须也更新这个方法。
另外,如果这些方法成本高昂,最好仅在需要时执行计算。
更好的解决方案是通过隔离方法的功能来保持简单:
public void addItem(Item item) {
this.list.add(item);
}
public Item removeItem(int i) {
return this.list.remove(i);
}
public void setList(ArrayList<Item> list) {
this.list = list;
}
您立即就清楚地知道这些方法的作用,并且不会有任何偷偷摸摸的代码让您以后感到头疼。另外,现在您不需要在构造函数中执行这些操作。
我确信可以为更复杂的情况(例如索引)建立一个案例,但这似乎超出了本讨论的范围。
关于java - 将属性存储在实例变量中还是使用方法来计算它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61915011/