Wednesday, 28 October 2009

SOLID principles

The term SOLID is an acronym for:
  • Single Responsibility Principle
    • A class should have one, and only one, reason to change.
    • If a class assumes more than one responsibility, then there will be more than one reason for it to
      change.
    • If a class has more then one responsibility, then the responsibilities become coupled.
  • Open-Closed Principle
    • Software entities should be open for extension but closed for modification.
    • You should be able to extend a classes behaviour, without modifying it.
    • The primary mechanisms behind the Open-Closed principle are abstraction (inheritance) and polymorphism.
  • Liskov Substitution Principle
    • Derived classes must be substitutable for their base classes.
    • Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.
    • A.K.A. Design By Contract.
    • Derived types are completely substitutable for their base types.
  • Interface Segregation Principle
    • Make fine grained interfaces that are client specific.*
    • Clients should not be forced to depend upon interfaces that they do not use.
  • Dependency Inversion Principle
    • Depend on abstractions, not on concretions.
    • Modules that encapsulate high level policy should not depend upon
      modules that implement details.
    • High level modules should not depend upon low level modules. Both should depend upon abstractions.
    • Abstractions should not depend upon details. Details should depend upon abstractions.

* “This principle deals with the disadvantages of “fat” interfaces. Classes that have “fat” interfaces are classes whose interfaces are not cohesive. In other words, the interfaces of the class can be broken up into groups of member functions. Each group serves a different set of clients. Thus some clients use one group of member functions, and other clients use the other groups.”
See http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod

Tuesday, 27 October 2009

Naming unit tests

In his book The Art of Unit Testing, Roy Osherove suggests the following format for the name of unit tests:

MethodUnderTest_Scenario_Behaviour()

  • MethodUnderTest - The name of the method being tested.
  • Scenario - This part gives us the “with” part of the name: “When I call method X with a null value, then it should do Y.”
  • Behaviour - This part specifies in plain English what the method should do or return, or how it should behave, based on the current scenario: “When I call method X with a null value, then it should do Y.”

Thursday, 22 October 2009

Expression Trees

In LINQ, expression trees represent structured queries that target sources of data that implement IQueryable<T>. Expression trees are also used in LINQ to represent lambda expressions that are assigned to variables of type Expression<TDelegate>.
Instances of Expression<TDelegate> can be executed. To execute an expression tree call the Compile method to create an executable delegate and then call invoke it. Executing an expression tree may return a value, or it may just perform an action such as calling a method.
We can use the Expression Trees to create data store agnostic dynamic query APIs.
The foundation of the Expression Trees in .Net is the System.Linq.Expression namespace. The MSDN documentation states:
“Expression trees represent language-level code in the form of data. The data is stored in a tree-shaped structure. Each node in the expression tree represents an expression, for example a method call or a binary operation such as x < y.”
See http://msdn.microsoft.com/en-us/library/bb397951.aspx
Expression nodes are encapsulated by instances of the Expression class and its subclasses. To build expression tree nodes you use static factory methods on the Expression classes.
You can also get the compiler to build an expression tree for you from a lambda expression. When you do this the Expression is always of type Expression<TDelegate>. The Expression<TDelegate> type provides the Compile method, that compiles the code represented by the expression tree into an executable delegate.
Expression trees are immutable so if you want to modify an expression tree, you must create a copy with the necessary modifications. You can use an expression tree visitor to traverse the existing expression tree. See http://msdn.microsoft.com/en-us/library/bb882521.aspx for an example on how to do this.
Note:
“Only those expression trees that represent functions, namely Expression<TDelegate> and its parent type LambdaExpression, can be compiled into executable code. To execute other types of expression trees, you must first wrap them in a LambdaExpression node. You can obtain such a LambdaExpression by calling the Lambda method and passing the expression tree as the argument.”

Dynamic Queries

For basic information on creating dynamic queries see http://msdn.microsoft.com/en-us/library/bb882637.aspx.
For an example of using AND/OR operations see http://msdn.microsoft.com/en-us/library/bb546136.aspx.

Tuesday, 20 October 2009

IQueryable and IQueryable<T>

The type returned from a LINQ query will be of type IQueryable. For example, the var in the following query will be an IQueryable:
var query = from u in data.Users 
            where u.LastName == "Smith" 
            select new { u.FirstName, u.LastName}
IQueryable has very few members and has 3 properties of particular interest:
public interface IQueryable : IEnumerable
{
    Type ElementType { get; }
    Expression Expression { get; }
    IQueryProvider Provider { get; }
}
An IQueryable has an Expression property. In other words we can get hold of the Expression Tree for the query (note that the Expression type is the base class for the open generic implementations such as Expression<T>). If we can get hold of the Expression Tree we can manipulate it!
Because IQueryable has a GetEnumerator() method you can enumerate the results of the query. 
See http://msdn.microsoft.com/en-us/library/system.linq.iqueryable.aspx
IQueryable<T> implements IQueryable (which itself implements IEnumerable) and “provides functionality to evaluate queries against a specific data source wherein the type of the data is known”. The MSDN documentation states:
“This interface inherits the IEnumerable<T> interface so that if it represents a query, the results of that query can be enumerated. Enumeration forces the expression tree associated with an IQueryable<T> object to be executed. Queries that do not return enumerable results are executed when the Execute<TResult>(Expression) method is called.
The definition of "executing an expression tree" is specific to a query provider. For example, it may involve translating the expression tree to a query language appropriate for an underlying data source.
The IQueryable<T> interface enables queries to be polymorphic. That is, because a query against an IQueryable data source is represented as an expression tree, it can be executed against different types of data sources.” (my italics)
IQueryable<T> has a stack of members including all the query type operations you would expect in the form of extension methods (e.g.  Distinct, Max, Min, etc). It has the same properties as IQueryable, including the Expression property.
See http://msdn.microsoft.com/en-us/library/bb337580.aspx

Monday, 19 October 2009

Expression<TDelegate> Class

Documentation is here: http://msdn.microsoft.com/en-us/library/bb335710.aspx
The documentation states:
Represents a strongly typed lambda expression as a data structure in the form of an expression tree. This class cannot be inherited…
“…When a lambda expression is assigned to a variable, field, or parameter whose type is Expression<TDelegate>, the compiler emits instructions to build an expression tree…
…The expression tree is an in-memory data representation of the lambda expression. The expression tree makes the structure of the lambda expression transparent and explicit. You can interact with the data in the expression tree just as you can with any other data structure.
The ability to treat expressions as data structures enables APIs to receive user code in a format that can be inspected, transformed, and processed in a custom manner. For example, the LINQ to SQL data access implementation uses this facility to translate expression trees to Transact-SQL statements that can be evaluated by the database.”

Properties

Expression<TDelegate> has 4 properties:
  • Body – gets the body of the lambda expression.
  • NodeType – gets the node type of the expression (an enumeration of 45 different values representing all the different types of expression such as constants, greater than (>), less than (<) etc).
  • Parameters – gets the parameters of the lambda expression.
  • Type - gets the static type of the expression that this Expression represents (i.e. one of the Func types such as Func<T1, T2, TResult>).

Methods

There is really only one interesting method on Expression<TDelegate>:
  • Compile - compiles the lambda expression described by the expression tree into executable code.

Namespace

Expression<TDelegate> is part of the System.Linq.Expressions namespace which contains a number of interesting classes:
Class Description
BinaryExpression Represents an expression that has a binary operator.
ConditionalExpression Represents an expression that has a conditional operator.
ConstantExpression Represents an expression that has a constant value.
ElementInit Represents an initializer for a single element of an IEnumerable collection.
Expression Provides the base class from which the classes that represent expression tree nodes are derived. It also contains static (Shared in Visual Basic) factory methods to create the various node types. This is an abstract class.
Expression<TDelegate> Represents a strongly typed lambda expression as a data structure in the form of an expression tree. This class cannot be inherited.
InvocationExpression Represents an expression that applies a delegate or lambda expression to a list of argument expressions.
LambdaExpression Describes a lambda expression.
ListInitExpression Represents a constructor call that has a collection initializer.
MemberAssignment Represents initializing a field or property of a newly created object.
MemberBinding Provides the base class from which the classes that represent bindings that are used to initialize members of a newly created object derive.
MemberExpression Represents accessing a field or property.
MemberInitExpression Represents calling a constructor and initializing one or more members of the new object.
MemberListBinding Represents initializing the elements of a collection member of a newly created object.
MemberMemberBinding Represents initializing members of a member of a newly created object.
MethodCallExpression Represents calling a method.
NewArrayExpression Represents creating a new array and possibly initializing the elements of the new array.
NewExpression Represents a constructor call.
ParameterExpression Represents a named parameter expression.
TypeBinaryExpression Represents an operation between an expression and a type.
UnaryExpression Represents an expression that has a unary operator.
See http://msdn.microsoft.com/en-us/library/system.linq.expressions.aspx.
More to follow on some of these separate types.

ExpressionTreeVisulaizer in VS 2008

To install the ExpressionTreeVisualizer:
  1. Get the C# language samples that include example LINQ projects from http://code.msdn.microsoft.com/csharpsamples.
  2. Open and build the ExpressionTreeVisualizer solution.
  3. Copy the generated ExpressionTreeVisualizer.dll file into ..\Program Files\Microsoft Visual Studio 9.0\Common7\Packages\Debugger\Visualizers directory.
If and when you set a breakpoint and hover over an Expression you can click on the magnifying glass icon in the pop-up tooltip to access the Expression Visualizer.

Friday, 16 October 2009

Func and Action

Func(TResult) is a delegate type that encapsulates a method that has no parameters and returns a value of the type specified by the TResult parameter.
MSDN documentation states:
“You can use this delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate. The method must correspond to the method signature that is defined by this delegate. This means that the encapsulated method must have no parameters and must return a value.”
The documentation goes on to point out that if you need a delegate type that does not have a return type use Action instead.
There are 4 further delegate types related to Func(TResult):
  • Func(T, TResult)
  • Func(T1, T2, TResult)
  • Func(T1, T2, T3, TResult)
  • Func(T1, T2, T3, T4, TResult)
Each of these encapsulates a method that takes one or more parameters of various types and which returns TResult.
There are equivalent Action types for encapsulating delegates that do not have a return type.
This is all very interesting when you consider you can assign a lambda expression to a Func, e.g.
Func<int, int, int> function = (a,b) => a + b;
…and that you can also create an Expression from a lambda represented as a Func.
Expression<Func<int, int, int>> expression = (a,b) => a + b;
More to follow on Expression.
Friday, 16 October 2009,