Are protected members/fields really that bad?

前端 未结 6 1597
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 02:33

Now if you read the naming conventions in the MSDN for C# you will notice that it states that properties are always preferred over public and protected fields. I have even

6条回答
  •  孤城傲影
    2020-11-29 02:49

    OK, downvote time.

    • First of all, properties will never hurt performance (provided they don't do much). That's what everyone else says, and I agree.

    • Another point is that properties are good in that you can place breakpoints in them to capture getting/setting events and find out where they come from.

    The rest of the arguments bother me in this way:

    • They sound like "argument by prestige". If MSDN says it, or some famous developer or author whom everybody likes says it, it must be so.

    • They are based on the idea that data structures have lots of inconsistent states, and must be protected against wandering or being placed into those states. Since (it seems to me) data structures are way over-emphasized in current teaching, then typically they do need those protections. Far more preferable is to minimize data structure so that it tends to be normalized and not to have inconsistent states. Then, if a member of a class is changed, it is simply changed, rather than damaged. After all, somehow lots of good software was/is written in C, and that didn't suffer massively from lack of protections.

    • They are based on defensive coding carried to extremes. It is based on the idea that your classes will be used in a world where nobody else's code can be trusted not to goose your stuff. I'm sure there are situations where this is true, but I've never seen them. What I have seen is situations where things were made horribly complicated to get around protections for which there was no need, and to try to guard the consistency of data structures that were horribly over-complicated and un-normalized.

提交回复
热议问题