Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to we call multiple optional functions in one line?

Consider I have multiple functions in my simple server framework as shown below, It takes multiple functions like this :

new TestServer()
    .DOBind("ip", "port")
    .SetMaxBindTries(3)
    .SetMaxConnections(300)
    .ONBind(delegate {...})
    .ONReceiveBytes(delegate {...})
    .ONSocketStatusChanged(delegate {...})
    .ONBlaBlaBla...

my question: - How can I do something like this ? - What are the "special key words" to investigate ? - What kind of "class-design / design-pattern" structure should I follow ?

Any pointers appreciated.

like image 716
Dentrax Avatar asked Dec 24 '22 15:12

Dentrax


1 Answers

No secret keyword or design here. What happens is that each of these methods returns the instance of the TestServer (simply by returning this):

TestServer DoThis()
{
    // method code
    return this;
}

TestServer DoThat(string WithThisParameter)
{
    // method code
    return this;
}

And then you can do this:

var x = new TestServer();
x.DoThis().DoThat("my string").DoThis();

Apparently, as Vache dee-see wrote in the comments, this is called "fluent API"

like image 88
Zohar Peled Avatar answered Dec 28 '22 07:12

Zohar Peled