To use a read-only property or a method?

C#.NetClassMethodsProperties

C# Problem Overview


I need to expose the "is mapped?" state of an instance of a class. The outcome is determined by a basic check. It is not simply exposing the value of a field. I am unsure as to whether I should use a read-only property or a method.

Read-only property:

public bool IsMapped
{
    get
    {
        return MappedField != null;
    }
}

Method:

public bool IsMapped()
{
    return MappedField != null;
}

I have read MSDN's Choosing Between Properties and Methods but I am still unsure.

C# Solutions


Solution 1 - C#

The C# standard says

> § 8.7.4 > > A property is a member that provides access to a characteristic of an object or a class. Examples of properties include the length of a string, the size of a font, the caption of a window, the name of a customer, and so on. Properties are a natural extension of fields. Both are named members with associated types, and the syntax for accessing fields and properties is the same. However, unlike fields, properties do not denote storage locations. Instead, properties have accessors that specify the statements to be executed when their values are read or written.

while as methods are defined as

> § 8.7.3 > > A method is a member that implements a computation or action that can be performed by an object or class. Methods have a (possibly empty) list of formal parameters, a return value (unless the method’s return-type is void ), and are either static or non-static.

Properties and methods are used to realize encapsulation. Properties encapsulate data, methods encapsulate logic. And this is why you should prefer a read-only property if you are exposing data. In your case there is no logic that modifies the internal state of your object. You want to provide access to a characteristic of an object.

Whether an instance of your object IsMapped or not is a characteristic of your object. It contains a check, but that's why you have properties to access it. Properties can be defined using logic, but they should not expose logic. Just like the example mentioned in the first quote: Imagine the String.Length property. Depending on the implementation, it may be that this property loops through the string and counts the characters. It also does perform an operation, but "from the outside" it just give's an statement over the internal state/characteristics of the object.

Solution 2 - C#

I would use the property, because there is no real "doing" (action), no side effects and it's not too complex.

Solution 3 - C#

I personally believe that a method should do something or perform some action. You are not performing anything inside IsMapped so it should be a property

Solution 4 - C#

I'd go for a property. Mostly because the first senctence on the referenced MSDN-article:

> In general, methods represent actions and properties represent data.

Solution 5 - C#

In this case it seems pretty clear to me that it should be a property. It's a simple check, no logic, no side effects, no performance impact. It doesn't get much simpler than that check.

Edit:

Please note that if there was any of the above mentioned and you would put it into a method, that method should include a strong verb, not an auxiliary verb like is or has. A method does something. You could name it VerifyMapping or DetermineMappingExistance or something else as long as it starts with a verb.

Solution 6 - C#

I think this line in your link is the answer

> methods represent actions and properties represent data.

There is no action here, just a piece of data. So it's a Property.

Solution 7 - C#

In situations/languages where you have access to both of these constructs, the general divide is as follows:

  • If the request is for something the object has, use a property (or a field).
  • If the request is for the result of something the object does, use a method.

A little more specifically, a property is to be used to access, in read and/or write fashion, a data member that is (for consuming purposes) owned by the object exposing the property. Properties are better than fields because the data doesn't have to exist in persistent form all the time (they allow you to be "lazy" about calculation or retrieval of this data value), and they're better than methods for this purpose because you can still use them in code as if they were public fields.

Properties should not, however, result in side effects (with the possible, understandable exception of setting a variable meant to persist the value being returned, avoiding expensive recalculation of a value needed many times); they should, all other things being equal, return a deterministic result (so NextRandomNumber is a bad conceptual choice for a property) and the calculation should not result in the alteration of any state data that would affect other calculations (for instance, getting PropertyA and PropertyB in that order should not return any different result than getting PropertyB and then PropertyA).

A method, OTOH, is conceptually understood as performing some operation and returning the result; in short, it does something, which may extend beyond the scope of computing a return value. Methods, therefore, are to be used when an operation that returns a value has additional side effects. The return value may still be the result of some calculation, but the method may have computed it non-deterministically (GetNextRandomNumber()), or the returned data is in the form of a unique instance of an object, and calling the method again produces a different instance even if it may have the same data (GetCurrentStatus()), or the method may alter state data such that doing exactly the same thing twice in a row produces different results (EncryptDataBlock(); many encryption ciphers work this way by design to ensure encrypting the same data twice in a row produces different ciphertexts).

Solution 8 - C#

If at any point you'll need to add parameters in order to get the value, then you need a method. Otherwise you need a property

Solution 9 - C#

IMHO , the first read-only property is correct because IsMapped as a Attribute of your object, and you're not performing an action (only an evaluation), but at the end of the day consistancy with your existing codebase probably counts for more than semantics.... unless this is a uni assignment

Solution 10 - C#

I'll agree with people here in saying that because it is obtaining data, and has no side-effects, it should be a property.

To expand on that, I'd also accept some side-effects with a setter (but not a getter) if the side-effects made sense to someone "looking at it from the outside".

One way to think about it is that methods are verbs, and properties are adjectives (meanwhile, the objects themselves are nouns, and static objects are abstract nouns).

The only exception to the verb/adjective guideline is that it can make sense to use a method rather than a property when obtaining (or setting) the information in question can be very expensive: Logically, such a feature should probably still be a property, but people are used to thinking of properties as low-impact performance-wise and while there's no real reason why that should always be the case, it could be useful to highlight that GetIsMapped() is relatively heavy perform-wise if it in fact was.

At the level of the running code, there's absolutely no difference between calling a property and calling an equivalent method to get or set; it's all about making life easier for the person writing code that uses it.

Solution 11 - C#

I would expect property as it only is returning the detail of a field. On the other hand I would expect

MappedFields[] mf;
public bool IsMapped()
{
     mf.All(x => x != null);
}

Solution 12 - C#

you should use the property because c# has properties for this reason

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDave NewView Question on Stackoverflow
Solution 1 - C#CarstenView Answer on Stackoverflow
Solution 2 - C#MichaView Answer on Stackoverflow
Solution 3 - C#Haris HasanView Answer on Stackoverflow
Solution 4 - C#venerikView Answer on Stackoverflow
Solution 5 - C#nvoigtView Answer on Stackoverflow
Solution 6 - C#LotokView Answer on Stackoverflow
Solution 7 - C#KeithSView Answer on Stackoverflow
Solution 8 - C#OdysView Answer on Stackoverflow
Solution 9 - C#CaseyView Answer on Stackoverflow
Solution 10 - C#Jon HannaView Answer on Stackoverflow
Solution 11 - C#SayseView Answer on Stackoverflow
Solution 12 - C#MjeOsXView Answer on Stackoverflow