I been thinking about when I should differentiate between methods and properties. For instance, suppose that I have the following class:
public class OrderProcessor
{
public bool RoundToNearestCent { get; set; }
public bool RoundDown { get; set; }
}
This class has two boolean properties, and you would use this class like so:
var o = new OrderProcessor();
o.RoundToNearestCent = true;
o.RoundDown = false;
o.DoSomething();
When designing software, you have to think about the accessibility of a class's members. We have two properties that are accessible at any time and can be changed independently. While this may be a bad example to explain for what I'm going to illustrate, you have to decide whether to allow the properties to be edited independently or not. For instance, if we were to change the class to this:
public class OrderProcessor
{
public bool RoundToNearestCent { get; private set; }
public bool RoundDown { get; private set; }
public void SetRoundingRules(bool nearestCent, bool roundDown) { .. }
}
Now we have a single method that does the work, and will do the work of setting the properties. The consumer will no longer be able to set the properties in this manner. While it may not be the best example, it illustrates how you can constrol the flow of using your components. Instead of potentially setting one of the properties, the user has to call the method and specify all the settings at one time, instead of individually.
This can be more useful when you need to guarantee that a method has been called. For instance, if adding a Process() method, the process method can ensure that the SetRoundingRules method has been called through a variable, as shown below.
public class OrderProcessor
{
private bool _hasSetRoundingRules = false;
public bool RoundToNearestCent { get; private set; }
public bool RoundDown { get; private set; }
public void SetRoundingRules(bool nearestCent, bool roundDown) {
_hasSetRoundingRules = true;
.
.
}
public void Process()
{
if (!_hasSetRoundingRules)
throw new Exception();
.
.
}
}
This can also be done using properties, if the properties use the bool? type instead of bool. That way if neither value has a value (is null), an exception can be thrown. Though this type of logic is much easier to implement with a method.
Image may be NSFW.Clik here to view.
