Properties versus Methods


Properties and methods are very similar. In fact, properties are syntactical shortcuts to defining methods. While both methods and properties can be used to perform activities, properties should be used to represent a piece of data and methods should be used to perform actions. Most often, a property is simply used to change (get or set) the state of one variable within a class. Methods are often used when we need to perform actions that change an overall object's state. In other words, methods perform the business functions of the object.

From the .NET point of view, there is no difference between properties and methods. Within .NET, properties are actually treated as methods. A property's get and set accessor are each compiled into their own method.

When designing classes, you will undoubtedly find yourself choosing between using properties and methods. The recommended approach to answering the question is to ask yourself if the purpose of the procedure to set or retrieve a piece of data or perform a more general action. Use properties to set and retrieve a piece of data; use methods to perform actions.

When naming your properties and methods, stick to nouns for properties to signify data and verbs for method names to signify an action. For example, if we expanded our Account class to carry customer information as well, then Name, Address, and Telephone would make ideal property names because they describe a piece of data. Withdraw(), MakeDeposit(), and Transfer() make ideal method names because they describe an action.

For more naming convention guidelines, refer to the specifications set forth in the .NET SDK's Design Guidelines for Class Library Developers. The .NET SDK can be downloaded freely from MSDN at http://msdn.microsoft.com.




C# Class Design Handbook(c) Coding Effective Classes
C# Class Design Handbook: Coding Effective Classes
ISBN: 1590592573
EAN: 2147483647
Year: N/A
Pages: 90

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net