Again as with my code reviews, one of the things I noticed in many classes is that they all have properties with only set accessors, but either no get accessor at all or with a private get accessor.

Although if you think for a sec, it sounds good to have many times a writable property but not readable. In fact, even I had the same notion many a times while writing code so far. But one thing I realized or learned today that such a feature is really not needed or its kind of not worthy to have in your code. The reason is simple that consumer code using your property can set a value for your private variable, so when he can set a value that means he already knows the value, so why to make your property a read only?

As of now, you may think that “OK? but what if I change this private variable's value once the consumer code sets a value to it”. Let me show that in code:

class CustomClass
{
    private string _someValue;
    
    public string MyProperty
    {
        set
        {
            _someValue = value;
        }
    }
    
    public void SomeMethod()
    {
        if (!string.IsNullOrEmpty(_someValue))
        {
            //Do some operations
           _someValue = string.Concat(_someValue, " some other values");
        }
    }
}

class TestClass
{
    public void TestMethod()
    {
        CustomClass cs = new CustomClass();
        cs.MyProperty = "My values";
        
        cs.SomeMethod();
    }
}

If you are planning to do this, then you are having a flawed design actually. When you are receiving a value from consumer into your class, then you should not change it or use it to store it, rather use other member to store the data. This way, a guy who is having rights to set a data will also have rights to get (read) a data. That way, you shall have a better design implemented. Because if you do not do this, later on, if consumer calls a method which may return this set value along with other data (say as a List<TVal>), then you are giving the consumer code wrong information.

Along with this, I do not see any better security added to your data in your class at all, right? Think for a moment. The only reason you implement properties to have a better security is mostly for not giving writable access. But here in this case, you already gave away the most critical part of the security and now you are trying do a small work in making it secure which is not really useful.

Hope it helps, your comments are welcome.

Happy coding, thanks. :)


Filed under: C#, CodeProject, Dotnet Tagged: .NET, blog, C#, codeproject, Dotnet, tips
推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"