Accessing members in your own class: use (auto)properties or not?

前端 未结 6 1663
温柔的废话
温柔的废话 2021-01-22 21:16

I\'ve created this \"question\" as a community-wiki, because there is no right or wrong answer. I only would like to know how the community feels about this specific issue.

6条回答
  •  忘掉有多难
    2021-01-22 22:04

    I think it becomes more difficult to change the internal implementation if the code uses its own public interface.

    Difficult to explain but consider these expressions:

    mTotalPrice = mPrice * mQuantity;
    
    mTotalPrice = Price * Quantity;
    

    What to do in the second expression if I need to change the internals to express all prices in € instead of $ (without affecting the public interface which still uses $)?

    One solution is to make the expression more complex by adding the opposite of the change in the property.

    mTotalPrice = Price / Rate * Quantity
    

    The other solution is to start to use the private field instead.

    mTotalPrice = mPrice * Quantity
    

    In the end you get a mix of private and public use. The only way to get consistent use is to always use the private field.

提交回复
热议问题