Do getters and setters impact performance in C++/D/Java?

后端 未结 10 2347
无人及你
无人及你 2020-12-06 09:26

This is a rather old topic: Are setters and getters good or evil?

My question here is: do compilers in C++ / D / Java inline the getters and setter?

To which

10条回答
  •  抹茶落季
    2020-12-06 09:43

    I'll echo Xtofl.

    Getters and setters are one of those things that are sometimes useful, but you get these doctrinaire people who somehow leap from "has proven useful in some cases" to "must be used all the time and if you don't use it you are a heretic who should be killed".

    If you have side effects to a get or set, by all means use a getter or setter.

    But if not, writing getters and setters just clutters up the code. There's a small performance penalty. In Java, if it's only executed a few times, the perforance penalty shouldn't matter, and if it's executed frequently, it should be inlined so the penalty is mitigated. So I'd worry more about making the code harder to read.

    And don't for a minute buy the argument that this eliminates the problem of global data. Global data is bad and should be avoided. But declaring a member field private and then creating public getters and setters for does nothing to solve the problem.

提交回复
热议问题