How important are naming conventions for getters in Java?

前端 未结 6 1959
孤城傲影
孤城傲影 2021-02-08 10:12

I’m a huge believer in consistency, and hence conventions.

However, I’m currently developing a framework in Java where these conventions (specifically the get

6条回答
  •  时光说笑
    2021-02-08 10:56

    I actually hate this convention. I would be very happen if it was replaced by a real java tool that would provide the accessor/modifier methods.

    But I do follow this convention in all my code. We don't program alone, and even if the whole team agrees on a special convention right now, you can be assured that future newcomers, or a future team that will maintain your project, will have a hard time at the beginning... I believe the inconvenience for get/set is not as big as the inconvenience from being non-standard.


    I would like to raise another concern : often, java software uses too many accessors and modifiers (get/set). We should apply much more the "Tell, don't ask" advice. For example, replace the getters on B by a "real" method:

        class A {
          B b;
          String c;
          void a() {
            String c = b.getC();
            String d = b.getD();
            // algorithm with b, c, d
          }
        }
    

    by

        class A {
          B b;
          String c;
          void a() {
            b.a(c); // Class B has the algorithm.
          }
        }
    

    Many good properties are obtained by this refactor:

    • B can be made immutable (excellent for thread-safe)
    • Subclasses of B can modify the computation, so B might not require another property for that purpose.
    • The implementation is simpler in B it would have been in A, because you don't have to use the getter and external access to the data, you are inside B and can take advantage of implementation details (checking for errors, special cases, using cached values...).
    • Being located in B to which it has more coupling (two properties instead of one for A), chances are that refactoring A will not impact the algorithm. For a B refactoring, it may be an opportunity to improve the algorithm. So maintenance is less.

提交回复
热议问题