Alex Rivera | Logout

Are set-only properties bad practice?

Asked 2010-12-30T17:50:17.397
9

I have some C# code that loves to create properties that have setters but no getters. To me this seems like an anti-pattern, but am I missing something?

public List<SiteVisitSummary> DataSource {
    set {
        // crazy logic here 
    }
}
Edit
Report

1 Answer

21

I don't know if I'd call it an anti-pattern or not. I think the important thing to realize is that the property in your example is essentially a method, disguised as a property. For this reason it's unintuitive, and I'd generally avoid it. To me this looks a lot more natural:

public void SetDataSource(IEnumerable<SiteVisitSummary> dataSource)
{
    // crazy logic here
}

One fairly reasonable case I have seen made for set-only properties is when there are several properties grouped together such that setting all to a single value is a reasonable thing to do (but obviously, getting all as one value doesn't make sense). For example:

class Polyhedron
{
    public int Height { get; set; }
    public int Width { get; set; }
    public int Depth { get; set; }

    public int AllDimensions
    {
        set { Height = Width = Depth = value; }
    }
}
answered 2010-12-30T17:55:17.340

Your Answer