Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force a client to set certain properties

Tags:

c#

My class has ten properties that must be set before the class can be used.

I want to force (or at least very strongly encourage, preferably with warnings) a user of my class to set these properties before calling any methods of the class.

I could use a constructor that takes values for all the properties as parameters but I don't want to because that many parameters would be unwieldy.

I could check the values of the properties inside all the methods of the class but this is too late - I want a compile-time check.

What can I do?

like image 219
cja Avatar asked Sep 18 '25 18:09

cja


2 Answers

Maybe you can use some variation of the Builder Pattern with fluent interface. You could have kind of steps or something where you can't skip some of the properties. For example to set property Y of the builder you will need the object returned by the method that sets property X.

new Builder().SetX(10).SetY(20) //compiles because SetX returns a class with SetY method
new Builder().SetY(20) //does not compile because the builder only has SetX method

To avoid having multiple classes you may have one class with multiple interfaces each of which exposes only one method.

On the other hand I would probably go for the constructor even with a lot of parameters

like image 97
Stilgar Avatar answered Sep 20 '25 07:09

Stilgar


Some ideas:


Optional parameters should reduce mess of constructor parameters

public class SomeClass
{
    public int Property1 {get; private set;}
    public int Property2 {get; private set;}
    public int Property3 {get; private set;}

    public SomeClass(int some1 = 1, int some2 = 2, int some3 = 3)
    {
        SomeProperty1 = some1;
        SomeProperty2 = some2;
        SomeProperty3 = some3;
    }
}

Easy to use:

var a = new SomeClass(some3: 123);

You can try use nullables to throw if some value is not set

public class SomeClass
{
    private int? _property1;
    public int Property1 { get { return (int)_property1.Value; } } // will throw

    public SomeClass() {}

    public int SomeMethod()
    {
       int val = _property1.Value; // will throw
       ...
       return 123;
    }
}
like image 36
Sinatr Avatar answered Sep 20 '25 09:09

Sinatr