How can we name multiple optional functions on one line?
I have several features in my simple server infrastructure as shown below. This requires several functions:
new TestServer()
.DOBind("ip", "port")
.SetMaxBindTries(3)
.SetMaxConnections(300)
.ONBind(delegate {...})
.ONReceiveBytes(delegate {...})
.ONSocketStatusChanged(delegate {...})
.ONBlaBlaBla...
my question is: - How can I do something like this? - What are the "special keywords" for the investigation? - Which class-design / design-pattern structure should I follow?
Any pointers appreciated.
+3
source to share
2 answers
There is no secret keyword or design here. It happens that each of these methods returns a TestServer instance (just 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 the fluent API
+7
source to share
class TestServer
{
string x = "";
string y = "";
string z = "";
TestServer SetX(string val)
{
x = val;
return this;
}
TestServer SetY(string val)
{
y = val;
return this;
}
TestServer SetZ(string val)
{
z = val;
return this;
}
}
then you can do it like this
new TestServer().SetX("blbablabla").SetY("Blablabla").SetZ("blablabla");
+1
source to share