Generics in .Net – Part 5 – Generic Namespaces

So, it’s been awhile since I’ve published a post on this site.  Today I found myself answering a stack overflow post with essentially what I had planned on covering for this part of my series on generics in .net.  So I figured that I would post the same content here.  As a result, this 5th part is being publish out of order and before parts 2-4.  Hopefully, it won’t be another year before I get around to posting those parts.  So with that said, here is the post.  Note that some of the concepts employed in this post will be covered in parts 2-4.

For those who work with multiple generic classes that share the same generic type parameters, the ability to declare a generic namespace would be extremely useful.  Unfortunately, .Net (or at least C#) does not support the idea of generic namespaces.  So in order to accomplish the same goal, we can use generic classes to fulfill the same goal.  Take the following example classes related to a logical entity:

public  class       BaseDataObject
                    <
                        tDataObject, 
                        tDataObjectList, 
                        tBusiness, 
                        tDataAccess
                    >
        where       tDataObject     : BaseDataObject<tDataObject, tDataObjectList, tBusiness, tDataAccess>
        where       tDataObjectList : BaseDataObjectList<tDataObject, tDataObjectList, tBusiness, tDataAccess>, new()
        where       tBusiness       : IBaseBusiness<tDataObject, tDataObjectList, tBusiness, tDataAccess>
        where       tDataAccess     : IBaseDataAccess<tDataObject, tDataObjectList, tBusiness, tDataAccess>
{
}

public  class       BaseDataObjectList
                    <
                        tDataObject, 
                        tDataObjectList, 
                        tBusiness, 
                        tDataAccess
                    >
:   
                    CollectionBase<tDataObject>
        where       tDataObject     : BaseDataObject<tDataObject, tDataObjectList, tBusiness, tDataAccess>
        where       tDataObjectList : BaseDataObjectList<tDataObject, tDataObjectList, tBusiness, tDataAccess>, new()
        where       tBusiness       : IBaseBusiness<tDataObject, tDataObjectList, tBusiness, tDataAccess>
        where       tDataAccess     : IBaseDataAccess<tDataObject, tDataObjectList, tBusiness, tDataAccess>
{
}

public  interface   IBaseBusiness
                    <
                        tDataObject, 
                        tDataObjectList, 
                        tBusiness, 
                        tDataAccess
                    >
        where       tDataObject     : BaseDataObject<tDataObject, tDataObjectList, tBusiness, tDataAccess>
        where       tDataObjectList : BaseDataObjectList<tDataObject, tDataObjectList, tBusiness, tDataAccess>, new()
        where       tBusiness       : IBaseBusiness<tDataObject, tDataObjectList, tBusiness, tDataAccess>
        where       tDataAccess     : IBaseDataAccess<tDataObject, tDataObjectList, tBusiness, tDataAccess>
{
}

public  interface   IBaseDataAccess
                    <
                        tDataObject, 
                        tDataObjectList, 
                        tBusiness, 
                        tDataAccess
                    >
        where       tDataObject     : BaseDataObject<tDataObject, tDataObjectList, tBusiness, tDataAccess>
        where       tDataObjectList : BaseDataObjectList<tDataObject, tDataObjectList, tBusiness, tDataAccess>, new()
        where       tBusiness       : IBaseBusiness<tDataObject, tDataObjectList, tBusiness, tDataAccess>
        where       tDataAccess     : IBaseDataAccess<tDataObject, tDataObjectList, tBusiness, tDataAccess>
{
}

We can simplify the signatures of these classes by using a generic namespace (implemented via nested classes):

    public
    partial class   Entity
                    <
                        tDataObject, 
                        tDataObjectList, 
                        tBusiness, 
                        tDataAccess
                    >
            where   tDataObject     : Entity<tDataObject, tDataObjectList, tBusiness, tDataAccess>.BaseDataObject
            where   tDataObjectList : Entity<tDataObject, tDataObjectList, tBusiness, tDataAccess>.BaseDataObjectList, new()
            where   tBusiness       : Entity<tDataObject, tDataObjectList, tBusiness, tDataAccess>.IBaseBusiness
            where   tDataAccess     : Entity<tDataObject, tDataObjectList, tBusiness, tDataAccess>.IBaseDataAccess
    {

        public  class       BaseDataObject {}

        public  class       BaseDataObjectList : CollectionBase<tDataObject> {}
        
        public  interface   IBaseBusiness {}
        
        public  interface   IBaseDataAccess {}

    }

 

Then, through the use of partial classes you can separate the classes into separate nested files.  I recommend using a Visual Studio extension like NestIn to support nesting the partial class files.  This allows the “namespace” class files to also be used to organize the nested class files in a folder like way.

For example:

Entity.cs

    public
    partial class   Entity
                    <
                        tDataObject, 
                        tDataObjectList, 
                        tBusiness, 
                        tDataAccess
                    >
            where   tDataObject     : Entity<tDataObject, tDataObjectList, tBusiness, tDataAccess>.BaseDataObject
            where   tDataObjectList : Entity<tDataObject, tDataObjectList, tBusiness, tDataAccess>.BaseDataObjectList, new()
            where   tBusiness       : Entity<tDataObject, tDataObjectList, tBusiness, tDataAccess>.IBaseBusiness
            where   tDataAccess     : Entity<tDataObject, tDataObjectList, tBusiness, tDataAccess>.IBaseDataAccess
    {
    }

Entity.BaseDataObject.cs

    partial class   Entity<tDataObject, tDataObjectList, tBusiness, tDataAccess>
    {

        public  class   BaseDataObject
        {

            public  DataTimeOffset  CreatedDateTime     { get; set; }
            public  Guid            CreatedById         { get; set; }
            public  Guid            Id                  { get; set; }
            public  DataTimeOffset  LastUpdateDateTime  { get; set; }
            public  Guid            LastUpdatedById     { get; set; }

            public
            static
            implicit    operator    tDataObjectList(DataObject dataObject)
            {
                var returnList  = new tDataObjectList();
                returnList.Add((tDataObject) this);
                return returnList;
            }

        }
        
    }

Entity.BaseDataObjectList.cs

    partial class   Entity<tDataObject, tDataObjectList, tBusiness, tDataAccess>
    {

        public  class   BaseDataObjectList : CollectionBase<tDataObject>
        {

            public  tDataObjectList ShallowClone() 
            {
                var returnList  = new tDataObjectList();
                returnList.AddRange(this);
                return returnList;
            }
        
        }

    }

Entity.IBaseBusiness.cs

    partial class   Entity<tDataObject, tDataObjectList, tBusiness, tDataAccess>
    {

        public  interface   IBaseBusiness
        {
            tDataObjectList Load();
            void            Delete();
            void            Save(tDataObjectList data);
        }

    }

Entity.IBaseDataAccess.cs

    partial class   Entity<tDataObject, tDataObjectList, tBusiness, tDataAccess>
    {

        public  interface   IBaseDataAccess
        {
            tDataObjectList Load();
            void            Delete();
            void            Save(tDataObjectList data);
        }

    }

The files in the visual studio solution explorer would then be organized as such:

    Entity.cs
    +   Entity.BaseDataObject.cs
    +   Entity.BaseDataObjectList.cs
    +   Entity.IBaseBusiness.cs
    +   Entity.IBaseDataAccess.cs

And you would implement the generic namespace like the following:

User.cs

    public
    partial class   User
    :
                    Entity
                    <
                        User.DataObject, 
                        User.DataObjectList, 
                        User.IBusiness, 
                        User.IDataAccess
                    >
    {
    }

User.DataObject.cs

    partial class   User
    {

        public  class   DataObject : BaseDataObject 
        {
            public  string  UserName            { get; set; }
            public  byte[]  PasswordHash        { get; set; }
            public  bool    AccountIsEnabled    { get; set; }
        }
        
    }

User.DataObjectList.cs

    partial class   User
    {

        public  class   DataObjectList : BaseDataObjectList {}

    }

User.IBusiness.cs

    partial class   User
    {

        public  interface   IBusiness : IBaseBusiness {}

    }

User.IDataAccess.cs

    partial class   User
    {

        public  interface   IDataAccess : IBaseDataAccess {}

    }

And the files would be organized in the solution explorer as follows:

    User.cs
    +   User.DataObject.cs
    +   User.DataObjectList.cs
    +   User.IBusiness.cs
    +   User.IDataAccess.cs

The above is a simple example of using an outer class as a generic namespace.  I’ve built “generic namespaces” containing 9 or more type parameters in the past.  Having to keep those type parameters synchronized across the nine types that all needed to know the type parameters was tedious, especially when adding a new parameter.  The use of generic namespaces makes that code far more manageable and readable.

Generics in .Net – Part 1 – The Basics

One of the most powerful features in my opinion about .Net, which really sets it apart from other language frameworks, is its implementation of Generics.  This post will be the first in a multiple part series on the subject.

What is Generics?

So, what is Generics and how do we use it?  Generics or generic programming is a form of coding where type parameters are declared in the signature of classes or methods in place of specific types so that they can be specified later as type arguments.  These type parameters are then used in place of specific types in the implementation of those classes or methods where they are defined.  The following are examples of declared type parameters on a class and on a couple of methods of a normal class:

public  class   GenericClass<T>
{
    private T   someValue;

    public      GenericClass(T someValue) { this.someValue = someValue; }
}

public  class   NormalClass
{

    public  T       GetValue<T>(string key) {...}

    public  void    SetValue<T>(string key, T value) {...}

}

In the above examples, <T> declares that the class or method where it is defined contains zero, one or more references to an as of yet undeclared type T that will be specified later.  Once specified, all instances where T is used will effectively be substituted with the type specified.

Consuming Generic Classes

Perhaps the most common use of Generics in .Net is the use of the Generic classes found within the System.Collections.Generic namespace.  And of these classes, perhaps the most commonly used is the List<T> class.  The List<T> class is the Generic equivalent of the ArrayList class.  It is virtually identical in function as both implement the IList interface and both essentially contains and manage an array of items.  Where the List<T> class shines is in the type safety of ensuring that each instance of the class contains only a homogeneous list of type T or its derivatives.  ArrayList by comparison is homogenous only to the System.Object type.  Since nearly all types derive from System.Object, the ArrayList class does not do much to ensure type safety in most practical cases, especially when one has a specific sub type in mind that they wish to have a homogeneous list of.

So the List<T> class allows you to specify a type argument for parameter T that “constrains” T to a specific type or its derivatives.  When you construct an instance of List<T> at run-time, the type argument that you provide is effectively substituted for T all throughout the implementation of List<T> and a new class type is created.  Any further instances created using the same type argument for T are also instances of this new class type.

One of the main advantages of this form of reuse is in leveraging the same general functionality of a List type across multiple item types without have to repeat write the same general code.  Take the following for example class snippets:

public  class   IntList
{
    ...
    public  int GetValueAtIndexOrDefault(int index, int defaultValue)
    {
        int returnValue;
        if (!this.TryGetValue(index, out returnValue))  returnValue = defaultValue;
        return returnValue;
    }
    ...
}

public  class   StringList
{
    ...
    public  string  GetValueAtIndexOrDefault(int index, string defaultValue)
    {
        string  returnValue;
        if (!this.TryGetValue(index, out returnValue))  returnValue = defaultValue;
        return returnValue;
    }
    ...
}

Consider how the two implementations of GetValueAtIndexOrDefault are virtually identical.  They vary only between the use of the types int and string with regards to the type of items each type of list contains.  Using generics, the above two implementation could be abstracted into the following:

public  class   List<T>
{
    ...
    public  T   GetValueAtIndexOrDefault(int index, T defaultValue)
    {
        T   returnValue;
        if (!this.TryGetValue(index, out returnValue))  returnValue = defaultValue;
        return returnValue;
    }
    ...
}

Notice how the code is now DRYed up.  The type parameter T is now substituted for whatever type arguments we want to specify.  To effectively replace the IntList and StringList class types, we would create instances of List<int> and List<string> respectively.

I plan on posting more on the topic of generics in future posts covering the following concepts:

Generics Inheritance (Parametric Polymorphism)

Understanding Generic Type Parameter Constraints (Bounded Parametric Polymorphism)

Subclass Type Parameter Constraint

Generic Namespaces

 

Atomic Stack

So, I’ve been thinking about how I wanted to try to jump start my blog for a very long time.  The problem is, that for as much as I like technology, I’ve never really taken to the typed word.  I’ve always preferred to make a phone call rather than write up an email or send a text. For as fast as I can type, it seems that I can never really type fast enough to get my ideas recorded, except generally in perhaps the case of programming which is good, given that I’m a programmer.  But when it comes to free-flowing thoughts like those generally relayed via speech, I would definitely prefer to dictate than to actually type.  So, I’m going to attempt to use the Voice Memos iOS application as a way to stage the content for my blog.

Recently I decided to start an open source project, based on some opinions I had received at the St. Louis Days of .Net which echoed similar sentiments from the previous year’s conference.  You see, over the years I’ve been fortunate to have been tasked with solving some of the most difficult challenges faced by the various teams that I have been a part of.  I’ve also been fortunate to have worked with some very talented and skilled individuals on those teams.  Some I collaborated with and others I was literally schooled by.  I’ve somehow managed to hold on to the practices that have proven useful and advantageous in the various projects that I’ve worked on and assimilated them as recurring patterns.  I’ve described some of these patterns to certain individuals over the last few years, and nearly every time, I’ve been asked if any of it was embodied in an open source implementation.  The unfortunate answer has always been nothing that I’m involved with and nothing that I was aware of.

So the purpose of this open source project is to embody the set of tools that I will be implementing and leveraging during the course of the development of a personal closed source project of my own.  As such, requirements will flow from my personal project to the tool-set project.  The tool-set will be comprised of a stack of technologies that I will leverage to build an n-tier web application.  These technologies will be new implementations based upon the patterns that I have successfully leveraged over the years.  These will include things in the following list, which I plan to go into further detail of in future posts:

  • Configurable tier implementations across 8 tiers (data storage, data access/io, business enforcement, application services, service hosting, client side server access/io, client side controllers and client side views)
  • Three independent storage/transport schemas (data storage, entity model, and use case schemas)
  • Entity Model in memory indexing
  • Entity Model domain specific querying language built as a fluent api on top of .Net classes
  • Singleton/Multiton supporting services with lifetimes managed by an Abstract Factory implementation
  • Vertically integrated independent entity tiers relationally bound in the business tier with optimized distributed data access/io execution
  • Expansive configuration
  • Web server host abstraction (with IIS integration implementation, future implementations may include integration on top of OWIN)
  • Built in user account management and security authentication/authorization (including access challenge/negotiation)
  • Built in/expandable service hosting options (default web service implementation with multiple/expandable content negotiation options)
  • Subclassable Enums (and conversely enumerated subclasses, an excellent alternative to using switch statements)
  • Additional supporting data types
  • Advanced .net generics tricks (including subclass constraints/contexts and generic namespaces via nested classes)
  • General object based data storage services for supporting the practice of high fidelity functional prototyping
  • Interchangeable client side server proxies (supporting functional prototyping via an elaborate proxy implementation simulating future remote services)
  • Classical inheritance implementation on top of ECMAScript 5/JavaScript 1.8.5 with base class method call dispatching, public and protected access modifiers, instance and static scopes with constructors
  • Pure client side MVC solution implemented using JSON/HTML/JavaScript
  • and of course more…

The name of this set of tools is Atomic Stack.  The server side tiers (Atomic.Net) are being implemented in .Net using C# due its amazing generics support.  The client side tiers (AtomicWeb/AtomicJS) are being built upon HTML5/ECMAScript 5/CSS 3.  The project goals will including adherence to development practices including:

  • Separation of Concerns (including Unobtrusive JavaScript)
  • Clean Coding Principles
  • Tier/Down Design and Development (with wide client side development cycles with narrow vertical server side development sprints)

In addition I will be looking at employing additional practices not currently in use including the following:

  • Design by Contract (at least for application hosted services)
  • Test Driven Development

I’m sure that if anyone actually comes across this blog, that some may point out that there are a ton of frameworks and libraries out there.  They may question, do we really need yet another framework or library, much less a stack of them?  Frankly, I’m not sure.  I do know however that I have ideas and I would like to contribute those ideas in a tangible way to the community.  And due to my past experience, there is a certain degree of independent yet cohesiveness among these ideas which therefore are compelling me to attempt to start from scratch and create these new tools with minimal constraints solely upon the raw platforms that they are to be built upon (.Net, JavasScript, HTML, CSS, etc.).  Ofcourse I will very likely be incorporating additional dependencies upon things that are already well written and tested (like Mike Woodring’s DevelopMentor ThreadPool, HtmlAgilityPack and jQuery).  But it is very likely that I will avoid some tools whose implementations I find lacking (for example the MS Entity Framework).

Anyway, I droned on long enough and I’m not quite sure how to end this post.  If you are interested in checking out the project, please visit http://atomicstack.com.