Best Practice: Accessory Properties or Parameterless Methods?

Which is the best practice and why?

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

      

or

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

      

+2


source to share


10 replies


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

If you look at the generated IL code, you will notice that it is exactly the same. The property will create a method that produces the same IL code.

As far as .Net implementations go, you should probably use the property. The .Net framework uses properties for IsXXX-Functionality when no parameter is used, otherwise it uses methods, unless some other thing indicates that using a method is more appropriate. (see above examples)



This is the IL generated by both versions if 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

      

Hooray!

+7


source


In my opinion, use properties in these situations if:

  • Calling is expensive, for example. Database calls are made.
  • When the property is called, side effects occur, eg. other variables are also set
  • Calling the property multiple times gives different results.
  • Your property is only used to set values


In your example, I would go with a property.

+10


source


The property should be a pretty trivial wrapper around the value. For the user of the property, it should act exactly like a variable.

If it does any work, has side effects (like reading / writing changes some other state in your class), or if it might fail (like throwing an exception), then it's better to write it as a Get method, like so that the caller can see that it is not just a value.

Other than that, it depends on personal preference (do you think "Properties" should only represent specific member variables, or can they be used to read "computed values" like the example in your example).

+6


source


Generally:

If you are using a language where option # 1 is legal, you must use it. This improves readability and makes it for this kind of work.

If you cannot use parameter # 1, you must use get / set methods; i.e:.

bool getIsTodayMonday()
void setIsTodayMonday(bool timetravelingArgument)

      

Your specific example

I think you can come up with arguments for both, although I would go with option # 2 as the fields (in my opinion) shouldn't do too much computation (other than validation and possibly transformation).

+4


source


For me, I would say that IsTodayMonday is more like a method than a property, so I would go with the second option. Have a look at Method vs Property in C # - What's the difference for a good example of using properties over methods.

+1


source


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

Or from a user perspective: I wouldn't mind accessing obj.IsTodayMonday multiple times, because I would assume it doesn't require a lot of computation. In the case of obj.IsTodayMonday (), I would consider caching and reusing the result.

But this is, of course, how I write the code. It depends on your policies.

+1


source


Clock.IsTodayMonday

suggests to me that this has no side effects or computation.

Clock.IsTodayMonday()

indicates that side effects or calculations are possible.

It IsTodayMonday

might be appropriate in your case , but as it goes and asks for the system clock, it might be more appropriate to call it IsTodayMonday()

.

More complex example might be PrimeFactors

. If you had an integer property PrimeFactors

, it would indicate to me that you can call it over and over again without any performance boost. However, if there was a method called PrimeFactors()

, then I would probably use a temporary variable to cache the result if I needed it more than once, especially in a tight loop.

+1


source


DataBinding doesn't work on methods, so if you ever intend to bind your object to a specific control, keep that in mind. I personally prefer properties for readability reasons.

0


source


Have you considered

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

      

instead of this? It is significantly easier to unit test than the original method.

0


source


I have twenty years of software development experience as a consultant for a number of different companies and also work for an OEM company. For me, this question is more like a question about company policy (coding rules), and if any company wants to choose methods that help in creating practices that are easy to understand and easy to debug and read, then they should choose to use Get / Set over properties. This is because, for example, when debugging a calling class that uses a property from another class, it looks like potentially invalid access to public variables (BAD and looks dangerous). On the other hand, if you see a call to the Getter / Setter method there, you will immediately know that this is not a public variable access, and that there is a call handling function.and it might even return an error code or an exception if thrown. Any coding guidance or practice choice should be based on the fact that this choice better guides coders to write quickly understandable, reliable (safe), portable, simple and symmetric code that is debuggable. And should there be other reasons?

0


source







All Articles