Mark Needham

Thoughts on Software Development

C#: Properties vs Methods

with 7 comments

I was browsing through our tests today and noticed a test along these lines (simplified for example purposes):

[Test, ExpectedException(typeof(Exception))]
public void ShouldThrowExceptionIfNoBarSet()
{
    var bar = new Foo(null).Bar;
}
public class Foo
{
	private readonly string bar;
 
	public Foo(string bar)
	{
    		this.bar = bar;
	}
 
	public string Bar
	{
    		get
    		{
        		if (bar == null)
        		{
            		throw new Exception("No bar");
        		}
        		return bar;
    		}
	}
}

What I found strange here is that ‘bar’ is never used and Resharper points out as much. If we try to remove it, however, the code no longer compiles.

[Test, ExpectedException(typeof(Exception))]
public void ShouldThrowExceptionIfNoBarSet()
{
    new Foo(null).Bar;
}
Only call, assignment, increment, decrement, and new object expressions can be used as a statement.

We therefore need to assign the call to Bar to a variable even though we never intend to reference it.

This problem wouldn’t happen if Bar was a method instead.

[Test, ExpectedException(typeof(Exception))]
public void ShouldThrowExceptionIfNoBarSet()
{
    new Foo(null).Bar();
}
public string Bar()
{
    if (bar == null)
    {
        throw new Exception("No bar");
    }
    return bar;
}

Which got me thinking how do we know when to use a method and when to use a property?

Clearly if there are parameters to be passed in then we have no choice but to use a method since we can’t call properties with parameters.

If we are simply returning data values then we might as well just use properties since this is what they were made for. We can even make use of automated properties to smooth the process.

Which leaves the situation where there is some logic that needs to be calculated, no outside data is needed to do this calculation and a result is returned to the client.

Probably because of the Java influence my preference would be to do this using a method but I don’t really have any other justification for not using a property to achieve the same thing.

Discussing this briefly with Dave we thought maybe if a property is used then the execution needs to be idempotent (i.e. return the same result every time) although the argument could be made that well written methods should also be side effect free. Eric Evans’ advocates writing side effect free functions in Domain Driven Design for example.

Does anyone have any compelling reasons why or why not to use one or the other?

Written by Mark Needham

February 11th, 2009 at 11:20 am

Posted in .NET

Tagged with ,

  • mike

    i always favor properties due to readability … i consider the extra parenthesis noise … would love to remove them from methods with no args too

  • http://www.JeremyJarrell.com Jeremy

    I like methods when the retrieval of the value is non-trivial. For example, customer.AccountNumber is likely already stored on the client or at least would be a quick trip to get. Conversely, customer.GetOutstandingDebts() likely requires a trip back to the datalayer to retrieve some info and then possibly some calculations on the data client side before it’s ready to be returned. This also falls inline with your commend about properties being idempotent, since the result GetOutstandingDebts() may vary in the same session.

    Short answer is if it’s a cheap operation I like a property, if it’s a potentially expensive operation I like a Get*() method as a warning that this could take some time.

  • Jeremy Gray

    I’ve read and am a fan of Evans’ DDD book but do admit finding the encouragement to write side-effect-free functions to be a bit of an odd one given the subject matter of the book. Pure side-effect-free functions are the antithesis of OO (as you have functional over here and OO way over there), and OO is very much at the core of DDD. Evans also argues for clear CQS, which IMHO makes more sense and fits DDD far better than functional purity would.

    Personally I feel there is a time for both styles and that, in fact, things often go the best when you use both at the same time, pushing each type to their very extremes: functional pieces which are very pure and free from side-effects + OO pieces that are hallmarks of good CQS, avoidance of Tell, Don’t Ask violations, etc.

    As for “the argument could be made that well-written mothods should also be side effect free.” I’d be tempted to suggest that while that is true for a functional style it will be equally untrue for an OO style and that, if anything, (to paraphrase in response to the overall subject of properties versus methods) the argument could be made that well-written class should also be free of getters and setters, whether in property or method form. Put that in your pipe and smoke it. ;)

  • Pingback: Arjan`s World » LINKBLOG for February 11, 2009

  • Foo

    I’m generally not a big fan of FXCop, but I think its correct on its guidelines for function vs. property. Properties generally look like really simple things to clients of a service, and they generally do things like:

    for (int i = 0; i < collectionThingy.Count; i++)

    The problem with that code is that if the count code is going to be called repeatedly and if its costly it could be very very expensive for what is probably an unchanging value.

    Whereas

    for (int i =0; i < collectionThing.CalculateCount(); i++)

    Is going to point out that the computer is actually doing something that might be costly and most clients will write that as:

    int count = collectionThing.CalculateCount();
    for (int i =0; i < count; i++)

    And do what looks like it might be costly just the one time.

    For this reason, I try to use properties when the operation is very light. Functions should do the heavy lifting.

    Oh and btw that thing about having to use functions if you want parameters isn’t necessarily correct:

    var adder = new Adder();
    adder.FirstValue = 3;
    adder.SecondValue = 5;
    var sum = adder.CalculatedValue;

    Not sure if you’d ever want to do that… but you could.

  • Foo

    One last thing… that bit about idempotent.

    Not sure I buy it.

    iterator.Next

    Is a pretty good property most of the time and it will generally return a different value every time.

  • Justin

    properties are a trade off for me

    the pro: makes coding accessor/mutator pair feel less redundant (not the word “feel”)

    the con(s): you’re doing the same task but just saving yourself a dozen keystrokes for each pair, they aren’t doing anything else from how I see it. (They just create the get/set methods just how you would, at the CIL level).

    so… it appears to be somewhat of wash… except for all those programmers from every other language that shouldn’t have learn another new pointless trick!

    Summary: If your code stays amongst an all C# team, they are a tiny shortcut. Otherwise (sample code, teaching) your better off skipping it.

    btw, I see some comments above along performance lines above. I would expect the compiler to take of those details, I don’t profess to know csc is a “good” compiler though.