Datasheet

18
x
CHAPTER 1 PRIMER
{
return op(l, r);
}
static void MathExamples()
{
int x = 2;
int y = 3;
// using explicit anonymous methods
int added = Operate(x, y,
delegate(int l, int r){ return l+r; });
int multd = Operate(x, y,
delegate(int l, int r){ return l*r; });
// using lambda expressions
int addedagain = Operate(x, y, (l, r) => l + r);
int multdagain = Operate(x, y, (l, r) => l * r );
}
When used this way, it doesn’t make a lot of sense, because it would seem obvious to just write
x + y, but now that the operation is abstracted away from the actual point of performing the opera-
tion, any kind of operation can be passed in.
This has some interesting implications. Consider, for example, an all-too-common business rule:
Classes are associated with a given fi eld of study (which must now appear on the Class object
as another property,
Field), because only certain kinds of Students can take certain kinds of
Classes — for example, a Student studying Computer Science can take Computer Science
classes, as can
Students studying video game design, but Computer Science students are forbid-
den from taking anything that won’t help them learn computer science better, such as
Underwater
Basketweaving classes. Meanwhile, Video game design is a pretty open-ended major and accepts
just about anything except
Fashion Design classes, whereas Physics majors will need to know
some
Physics and Computer Science but nothing else, and so on. (Like so many of its kind, this
business rule made all kinds of sense back when it was fi rst created, and nobody still with the com-
pany remembers why it was created in the fi rst place, so dont question it now.) When a
Student
signs up for a
Class, this business rule needs to be enforced, but where?
This kind of validation has historically plagued the object-oriented designer; effective enforcement
of the rule requires knowledge coming from two different places, the
Student and the Class. As
such, it seems to defy logical placement: If the validation routine lives on the
Student, the Student
class then has to have awareness of every kind of
Class in the system, a clear violation of separation
of concerns, and vice versa if the validation routine lives on the
Class.
If the validation is abstracted away, however, now the validation can occur without having to know
the actual details yet:
delegate bool MajorApproval(Class cl);
class Student : Person
{
// ...
private MajorApproval m_majorApproval;
// ...
public MajorApproval CanTake
{
c01.indd 18c01.indd 18 10/1/2010 3:20:38 PM10/1/2010 3:20:38 PM