Use properties or methods to expose business rules in C#?

Posted by Val on Stack Overflow See other posts from Stack Overflow or by Val
Published on 2010-03-11T15:47:42Z Indexed on 2010/03/11 19:39 UTC
Read the original article Hit count: 241

Filed under:
|
|

I'm writing a class to encapsulate some business rules, each of which is represented by a boolean value. The class will be used in processing an InfoPath form, so the rules get the current program state by looking up values in a global XML data structure using XPath operations. What's the best (most idiomatic) way to expose these rules to callers -- properties or public methods?

Call using properties

Rules rules = new Rules();
if ( rules.ProjectRequiresApproval ) {
    // get approval
} else {
    // skip approval
}

Call using methods

Rules rules = new Rules();
if ( rules.ProjectRequiresApproval() ) {
    // get approval
} else {
    // skip approval
}

Rules class exposing rules as properties

public class Rules() {
    private int _amount;
    private int threshold = 100;

    public Rules()  {
        _amount = someExpensiveXpathOperation;
    }

    // rule property
    public bool ProjectRequiresApproval {
        get { return _amount < threshold }
    }
}

Rules class exposing rules as methods

public class Rules() {
    private int _amount;
    private int threshold = 100;

    public Rules()  {
        _amount = someExpensiveXpathOperation;
    }

    // rule method
    public bool ProjectRequiresApproval() {
        return _amount < threshold;
    }
}

What are the pros and cons of one over the other?

© Stack Overflow or respective owner

Related posts about c#

Related posts about properties