Method Calling Public/Private Members or Methods Best Practice - C#.NET

后端 未结 2 1895
难免孤独
难免孤独 2021-01-18 12:26

What is the best practice for calling members/fields from a private method and public method? Should the private method always call private fields or should they call the pu

2条回答
  •  轮回少年
    2021-01-18 13:17

    I prefer to have all code go through the public interface, simply to reduce the number of places in the code that accesses the actual backing field. Two reasons are

    • Simplifies debugging; if you have an issue where a value is changed, or returns an unexpected value, you can set a breakpoint inside the property getter or setter and easily trap any access to the value.
    • Reduces impact of changes, you can make changes to the field and it will affect very few places in the code directly.

    Or, to put it in a single word: encapsulation.

提交回复
热议问题