August 2010
Intermediate to advanced
376 pages
10h 6m
English
Christian Horsdal Gammelgaard provides the following code in C#, using the extension method facility as a way to demonstrate injection of role functionality into a domain class.
using System;
namespace DCI
{
// Methodless role types
public interface TransferMoneySink
{
}
// Methodful roles
public interface TransferMoneySource
{
}
public static class TransferMoneySourceTraits
{
public static void TransferFrom(
this TransferMoneySource self,
TransferMoneySink recipient, double amount)
{
// This methodful role can only
// be mixed into Account object (and subtypes)Account self_=self as Account;
Account recipient_=recipient as Account;
// Self-contained readable and testable
// algorithm
if (self_ != null && recipient_ != null)
{
self_.DecreaseBalance(amount);
self_.Log("Withdrawing " + amount);
recipient_.IncreaseBalance(amount);
recipient_.Log("Depositing " + amount);
}
}
}
// Context object
public class TransferMoneyContext
{
// Properties for accessing the concrete objects
// relevant in this context through their
// methodless roles
public TransferMoneySource Source {
get; private set;
}
public TransferMoneySink Sink {
get;
private set;
}
public double Amount {
get; private set;
}
public TransferMoneyContext()
{
// logic for retrieving source and sink accounts
}
public TransferMoneyContext(
TransferMoneySource source,TransferMoneySink sink, double amount) { Source = source; Sink = sink; Amount = amount; } public void Doit() { Source.TransferFrom(Sink, ...Read now
Unlock full access