Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / C# 4.0

Domain Specific Language using C# 4.0 - Part 3

Rate me:
Please Sign up or sign in to vote.
3.00/5 (7 votes)
30 Dec 2010CC (ASA 2.5)3 min read 25.1K   14   9
Explains how to define internal DSL using C# language constructs

Previous Parts

In the last part of this article, we provided a domain-friendly API to create a new exam but left the part to provide a readable way for adding "n" of questions and their corresponding options.

Level 2: Method Chaining & Fluent API

After creating the exam instance, what would be the feasible way for the user to add questions. First, let us see the current API to add questions with the exam() method in ExamBuilder:

C#
ExamBuilder.exam(".NET Fundamentals").AddQuestion(question);

How many questions we can add by this way? Is it domain friendly? "Only one" is the answer for first question. "Yes this is definitely not domain friendlier" is the answer for the second question. The immediate requirement for the above problem is that if AddQuestion() returns the current exam object, then we can call AddQuestion() again and again for every question as long as we need for this exam. Instead of modifying "AddQuestion()", I introduce a method "question()" in the Exam class as:

C#
//Exam.cs
public Exam question(Question question)
{
	AddQuestion(question);
	return this;
}

We have just created a fluent API "question()" for this exam DSL. Fluent means "readable", by using "method chaining". Method chaining is a technique to call one or more methods in the same or different objects in a relay race fashion which produces a domain friendly definition. In the question() method, it just calls AddQuestion() method followed by returning the current instance of Exam object.

This will allow to add more than one question like:

C#
//User Mindset: Space1 for defining questions
Question q1 = new Question("Expansion of CLR");
q1.AddOption("A", "Common Language Runtime");
q1.AddOption("B", "Common LINQ Runtime");
q1.AddOption("C", "C# Language Runtime");
q1.AddOption("D", "C Language Runtime");
q1.AddAnswers(new string[] { "A" });

Question q2 = new Question("Expansion of CTS");
q2.AddOption("A", "C# Type System");
q2.AddOption("B", "Common Type System");
q2.AddOption("C", "Compiler Test Symbols");
q2.AddOption("D", "CLR Tolerate Service");
q2.AddAnswers(new string[] { "A" });            

//User Mindset: Space2 for adding above questions into Exam object
ExamBuilder.exam(title: ".NET Fundamentals")
	.question(q1)
	.question(q2);

However, we have touched the slice of the cake. This is the time to refactor Question object instantiation and its AddOption() method. Currently, the instantiation itself creates annoyance to the user and also he will get a feel of having two different spaces one for defining questions and another one for adding them into Exam object.

Let us introduce another version of question().

Level 3: Collections

C#
//Exam.cs
private static string[] opts = new string[] { "A", "B", "C", "D" };

public Exam question(string description, IList<string> options)
{
	Question q = new Question(description);
	int i = 0;
	
	foreach (string option in options)
	{
		q.AddOption(opts[i++], option);
	}

	return this;
}
</string>

Instead of asking Question object as parameter, this method asks question description as first argument followed by collection of string for options. Internally, I assign option keys "A", "B", "C", "D" sequentially using "opts" field. The consumption of this version would be:

C#
ExamBuilder.exam(title: ".NET Fundamentals")
	.question("Expansion of IL", 
		new List<string> {"Indian Language", "Intermediate Language"}
	);
</string>

But, you will definitely hate to see "new List<string>". What else we can do? Let us try "params" modifier.

C#
public Exam question(string description, params string[] options)

//Usage
.question("Expansion of IL", "Indian Language", "Intermediate Language")

Still, this is not domain friendly. How can user know all the parameters after the first parameter are options. Syntactically, you cannot stop the user after four options.

Shall we try to use Func<> or Action<> delegates? See the below code and its corresponding consumption.

Level 4: Delegates

C#
//Exam.cs
public Exam question(string desc, Action<question> options)
{
	Question q = new Question(desc);
	options(q);
	AddQuestion(q);
	return this;
}

//Usage
.question("Which one of the following is loaded during a new .NET process creation?", 
			q =>
			{
				q.AddOption("A", "ILAsm.exe");
				q.AddOption("B", "ILDasm.exe");
				q.AddOption("C", "MSCorEE.dll");
				q.AddOption("D", "MSVCVM.dll");
			}
		)
</question>

The above code seems quite domain friendly. Let us further refactor the Question's AddOption() method to make this as more readable by introducing a fluent version. The definition and consumption would be:

C#
//Solution 1 - inclusive of Exam, Question ctor, methods used
in the usage section below

//Question.cs
public Question a(string option)
{
	AddOption("A", option);
	return this;
}

public Question b(string option)
{
	AddOption("B", option);
	return this;
}

public Question c(string option)
{
	AddOption("C", option);
	return this;
}

public Question d(string option)
{
	AddOption("D", option);
	return this;
}

//Usage
ExamBuilder.exam(title: ".NET Fundamentals")
	.question("Expansion of CLR", q=>
		{
			q.a("Common Language Runtime")
			 .b("Common LINQ Runtime")
			 .c("C# Language Runtime")
			 .d("C Language Runtime");
		})
	.question("Expansion of CTS", q =>
		{
			q.a("C# Type System")
			 .b("Common Type System")
			 .c("Compiler Test Symbols")
			 .d("CLR Tolerate Service");
		})
	.question("Which one of the following is loaded during a 
				new .NET process creation?", q =>
		{
			q.a("ILAsm.exe")
			 .b("ILDasm.exe")
			 .c("MSCorEE.dll")
			 .d("MSVCVM.dll");
		}
	);

Since every question should have four options, I've defined chain of "a(), b(), c(), d()" methods to add options. I've added a comment saying that "Solution 1" in the code means that this would be one of the acceptable versions of exam DSL.

Only problem with this solution is the "q=>" followed by "q.a()...." which makes little annoyance. Can we tweak this part or would any other complete alternate be more readable? Let us see.

To be continued...

License

This article, along with any associated source code and files, is licensed under The Creative Commons Attribution-ShareAlike 2.5 License


Written By
Architect Aditi
India India
Working as Architect for Aditi, Chennai, India.

My Website: www.udooz.net

My Blog: www.udooz.net/blog

Comments and Discussions

 
Generalits good Pin
Pranay Rana30-Dec-10 8:05
professionalPranay Rana30-Dec-10 8:05 
GeneralMy vote of 5 Pin
sraghu4@uic.edu30-Dec-10 7:12
sraghu4@uic.edu30-Dec-10 7:12 
GeneralGood start Pin
sehoorae ependy30-Dec-10 6:56
sehoorae ependy30-Dec-10 6:56 
GeneralMy vote of 5 Pin
sehoorae ependy30-Dec-10 6:55
sehoorae ependy30-Dec-10 6:55 
QuestionWhy? Pin
#realJSOP30-Dec-10 4:40
mve#realJSOP30-Dec-10 4:40 
AnswerRe: Why? Pin
M Sheik Uduman Ali30-Dec-10 6:49
M Sheik Uduman Ali30-Dec-10 6:49 
GeneralRe: Why? Pin
Pranay Rana30-Dec-10 8:02
professionalPranay Rana30-Dec-10 8:02 
GeneralRe: Why? Pin
Keith Barrow31-Dec-10 1:56
professionalKeith Barrow31-Dec-10 1:56 
AnswerRe: Why? Pin
Keith Barrow31-Dec-10 1:59
professionalKeith Barrow31-Dec-10 1:59 
Good spot & 5'd, even if does help you pull away from P O'H Smile | :)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.