views:

271

answers:

10

Which is the better practice and why?

bool IsTodayMonday { get { return DateTime.Now.DayOfWeek == DayOfWeek.Monday; } }

Or

bool IsTodayMonday()
{
    return DateTime.Now.DayOfWeek == DayOfWeek.Monday;
}
+3  A: 

Generally:

If you're using a language where option #1 is legal, then you should use it. It increases readability and it's made for exactly this kind of job.

If you can't use option #1, you should use get/set methods; ie.:

bool getIsTodayMonday()
void setIsTodayMonday(bool timetravelingArgument)

Your example specifically

I think you can come up with arguments for both, though I'd go with option #2 as fields (in my view) shouldn't do too many calculations (except for validation and maybe transformation).

cwap
Confused, you start off by saying use the first then say you would use the second?
maxp
I'm confused about your question as well ^^ Do you mean "which of the following should I generally use" or "in the case of this method, which should I choose?". I'll edit to clarify my intend..
cwap
+6  A: 

A property should be a fairly trivial wrapper for a value. To the user of a property, it should act just like a variable.

If it does any amount of work, has side effects (e.g. reading/writing it changes some other state in your class), or if it might fail (e.g. throw exceptions) then it is better to write it as a Get method, so that the caller can see that it is not just a simple value.

Beyond that, it's more down to personal preference (whether you feel Properties should only represent concrete member variables, or whether they can be used to read "calculated values" such as the one in your example).

Jason Williams
+1  A: 

For me, I would say IsTodayMonday feels more like a method than a property so I would go with the second option See http://stackoverflow.com/questions/1294152/method-vs-property-in-c-whats-the-difference/1294189#1294189 for a good example of when to use properties over methods.

David G
+6  A: 

In my opinion, use properties in these situations unless:

  • The call is expensive, e.g. database calls are being made
  • There are side-effects when calling the property, e.g. other variables are being set as well
  • Calling the property multiple times yields different results
  • Your property is only used to set values

In your example, I would go with a property.

Razzie
+1 for "side effects"
Achim
How about DateTime.Now for point 3
Chris S
Good one! Of course, there are exceptions to every rule. And I'm no position to question the framework designer's choices :-)
Razzie
I wouldn't say DateTime.Now really breaks point 3. They way I interpret point 3 is that it should return the same value if the object is in the same state. Obviously DateTime.Now returns different because the "object" state has changed.
Stephan
+1  A: 

I would choose depending on what you want to communicate to the user and what's going on in the method. In your example I would probably go for the first version. If the calculation is more complex, I would go for the second version.

Or from a users point of view: I would not mind accessing obj.IsTodayMonday multiple times, because I would assume that it does not need heavy calculations. In case of obj.IsTodayMonday() I would think about caching and reusing the result.

But that's of course the way I write code. It depends on your policies.

Achim
+1  A: 

Clock.IsTodayMonday suggests to me that this has no side-effects or computations.

Clock.IsTodayMonday() indicates that there may side-effects or computations.

In your case, IsTodayMonday maybe appropriate, but as it goes and queries the system clock, it may be more appropriate to call it IsTodayMonday().

A more complex example maybe PrimeFactors. If you had a property of an integer called PrimeFactors, it would indicate to me that you could call it time and time again without any performance hit. However, if there were a method called PrimeFactors() then I'd probably use a temporary variable to cache the result if I needed it more than once, especially in a tight loop.

David Kemp
Nice, +1. That's my feeling too. In Ruby, strangely, we don't differentiate, and it drives me mad.
Yar
+7  A: 

To me - in this special case - it doesn't matter at all.

If you take a look at the generated IL-code you'll notice it is exactly the same. The Property will cause a method to be created which produces the same IL code.

In regards to the .Net implementations, you should probably use the property. The .Net framework uses properties for IsXXX-Functionality when no parameter is in use, otherwise it uses methods unless some other things indicate the use of a method is more appropriate. (see post above for examples for this)

This is the IL-Code produced by both versions in case you are interested (i used a simple console app and static methods/properties)

{
  // Code size       22 (0x16)
  .maxstack  2
  .locals init ([0] bool CS$1$0000,
           [1] valuetype [mscorlib]System.DateTime CS$0$0001)
  IL_0000:  nop
  IL_0001:  call       valuetype [mscorlib]System.DateTime [mscorlib]System.DateTime::get_Now()
  IL_0006:  stloc.1
  IL_0007:  ldloca.s   CS$0$0001
  IL_0009:  call       instance valuetype [mscorlib]System.DayOfWeek [mscorlib]System.DateTime::get_DayOfWeek()
  IL_000e:  ldc.i4.1
  IL_000f:  ceq
  IL_0011:  stloc.0
  IL_0012:  br.s       IL_0014
  IL_0014:  ldloc.0
  IL_0015:  ret
} // end of method Program::get_IsTodayProp

Cheers!

360Airwalk
I think you missed the point? I thought the question was about what clues properties and methods give to users of classes, not what the language allows.
David Kemp
that's why i stated how microsoft handles this issue in the framework - as for "best practice"
360Airwalk
A: 

DataBinding does not work on methods, so if you ever intend to bind your object to some control, keep this in mind. Personally I prefer properties, for readability reasons.

devnull
A: 

Have you considered

public static bool IsMonday(DateTime date)
{
    return date.DayOfWeek == DayOfWeek.Monday;
}

instead? This is significantly easier to unit test than the original method.

TrueWill
A: 

I have twenty years or so of experience in designing software as a consultant for a number of different companies and have also been working at OEM company. To me this question is more like a company policy (coding guidelines) question and if any company wants to choose methods that help in producing easy to understand and easy to debug and read practises, then they should choose using Get/Set over properties. This is because, for example, when debugging a calling class which uses a property from other class it seems there like a potentially not well handled public variable access (BAD and looks dangerous). On the other hand, if you would see a Getter/Setter method call there, then you would KNOW right away, that it is not a public variable access and that there is a function handling the call and it can even return error code or exception, if so chosen. Any coding guideline or practise selection should be based on the fact, that that selection better guides coders to write quickly-understandable, trustable (safe), portable, simple and symmetric code which is debugging -friendly. And should there be any other reasons?

R.Hatman