C
C#2y ago
SWEETPONY

❔ ✅ How to create builder?

I'd like to create builder which should look smth like that:
var schema = new SchemaBuilder()
.StartGroup("first group")
.AddText()
.EndGroup()
.StartGroup("second group")
.AddText()
.EndGroup()
var schema = new SchemaBuilder()
.StartGroup("first group")
.AddText()
.EndGroup()
.StartGroup("second group")
.AddText()
.EndGroup()
I know how to create builder but I don't understand how to create "groups". All objects inside .StartGroup()... .EndGroup() should have group name How to do it?
6 Replies
Thinker
Thinker2y ago
StartGroup could returns a new GroupBuilder object which has the name of the group in it. The group object also has a reference to the original SchemaBuilder which is returned when calling EndGroup.
class SchemaBuilder
{
private readonly List<GroupBuilder> groups = new();

public GroupBuilder StartGroup(string name)
{
var group = new GroupBuilder(this, name);
groups.Add(group);
return group;
}
}

class GroupBuilder
{
private readonly SchemaBuilder schemaBuilder;
private readonly string name;

public GroupBuilder(SchemaBuilder schemaBuilder, string name)
{
this.schemaBuilder = schemaBuilder;
this.name = name;
}

public GroupBuilder AddText()
{
// stuff

return this;
}

public SchemaBuilder EndGroup() => schemaBuilder;
}

var schema = new SchemaBuilder()
.StartGroup("first group")
.AddText()
.EndGroup()
.StartGroup("second group")
.AddText()
.EndGroup();
class SchemaBuilder
{
private readonly List<GroupBuilder> groups = new();

public GroupBuilder StartGroup(string name)
{
var group = new GroupBuilder(this, name);
groups.Add(group);
return group;
}
}

class GroupBuilder
{
private readonly SchemaBuilder schemaBuilder;
private readonly string name;

public GroupBuilder(SchemaBuilder schemaBuilder, string name)
{
this.schemaBuilder = schemaBuilder;
this.name = name;
}

public GroupBuilder AddText()
{
// stuff

return this;
}

public SchemaBuilder EndGroup() => schemaBuilder;
}

var schema = new SchemaBuilder()
.StartGroup("first group")
.AddText()
.EndGroup()
.StartGroup("second group")
.AddText()
.EndGroup();
SWEETPONY
SWEETPONYOP2y ago
didn't think about second builder may I ask a question is it ok to put GroupBuilder inside SchemaBuilder?
Thinker
Thinker2y ago
As a nested class? sure ig
SWEETPONY
SWEETPONYOP2y ago
thanks for helping!
Chairman Meow
Chairman Meow2y ago
I would tackle this with another approach. Instead of using two builders and a list to store them, I'd just use one builder and a dictionary/map that has the keys set to the group name.
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server