Can fields be added to the class that serve only to improve the readability of the code?



  • I have a class, it eats this field:

    private ArrayList<ArrayList<Long>> costs = new ArrayList<>();
    

    Further, in all cycles, I have many in this class, use the following designs:

    for (int i = 0; i < costs.get(row).size(); i++)
    

    or so:

    for (int i = 0; i < costs.size(); i++)
    

    Would it be better if I added two fields?

    private int costsSize;
    private int costsRowSize;
    

    I'll use them all over the cycles. I'm asking because they don't have any extra sense of load, you can get around without them. But the code will make it shorter and clearer. I also have a ghetter in this class that just returns the size (because this size is also needed in the outer code).

    public int getCritCount() {
        return costs.size();
    }
    

    Should we use it as a cycle? But I think the best would be the field of class. To make them conditional is less processor time than it takes every time to give them a method. But I can't get away from thinking that they don't make sense, and they don't describe the condition of this object.



  • It's weird to start fielding because you're basically producing information that's already stored in the collection. If the size goes away, you'll get either a collection going abroad or a partial rounding of the collection. It's more harm than good.

    The problem with the ghetters is that the oblivious logic of the complete flow of the collection is now dependent on the challenge of the method. Design for (int i = 0; i < costs.size(); i++) { ... costs[i] ... } is clear and recognised at first sight. Design for (int i = 0; i < getCostsSize(); i++) { ... costs[i] ... } - Not anymore.

    Personally, I wouldn't be fascinating with the ghetters, either using your code as it is or adding local variables. Some micro-optimizer can detect and say it's calling. costs.get(row).size() The cycle is not good.

    If you were using C#, I'd advise you to use a two-size mass unless you change the size of the table. Or you could use classes to work with the matrices, as recommended in the comments.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2