Is it a good practice to implement logic in properties

前端 未结 8 671
傲寒
傲寒 2021-02-05 02:39

we use ASP.NET with C# and based on open source projects/articles I passed through, I found many properties were including a logic but when I did so the team-le

8条回答
  •  -上瘾入骨i
    2021-02-05 03:12

    Placing business logic in a setter can get you in trouble if you ever have the need to serialize/deserialize your objects with JSon, XML or an ORM. An example of this may be when using a NoSql datastore like a document database or an ORM. Some of these (e.g. NHibernate) can be configured to access backing fields instead of the setter.

    I find that using a public Getter and Private setter along with a method to set the value with additional logic as required is a good approach. Most serializers can access the private setter so what you end up with is an accurate representation of the persisted object without accidentally firing logic that could potentially change values incorrectly when deserialized.

    However, if you don't think there will ever be a need to serialize/deserialize then this shouldnt be an issue.

提交回复
热议问题