I recently read the Building Maintainable Software book by Joost Visser and feel there is something they haven't discussed. The title hints as much, I do not know if following the guidelines have anything to do with field/attributes. The relevant guidelines:

-Write short units of code

-Keep your codebases small

Can I just have as many fields as I like/need? And how about comments and fields? Since comments are kind of forbidden when following the guidelines, does that also apply for fields?

有帮助吗?

解决方案

You haven't cited the actual content of those guidelines, so the question is hard to answer for people who do not have the book available. I'll try to answer more generally.

The important part with "guidelines" or "best practices" is to understand the reasoning behind them, to understand why they help to make code maintainable. If you understand that well, then you'll also be able to reason out how they apply to situations that are not mentioned explicitly, and - even more important - you'll know where they don't apply.

You can have as many fields as you need, but to make the code more maintainable, the number of fields should be limited. If you have too many fields in a class, the class is probably too big and does not follow the Single Responsibility Principle.

Another thing to do is to avoid misusing fields as hidden method parameters. If you have a field that is written only in method A, read only in method B, and A also calls B, then it should be a parameter of B instead of a field. This follows from the more general guideline to keep the scope of all state as small as possible to minimize the amount of state you have to think about at any given place.

As for comments, if those guidelines tell you they are "kind of forbidden" I really have to question their usefulness. It is true that comments can be bad if they are only a crutch to make badly structured code understandable instead of refactoring it to be easier to understand, but it's not really the comments that are the problem, it's the badly structured code. And comments are always inferior to code that needs no comments, because they tend to become outdated.

But if you have a field whose name cannot convey the necessary information to understand its meaning, and you cannot refactor the code to make it easier to understand (e.g. by using enums to specify and name the possible values), then you can and should most definitely comment a field with complex semantics.

许可以下: CC-BY-SA归因
scroll top