1

The business object is Foo.cs

What if Foo`s properties run custom logic? Would it then not a bad idea to create Foo objects which could change the data inside the Foo object and it returns values I do not expect?!

public class FooBuilder
{
    private string bar = "defaultBar";
    private string baz = "defaultBaz";
    private string bling = "defaultBling";

    public FooBuilder Bar(string value)
    {
        bar = value;
        return this;
    }

    public FooBuilder Baz(string value)
    {
        baz = value;
        return this;
    }

    public FooBuilder Bling(string value)
    {
        bling = value;
        return this;
    }

    public Foo Build()
    {
        return new Foo {Bar = bar, Baz = baz, Bling = bling};
    }
}
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
Pascal
  • 12,265
  • 25
  • 103
  • 195

1 Answers1

1

If I understand what you are asking...

It is ok for proprties to execute some code more than setting a backing fields. However if you set a property to one value and then use the getter and discover that it has returned a different value to what you set then that is unexpected. So either this should be avoided within properties or use methods that provide descriptive meaning as to the behaviour/data change.

so this IMO is bad

var foo = new Foo();
foo.Bar = "hello bar";
string bar = foo.Bar;

Console.WriteLine(bar); // if this does not print "hello bar" then it is bad/unexpected
aqwert
  • 10,559
  • 2
  • 41
  • 61
  • but this would mean in my business object Foo I can not run business logic in a Bar property?! – Pascal Jul 13 '12 at 14:13
  • You can as long as the getter of that property returns a value you expect. If you have complex business logic then perhaps you should think about using methods – aqwert Jul 13 '12 at 15:39
  • I would have rather expected the answer:"you should not use Business objects for this task, rather Data Access Objects". What do you think? – Pascal Jul 14 '12 at 15:27