Based on the video from Anders in Anders' keynote on language futures , one of the issue is about functional programming. One aspect of functional programming is avoiding mutable state. It is possible for imperative programming like C# or VB to avoid it with adopting functional style.
Fluent interface is an object oriented construct that defines a behavior capable of relaying the instruction context of a subsequent call. Based on Martin Fowler bliki of DSL, we can provide a more fluid feel to the code. This has an advantage that the coder will write code easier to read because the semantic is clear.
The combination of them will produce more functional
and readable code. Below is my example of both combination.
Meeting class
/// <summary>
/// Define meeting
/// </summary>
public class Meeting
{
private readonly DateTime? startTime;
private readonly DateTime? finishTime;
/// <summary>
/// Default Constructor
/// </summary>
public Meeting()
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="start"></param>
/// <param name="finish"></param>
internal Meeting(DateTime? start, DateTime? finish)
{
this.startTime = start;
this.finishTime = finish;
}
/// <summary>
/// Define start meeting
/// </summary>
/// <param name="start"></param>
/// <returns></returns>
public Meeting Start(DateTime start)
{
DateTime? temp = this.finishTime;
Meeting meet = null;
if (temp != null)
{
meet = new Meeting(start, temp);
}
else
{
meet = new Meeting(start, null);
}
return meet;
}
/// <summary>
/// Define finish meeting
/// </summary>
/// <param name="finish"></param>
/// <returns></returns>
public Meeting Finish(DateTime finish)
{
DateTime? temp = this.startTime;
Meeting meet = null;
if (temp != null)
{
meet = new Meeting(temp, finish);
}
else
{
meet = new Meeting(null, finish);
}
return meet;
}
/// <summary>
///
/// </summary>
public DateTime? StartTime
{
get { return this.startTime; }
}
/// <summary>
///
/// </summary>
public DateTime? FinishTime
{
get { return this.finishTime; }
}
}
Main Class
class Program
{
static void Main(string[] args)
{
Meeting meet = new Meeting().Start(DateTime.Now).Finish(DateTime.Now.AddDays(20));
Console.WriteLine("StartTime = " + meet.StartTime);
Console.WriteLine("FinishTime = " + meet.FinishTime);
Console.ReadLine();
}
}
In the meeting class, I use readonly field, so the state of the field can be accessed only on constructor. This code style I just copy from Anders video.
Method Start and Finish is fluent interface style. Those methods use in main class; you can see in the statement “Meeting meet = new Meeting().Start(DateTime.Now).Finish(DateTime.Now.AddDays(20));”
0 comments:
Post a Comment