Wednesday, 25 August 2010

Multiple inheritance with interfaces in VB.Net

I couldn’t recall the correct Visual Basic .Net syntax for creating an interface which itself extends other interfaces. So, as a reminder, here it is.

Lets say we have 2 simple interfaces: INameable and IIdentifiable. These interfaces simply require that implementing classes have an Id property and a Name property respectively. Lets also say that we want to define an IReferenceData interface that simply says implementing classes must implement INameable and IIdentifiable.

For comparison lets start with C#:

namespace Domain
{
    /// <summary>
    /// Classes implementing this interface will have a name property.
    /// </summary>
    public interface INameable
    {
        /// <summary>
        /// Gets or sets the name of the entity.
        /// </summary>
        string Name { get; set; }
    }

    /// <summary>
    /// Classes implementing this interface will have an Id property.
    /// </summary>
    public interface IIdentifiable
    {
        /// <summary>
        /// Gets or sets the unique ID of the entity.
        /// </summary>
        int Id { get; set; }
    }

    /// <summary>
    /// An interface to be implemented by reference data types (simple types with 
    /// Name and ID properties).
    /// </summary>
    public interface IReferenceData : IIdentifiable, INameable
    {
    }
}

Now, the same thing in VB.Net:

Namespace Domain
    ''' <summary>
    ''' Classes implementing this interface will have a name property.
    ''' </summary>
    Public Interface INameable
        Property Name As String
    End Interface

    ''' <summary>
    ''' Classes implementing this interface will have an Id property.
    ''' </summary>
    Public Interface IIdentifiable
        ''' <summary>
        ''' Gets or sets the unique ID of the entity.
        ''' </summary>
        Property Id As Integer
    End Interface

    ''' <summary>
    ''' An interface to be implemented by reference data types (simple types with 
    ''' Name and ID properties).
    ''' </summary>
    Public Interface IReferenceData
        Inherits IIdentifiable
        Inherits INameable
    End Interface
End Namespace

Note the separate Inherits statements on separate lines.

Sunday, 22 August 2010

VB.Net equivalent of C# typeof()

Here’s a quick gotcha that got me again today. In C# to get a type we might use code such as the following:

var type = typeof(SomeType);

The equivalent in Visual Basic .Net is:

Dim type = GetType(SomeType)

Equivalent of static classes is VB.Net

The closest thing in Visual Basic .Net to a C# static class is a Module (also known as a standard module). In C# a static class is described as follows:

“A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.” *

There is no direct equivalent in Visual Basic .Net but a Module has some properties similar to those of a static class:

  • Every module has exactly one instance and does not need to be created or assigned to a variable.
  • Modules do not support inheritance or implement interfaces.
  • A module is not a type - you cannot declare a programming element to have the data type of a module.
  • You can use Module only at namespace level.
  • The declaration context for a module must be a source file or namespace (not a class, structure, module, interface, procedure, or block).
  • You cannot nest a module within another module, or within any type.
  • A module has the same lifetime as your program.
  • All a module’s members are implicitly Shared. **

Example in C#:

static class SomeName
{
    public static string SomeMethod1() { return "Value 1"; }
    public static string SomeMethod2() { return "Value 2"; }
    //...
}

Equivalent in Visual Basic .Net:

Public Module SomeName
    Public Function SomeMethod1() As String
        Return "Value 1"
    End Function
    
    Public Function SomeMethod2() As String
        Return "Value 2"
    End Function
    '...
End Module

* Static Classes and Static Class Members (C# Programming Guide) 
** Shared - specifies that one or more declared programming elements are associated with a class or structure at large, and not with a specific instance of the class or structure.

Tuesday, 10 August 2010

Notes on Service-Orientation

I was thumbing through my copy of SOA Principles of Service Design by Thomas Erl, and thought I’d make a few notes on some of the standout concepts as well as notes picked up from other locations.

As usual this is going to be a work in progress…

OASIS (Organization for the Advancement of Structured Information Standards) defines SOA as:

“A paradigm for organizing and utilizing distributed capabilities that may be under the control of different ownership domains. It provides a uniform means to offer, discover, interact with and use capabilities to produce desired effects consistent with measurable preconditions and expectations.”

Principles of Service-Orientation as a design paradigm

Erl describes some of the principles of a service-oriented design paradigm in the following terms:

  • Standardised Service Contract
    • The purpose and capabilities of a service are exposed by a service contract.
  • Service Loose Coupling
    • Emphasis should be placed on reducing dependencies between the service contract, its implementation and its consumers.
  • Service Abstraction
    • Hide the underlying details of a service from its consumers.
    • Enables and preserves loose coupling. 
  • Service Reusability
    • Emphasises the positioning of services as enterprise resources “with agnostic functional contexts”.
  • Service Autonomy
    • Underlying solution logic needs to have a significant degree of control over its environment and resources.
  • Service Statelessness
    • “The management of excessive state information can compromise the availability of a service and undermine its scalability and potential.”
    • Ideally, services should remain stateful only when required.
  • Service Discoverability
    • “For services to be positioned as IT assets with repeatable ROI they need to be easily identified and understood when opportunities present themselves.”
  • Service Composability
    • Services should be capable of participating as effective composition members.
Tuesday, 10 August 2010

Friday, 6 August 2010

Isolation levels in SQL Server

Isolation defines how or when changes made by an operation become visible to other concurrent operations. In other words you can use Isolation levels to isolate a resource for a transaction and protect that resource from modification by other transactions.

Resources are protected through the use of locks. SQL Server decides what locks to take out (and when) by looking at the Isolation Level for the transaction. Lower levels of isolation will allow multiple access to a resource simultaneously but may introduce concurrency related problems (e.g. dirty-reads, data inaccuracy). Higher levels of isolation should eliminate concurrency problems but risk introducing blocking.

Serializable

All transactions occur in a completely isolated fashion.

Places a range lock on the data set preventing other users from updating or inserting rows into the data set until the transaction is complete.

This is the most restrictive of the four isolation levels.

Repeatable read

All data records read by a SELECT statement cannot be changed. The transaction acquires read locks on all retrieved data, but does not acquire range locks.

Locks are placed on all data that is used in a query preventing other users from updating the data. However, new ‘phantom’ rows can be inserted into the data set by another user and will be included in later reads in the current transaction.

Read committed

Records retrieved by a query are not prevented from modification. Non-repeatable reads may occur (data retrieved in a SELECT statement may be modified by some other transaction when it commits). Read locks are acquired on selected data but they are released immediately. Write locks are released at the end of the transaction.

Shared locks are held while the data is being read to avoid dirty reads but the data can be changed before the end of the transaction.

This is the default Isolation Level of SQL Server. It eliminates dirty-reads but other concurrency problems remain.

Read uncommitted

Dirty reads are allowed. One transaction may see uncommitted changes made another transaction.

It is possible to read uncommitted or dirty data but values in the data can be changed and rows can appear or disappear in the data set before the end of the transaction.

Wednesday, 28 July 2010

Service Locator pattern

A pattern that is showing up frequently in .Net development at the moment is Service Locator. It has appeared in the Composite Application Library (Prism - intended for use in Silverlight and WPF applications) as well as ASP.Net MVC. Service Locator is often seen going hand in hand with DI and IoC and one useful implementation of Service Locator might be to decouple an application from specific IoC containers (i.e. use the Service Locator pattern on top of IoC).

In essence, Service Locator is a simple pattern:

“Provide a global point of access to a service without coupling users to the concrete class
that implements it.”
*
Martin Fowler describes the pattern in the following terms:
“The basic idea behind a service locator is to have an object that knows how to get hold of all of the services that an application might need.” **

service-locator

The Composite Application Library documentation offers a number of drawbacks to Service Locator:

“The Service Locator pattern has the following liabilities:
  • There are more solution elements to manage.
  • You have to write additional code to add service references to the locator before your objects use it.
  • Your classes have an extra dependency on the service locator.
  • The source code has added complexity; this makes the source code more difficult to understand.” ***

In short the criticism is that Service Locator adds complexity to the application. Martin Fowler also notes that use of Service Locator can lead to testability issues:

“I've often heard the complaint that these kinds of service locators are a bad thing because they aren't testable because you can't substitute implementations for them. Certainly you can design them badly to get into this kind of trouble, but you don't have to.”

Common Service Locator

Many frameworks (including MVC 3) are now working to the Common Service Locator library. This is described in the following terms:
“The Common Service Locator library contains a shared interface for service location which application and framework developers can reference. The library provides an abstraction over IoC containers and service locators. Using the library allows an application to indirectly access the capabilities without relying on hard references.”
A number of IoC frameworks already provide implementations of the core interface (IServiceLocator) including Spring.Net, Unity, and Castle Windsor. The IServiceLocator interface requires that an IoC container provide the following methods:
TService GetInstance<TService>();
object GetInstance(Type serviceType, string key);
TService GetInstance<TService>(string key);
IEnumerable<object> GetAllInstances(Type serviceType);
IEnumerable<TService> GetAllInstances<TService>();

This is interesting but one has to ask if it’s an abstraction too far.

Update: If you are considering using the Service Locator pattern you should be aware that it is regarded by many as an anti-pattern. See Service locator anti-pattern.


* Service Locator, Game Programming Patterns / Communicating Patterns
** Using a Service Locator, Martin Fowler
*** Service Locator

Friday, 23 July 2010

A reminder about boxing and unboxing in C#

Here is a quick reminder about boxing and unboxing in C#. MSDN documentation contains this concise description of boxing and unboxing:

“Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. In the following example, the integer variable i is boxed and assigned to object o.” *

All primitive types (byte, char, int, long, etc.) and structures are value-based types derived from System.ValueType. Because value types are stored on the Stack they can be created and accessed more efficiently than reference types. Reference types are stored on the Heap and must be accessed using references.

An example of boxing and unboxing:

int i = 123;
object o = (object)i; // boxing
int j = (int)o; // unboxing

Why is this important?

Boxing and unboxing operations are computationally expensive in relation to other simple assignments (for example, when a value type is boxed, a new object must be allocated and constructed). If you have code which undertakes a lot of boxing operations you may run into performance issues.

Determining which methods and properties will cause boxing is possible by checking their their signatures. If a method takes an argument of type object or the argument is an interface then if you were to pass in a value type instance it will be boxed.

Note it is very easy to slip into boxing operations:

var sb = new StringBuilder();
for(int i = 0; i < 10; i++)
{
    sb.AppendFormat("Boxing: {0}, {1}", i, i + 1); // Boxing here   
}

You could get around this by calling the ToString() method early to prevent allocation on the heap:

var sb = new StringBuilder();
for(int i = 0; i < 10; i++)
{
    sb.AppendFormat("No boxing: {0}, {1}", i.ToString(), (i + 1).ToString()); // No boxing   
}

Value types and reference types

Again MSDN documentation provides a description of value types:

“Variables that are based on value types directly contain a values. Assigning one value type variable to another copies the contained value. This differs from the assignment of reference type variables, which copies a reference to the object but not the object itself.” **

There are 2 main categories of value types:

  • Structs (e.g. numeric types: integral types, floating-point types and decimal; bool; user defined structs)
  • Enumerations

In essence, value types are lightweight objects that are allocated on the current thread's stack (see Stack and heap below). There are exceptions to this (e.g. when a value type is allocated as an element of an array or is a field of a reference type). When an instance of a value-type is created a single space in memory is allocated to store the value. When instantiating a reference type an object is created in memory and is handled through a reference (somewhat like a pointer).

Stack and heap

The Stack can be thought of as being responsible for keeping track of what's executing in the code (the call stack). When a method is called (a Frame) data is pushed onto the Stack. Once the method executes the data is popped off the Stack and is discarded. Only the ‘top’ item is available in the Stack (typical behaviour for a stack being a last-in-first-out memory structure).

The Heap can be thought of as being responsible for keeping track of the objects referenced by the code. Any element in the Heap can be accessed directly.

Garbage collection

The Stack does not require garbage collection. It is self-maintaining because items are popped off the stack and discarded as they are used during program execution. On the other hand the Heap is subject to garbage collection.

* Boxing and Unboxing (C# Programming Guide)
** Value Types (C# Reference)

Friday, 23 July 2010