Showing posts with label Discipline. Show all posts
Showing posts with label Discipline. Show all posts

Thursday, March 31, 2016

The O in ORM

This code is not object-oriented enough. Objects are not oriented to objects; instead, objects are oriented to database detail, read: keys.

// Consumer code
var fields = Event.GetEventFields(da, actual.Event, language, language);

// Implementing code
public static IEnumerable<Dto.NotificationDto.Template.Response.EventFieldDto>
GetEventFields(IDomainAccess da, EventEnum @event, string lang, string fallbackLang)
{
    var list = 
        from e in da.Query<Event>()
        join f in da.Query<EventField>()
        on e.Enum equals f.Event.Enum

        where e.Enum == @event

        select new Dto.NotificationDto.Template.Response.EventFieldDto
        {
            FieldName = f.Field.TextXlat.Localize(lang, fallbackLang),
            FieldTag  = f.Field.Mnemonic
        };
}


When using a decent ORM like NHibernate, keys shouldn't leak as much as possible on the application layer, as keys could be composite. Joining and filtering with composite keys is a PITA, so just use object when joining and filtering.

Linq and NHibernate can facilitate that. It's only less capable ORM like Entity Framework that insist on accessing stuff through keys.

As much as possible, make objects communicate to objects.

To wit, here's how the ORM queries could be more object-oriented, oriented to object, instead of oriented to database. Foreign keys and primary keys are removed from the Linq query.


// Consumer code:
var fields = Event.GetEventFields(da, da.JustKey<Event>(actual.Event), language, language);


// Implementing code:
public static IEnumerable<Dto.NotificationDto.Template.Response.EventFieldDto>
            GetEventFields(IDomainAccess da, Event eventNeeded, string lang, string fallbackLang)
{

    var list = 
        from e in da.Query<Event>()
        join f in da.Query<EventField>()
        on e equals f.Event // notice that we can use the object themselves on joins. NHibernate is smart enough to know what is the primary key(s) of the object.

        where e == eventNeeded // same here. We don't need to use the primary key

        select new Dto.NotificationDto.Template.Response.EventFieldDto
        {
            FieldName = f.Field.TextXlat.Localize(lang, fallbackLang),
            FieldTag  = f.Field.Mnemonic
        };
    }



When using ORM, just forget the details of what is the primary key is, the primary key's property name may change or the primary could grow two composite key(two or more column keys), but the object itself stays the same.

So even if the name of the primary key (e.g., Id, Code, Enum) is changed to something else or primary key is changed to composite the suggested object-oriented Linq above would still work, future-proof.


Another thing to note, since there is a collection of EventField in Event itself, we can eliminate the join in code by using the EventField collection instead, and then flatten the Event's EventField collection by using SelectMany.


The join-using code above could be shortened to:


// Consumer code:
var fields = Event.GetEventFields(da, da.JustKey<Event>(actual.Event), language, language);


// Implementing code:
public static IEnumerable<Dto.NotificationDto.Template.Response.EventFieldDto>
            GetEventFields(IDomainAccess da, Event eventNeeded, string lang, string fallbackLang)
{
    var list = 
        from eventField in da.Query<Event>().SelectMany(e => e.Fields) 
                      
        where eventField.Event == eventNeeded

        select new Dto.NotificationDto.Template.Response.EventFieldDto
        {
            FieldName = eventField.Field.TextXlat.Localize(lang, fallbackLang),
            FieldTag  = eventField.Field.Mnemonic
        };

    return list.ToList();
}


Lastly, since the object can protect its children by enforcing protected access modifier, accesing the child from the aggregate directly is perfectly fine, it's still DDD as long things are accessed via aggregate's root.


// Consumer code:
var fields = Event.GetEventFields(da, da.JustKey<Event>(actual.Event), language, language);


// Implementing code:
public static IEnumerable<Dto.NotificationDto.Template.Response.EventFieldDto>
            GetEventFields(IDomainAccess da, Event eventNeeded, string lang, string fallbackLang)
{
    var list = 
        from eventField in da.Query<EventField>()

        where eventField.Event == eventNeeded

        select new Dto.NotificationDto.Template.Response.EventFieldDto
        {
            FieldName = eventField.Field.TextXlat.Localize(lang, fallbackLang),
            FieldTag  = eventField.Field.Mnemonic
        };

    return list.ToList();
}


Another approach is to get the aggregate root, and then project the collection, this way creating static method can be avoided.

// Consumer code:
Event eventNeeded = da.Get<Key>(actual.Event);
var fields = eventNeeded.GetEventFields(lang, fallbackLang); 


// Implementing code:
public IEnumerable<Dto.NotificationDto.Template.Response.EventFieldDto>
 GetEventFields(string lang, string fallbackLang)
{
    var list = 
        from eventField in this.Fields
        // where eventField.Event == eventNeeded // this will not be necessary anymore
        select new Dto.NotificationDto.Template.Response.EventFieldDto
        {
            FieldName = eventField.Field.TextXlat.Localize(lang, fallbackLang),
            FieldTag  = eventField.Field.Mnemonic
        };

    return list.ToList();
}  


However, for performance-conscious developers or users, the drawback of not using static method when accessing the aggregate's children is it will incur two queries to database. A query for getting a single row from parent, and another query for getting the children of the parent.


To improve the performance of the code above while giving the illusion of accessing the aggregate's intance method instead directly, use extension method. Thanks C#! :)

The code below will just issue one query to database, on event_field table only, event table will not be queried.

From a consumer:
var eventNeeded = da.JustKey<Event>(actual.Event);
var fields = eventNeeded.GetEventFields(da, language, language); // GetEventFields looks like an instance method and not an static method.



The instance method illusion helper:
public static class EventPerformanceHelper
{
    public static IEnumerable<Dto.NotificationDto.Template.Response.EventFieldDto>
    GetEventFields(this Event eventNeeded, IDomainAccess da, string lang, string fallbackLang)
    {
        var list =
            from eventField in da.Query<EventField>()

            where eventField.Event == eventNeeded

            select new Dto.NotificationDto.Template.Response.EventFieldDto
            {
                FieldName = eventField.Field.TextXlat.Localize(lang, fallbackLang),
                FieldTag  = eventField.Field.Mnemonic
            };


        return list.ToList();
    }
}


Read more about using DDD while not sacrificing performance: http://www.ienablemuch.com/2013/12/pragmatic-ddd.html

Wednesday, March 30, 2016

Highfalutin code #4. With great power, comes great responsibility.

No matter how powerful our programming language is..

foreach (var item in 
    documentFields.SelectMany(
        documentField => documentField.Options, 
        (documentField, option) => new { documentField, option }
    )
)
{
   item.option.DocumentField = item.documentField;
}


..we still have a great responsibility to make our code readable and maintainable:
foreach (var documentField in documentFields)
    foreach (var option in documentField.Options)
    {
        option.DocumentField = documentField;
    }


SelectMany's intent is to flatten *ALL* the option collection from all fields, and then assign each option item in collection to their parent field.

Though the objective of the first code is to make the program's intent obvious, its verbosity blurs the intent of the code.

In fact, if we want to make it appear we are flattening the collection, we can also do it as follows:

foreach (var documentField in documentFields) foreach (var option in documentField.Options)
{
    option.DocumentField = documentField;
}


If we look at the two for loops as projecting a table with two columns, the projected options will now look like flattened rows.

We just have to tilt our perspective sometimes :)


Disclaimer: I won't use the last code.

Wednesday, November 5, 2014

Minimalistic Architecture

Here's a recommended minimalistic and minimum layers for a modern day line of business applications, especially the SPA ones

  1. App
  2. RichDomainModel - emphasis on rich
  3. RichDomainModel.Test
  4. RichDomainModelMapping
  5. Dto
  6. UnitTestFriendlyDal - Domain Access Layer, emphasis on unit-test friendly

    1. App

    • Hosts the UI
    • Serves DTOs as JSON to browser using ASP.NET Web API. ASP.NET Web API gets and pushes DTOs to rich domain models
    • Uses DTOs for data bag between UI and domain models
    • For wiring dependencies, LightInject is highly recommended, it's a very capable IoC/DI container. For AOP concerns, LightInject has interception capability
      • References RichDomainModel, Dto, LightInject, NHibernate


      2. RichDomainModel

      • Receives and returns DTOs to App project
      • Sample implementation:

      using Dto;
      
      using System.Collections.Generic;
      using System.Linq;
      using UnitTestFriendlyDal;
      
      namespace Domain
      {
          public static partial class ProductionDomain
          {
              public class ProductCategory
              {
                  public int    ProductCategoryId   { get; set; }
                  public string ProductCategoryName { get; set; }
      
                  public static IEnumerable<ProductionDto.ProductCategory> GetAll(IDomainAccess ds)
                  {
                      // http://www.ienablemuch.com/2014/10/proper-way-to-query-reference-entity.html
                      return ds.Query<ProductCategory>().MakeCacheable().ToList()
                          .Select(x => new ProductionDto.ProductCategory { Id = x.ProductCategoryId, Name = x.ProductCategoryName }); 
                  }     
              }
          }
      }
      

      • Has no virtual keyword on domain models' members even though NHibernate need domain models' members to be virtual. Uses Virtuosity.Fody to automatically make the domain models' members virtual
      • Though I mentioned above I love the word The, it's better to use an apt naming convention for the domain models. For AdventureWorks example, the tables HumanResources.Department, HumanResources.Employee, Person.Address, Person.Person and Production.Product tables domain models counterparts are: HumanResourcesDomain.Department, HumanResourcesDomain.Employee, PersonDomain.Address, PersonDomain.Person, ProductionDomain.Product. 
      • Do note that the names with Domain suffix are static partial classes, not namespaces, to see why static partial classes are better than namespace, see the link above. As for the need to use suffix/prefix, we cannot nest a class inside another class if it has the same name as the outer class
      • References Dto and UnitTestFriendlyDal only


      3. RichDomainModel.Test

      • Tests the business logic / behavior of the rich domain models
      • References RichDomainModel, RichDomainModelMapping, NHibernate, UnitTestFriendlyDal


      4. RichDomainModelMapping

      • Maps relational entities to RichDomainModel
      • References RichDomainModel and NHibernate only

      5. Dto - data bag between UI and rich domain model


      6. UnitTestFriendlyDal

      • DAL is not data access layer nor repository. This is just a domain access layer that needed its Linq be mockable. The data access layer / repository is NHibernate itself, no need to abstract NHibernate. Don't pile abstractions after abstractions on top of NHibernate, especially if the ORM has a repository, unit-of-work and data access layer built in
      • This is just a thin layer for ORM. NHibernate's .Query (Linq) is an extension method, extension methods can't be mocked properly, hence this interface is created. Abstracting the ORM is not the goal, it's the testability that we are after. Had NHibernate's .Query is not an extesion method, it can be mocked properly, this layer will not be needed. There's no need to add unnecessary abstractions on top of a capable ORM
      • References NHibernate only


      Here's a sample of an SPA stack that applies the layers above



      Sample Code: https://github.com/MichaelBuen/DemoSpaArchitectureMvp



      Multi-tenancy concern

      For multi-tenancy, it's better not to use schema on NHibernate. NHibernate doesn't have the capability yet to do proper multi-tenancy, Hibernate has

      Shoehorning schema on NHibernate's ISessionFactory as a mechanism to do multi-tenancy would entail each tenant to have their own session factory. Disadvantage being, as the second level cache for common reference tables amongst tenants have a copy on each tenant's session factory, the second-level cache can't be shared effectively, or can't be shared at all. So changes on common reference tables on one tenant will not appear on other tenants' second level cache. On the other hand, if we isolate the common reference table to one session factory only, the drawback is we cannot navigate nor join tenant entities to those common reference tables as those entities live in their own session factory

      I'll expound and make a simulation of this on another post


      Database schema is a bit fancy as a multi-tenancy mechanism, especially if the ORM is not yet capable of mapping entities to schema on-the-fly or elegantly

      So for now on NHibernate, it's better to use filters for multi-tenancy concerns



      Naming guideline

      http://www.ienablemuch.com/2013/01/when-your-codes-names-are-running-afoul.html



      Happy Coding!

      Sunday, October 19, 2014

      C# var abuse

      What happened to programming to an interface?



      You have this DLL that contains this interface and implementation:
      namespace UnitTestFriendlyDal
      {
          public interface IDomainAccess : IDisposable
          {
              object Save(object transientObject);
              IQueryable<T> Query<T>();
              T Get<T>(object id);
              T Load<T>(object id);
              void Evict<T>(object id);
          }
      
          public class DomainAccess : IDomainAccess
          {
      
              NHibernate.ISessionFactory _sessionFactory;
              NHibernate.ISession _session;
              NHibernate.ITransaction _transaction;
      
      
              public DomainAccess(NHibernate.ISessionFactory sessionFactory)
              {
                  _sessionFactory = sessionFactory;
                  _session = _sessionFactory.OpenSession();
                  _transaction = _session.BeginTransaction();
              }
      
              // IDomainAccess implementation...
              
      
      
              public Save(object transientObject)
              {
                  return _session.Save(transientObject);
              }
      
              
              IQueryable<T> Query<T>()
              {
                  return _session.Query<T>();
              }
      
      
              public T Get<T>(object id)
              {
                  return _session.Get<T>(id);
              }
      
              public T Load<T>(object id)
              {
                  return _session.Load<T>(id);
              }
      
      
      
              public void Evict<T>(object id)
              {
                  _sessionFactory.Evict(typeof(T), id);
              }
              
      
              
              // Because transaction is a cross-cutting concern. It should be automated
              void IDisposable.Dispose()
              {
                   // http://www.hibernatingrhinos.com/products/nhprof/learn/alert/donotuseimplicittransactions
                          
                  _transaction.Commit();
                  _transaction.Dispose();
                  _session.Dispose();
              }
      
      
              //... IDomainAccess implementation
          }
      }
      


      Developers will use DomainAccess directly instead:
      using (var da = new DomainAccess(_sessionFactory))
      {    
          var c = Customer.Get(domainAccess: da, id: 1);
      }
      


      So what happen now to programming to an interface principle? Prior to C# version 3, you can still convince your colleagues to use variable declaration that adheres to programming to an interface principle: IDomainAccess da = new DomainAccess(), instead of: DomainAccess da = new DomainAccess(). interface variable declaration is just one letter away from its concrete class variable declaration :-)


      Now, some developers will steadfastly refuse to type the type anymore. Code's obviousness to other developers is not given an attention, worse yet most won't care anymore if the code is not adhering to programming to an interface principle anymore


      Another problem with var, when you generate method stub using the da variable from a var declaration, Visual Studio will generate the method stub based on da's concrete class, not based on its interface:
      public static Get(DomainAccess domainAccess, int id)
      {
      }
      

      When it should ideally be interface-based instead:
      public static Customer Get(IDomainAccess domainAccess, int id) 
      {
      }
      


      What you wanted your fellow colleagues to practice:
      using (IDomainAccess da = new DomainAccess(_sessionFactory))
      {    
          var c = Customer.Get(domainAccess: da, id: 1);    
      }
      


      There's a slim chance that you can convince your colleagues who are fans of var to declare variables based on their interface

      Surely, most C# developers didn't heed this Microsoft warning:
      However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required


      Another good argument against var abuse. Bradley Smith wrote:
      var encourages Hungarian Notation

      If the ommission of type names from variable declarations forces us to more carefully name our variables, it follows that variable names are more likely to describe not only their purpose, but also their type:

      var dtIndividuals = GetContacts(ContactTypes.Individuals);

      This is precisely the definition of Hungarian Notation, which is now heavily frowned upon as a practice, especially in type-safe languages like C#.


      dtIndividuals is DataTable individuals. Imagine when there was no var, variable declaration like DataTable dtIndividuals are frowned upon; but now there's var, it's ok to use Hungarian notation again?


      var is the most abused language feature


      How I wish that compilers could at least advise the developer to use the concrete class' interface instead when declaring variables


      To solve the problem above without incurring friction with var everything camp, you can make your concrete classes implement interfaces explicitly, thereby hiding the concrete class' implemented interface methods.
      public class DomainAccess : IDomainAccess
      {
      .
      .
      . 
          // Implement interfaces explicitly. This will make Save not available on DomainAccess instance
          IDomainAccess.Save(object transientObject)
          {
              return _session.Save(transientObject);
          }
      .
      .
      .
      }
      


      So when using the DomainAccess directly (via var), accessing its method will result to compile error..
      using (var da = new DomainAccess(_sessionFactory))
      {        
          da.Save(new Company{ ... }); // this will result to compile error, Save is inaccessible from concrete class DomainAccess
      }
      


      ..so that would compel the developer to program to an interface instead::
      using (IDomainAccess da = new DomainAccess(_sessionFactory))
      {       
          da.Save(new Company{ ... }); // this will compile, Save is accessible from the IDomainAccess interface
      }
      


      Problem solved, that's programming to an interface. Using EIMI as a solution to this problem still has wrinkles in it, programming to an interface can be enforced but it's still easy to accidentally use the DomainAccess concrete class directly via the var keyword, the developer shall then have to change the variable declaration to use the interface instead, wasting time


      There's a better approach, we can make the DomainAccess non-public, then just give the user an instance of IDomainAccess implementation from a factory
      // remove the public keyword
      class DomainAccess : IDomainAccess
      {
          // implement interface methods
      }
      


      When used outside of DomainAccess project, this will not compile:
      var da = new DomainAccess(_sessionFactory); // DomainAccess is not visible to other projects
      



      So to give the user an IDomainAccess object, the dev shall use this pattern instead:
      public class CompaniesController : Controller
      {
          IDomainAccessFactory _daf;
          
          public CompaniesController(IDomainAccessFactory daf)
          {
              _daf = daf;
          }
          
          public JsonResult CompanySave(CompanyDto dto)
          {
              int savedId = 0;
              // OpenDomainAccess returns IDomainAccess instead of returning DomainAccess
              using (var da = _daf.OpenDomainAccess())
              {
                  savedId = da.Save(new Company{...});            
              }                
              return Json(new { savedId = savedId });
          }        
      }
      


      DomainAccess cannot be instantiated directly anymore, it shall be built from a factory instead and return it through interface. Here's an implementation:
      namespace UnityTestFriendlyDal
      {
          public interface IDomainAccessFactory
          {
              IDomainAccess OpenDomainAccess();
          }
          
          public class DomainAccessFactory : IDomainAccessFactory
          {
              NHibernate.ISessionFactory _sessionFactory;
      
              public DomainAccessFactory(NHibernate.ISessionFactory sessionFactory)
              {
                  _sessionFactory = sessionFactory;
              }
              
              // return through DomainAccess concrete class through IDomainAccess interface
              public IDomainAccess OpenDomainAccess()
              {
                  return new DomainAccess(_sessionFactory);
              }
          }
      
          public interface IDomainAccess : IDisposable
          {
              object Save(object transientObject);
              IQueryable<T> Query<T>();
              T Get<T>(object id);
              T Load<T>(object id);
              void Evict<T>(object id);
          }
          
          // Don't make this public
          class DomainAccess : IDomainAccess
          {
              // Though you can use public/internal on method implementations (as long as you don't make the class DomainAcess public), 
              // it's advisable to use explicit interface method implementation instead
      
              // interface implementations here
          }
      }
      


      When you generate a method stub from a variable declaration using var that receives an interface, the generated method stub will naturally generates a method with a parameter of interface. You can reap the benefit of using interfaces when you can properly enforce the use of interfaces everywhere



      Good read on "To var or not to var" :

      http://shahinalborz.se/2011/01/to-var-or-not-to-var-c-implicit-variable-declaration/

      http://www.brad-smith.info/blog/archives/336

      http://weblogs.asp.net/stevewellens/can-the-c-var-keyword-be-misused

      Good read on Programming To An Interface:

      http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface/384067#384067

      http://www.codeproject.com/Articles/392516/Why-I-use-explicit-interface-implementation-as-a-d




      Happy Coding!

      Wednesday, October 15, 2014

      Mapping many-to-many

      Is too much information hiding necessary?

      Three ways to map a many-to-many relationship:
      http://lostechies.com/jimmybogard/2014/03/12/avoid-many-to-many-mappings-in-orms/


      And there is such thing as exotic mapping, avoid it if it is not needed

      Saturday, October 11, 2014

      Refactoring peace of mind with ASP.NET MVC

      If the ASP.NET MVC view has this code:
      // http://stackoverflow.com/questions/6852979/get-current-controller-in-view
      
      string controller = (string)this.ViewContext.RouteData.Values["controller"];
      string action = (string)this.ViewContext.RouteData.Values["action"]; // can use this too: (string)this.ViewContext.Controller.ValueProvider.GetValue("action").RawValue;
      
      if (controller == "Companies" && action == "Search") 
      {
          ...
      }
      


      We can improve it by making it refactoring-friendly:
      Type controllerType = ViewContext.Controller.GetType();
      string action = (string)this.ViewContext.RouteData.Values["action"]; // can use this too: (string)this.ViewContext.Controller.ValueProvider.GetValue("action").RawValue;
      
      if (controllerType == typeof(Erp.Controllers.CompaniesController) 
          && action == StaticReflection.GetMemberName<Erp.Controllers.CompaniesController>(m => m.Search(null)) 
      {
          ...
      }
      


      The refactoring enabler:
      namespace Erp.Helper
      {
          // http://joelabrahamsson.com/getting-property-and-method-names-using-static-reflection-in-c/
          public class StaticReflection
          {
              public static string GetMemberName<T>(System.Linq.Expressions.Expression<Func<T, object>> expression)
              {
                  if (expression == null)
                  {
                      throw new ArgumentException(
                          "The expression cannot be null.");
                  }
      
                  return GetMemberName(expression.Body);
              }
      
              public static string GetMemberName<T>(System.Linq.Expressions.Expression<Action<T>> expression)
              {
                  if (expression == null)
                  {
                      throw new ArgumentException(
                          "The expression cannot be null.");
                  }
      
                  return GetMemberName(expression.Body);
              }
      
              private static string GetMemberName(System.Linq.Expressions.Expression expression)
              {
                  if (expression == null)
                  {
                      throw new ArgumentException(
                          "The expression cannot be null.");
                  }
      
                  if (expression is System.Linq.Expressions.MemberExpression)
                  {
                      // Reference type property or field
                      var memberExpression =
                          (System.Linq.Expressions.MemberExpression)expression;
                      return memberExpression.Member.Name;
                  }
      
                  if (expression is System.Linq.Expressions.MethodCallExpression)
                  {
                      // Reference type method
                      var methodCallExpression = (System.Linq.Expressions.MethodCallExpression)expression;
                      return methodCallExpression.Method.Name;
                  }
      
                  if (expression is System.Linq.Expressions.UnaryExpression)
                  {
                      // Property, field of method returning value type
                      var unaryExpression = (System.Linq.Expressions.UnaryExpression)expression;
                      return GetMemberName(unaryExpression);
                  }
      
                  throw new ArgumentException("Invalid expression");
              }
      
          }
      }
      



      No approach is complete if it is not wrapped in a fluent API. Now your code is completely free of string, typos could be avoided:
      if (ViewContext.Controller.Verify<Erp.Controllers.CompaniesController>().IsTheContext())
      {
          ...
      }
      


      If we want to detect both controller and action:
      if (ViewContext.Controller
          .Verify<Erp.Controllers.CompaniesController>().WithAction(m => m.Search(null)).IsTheContext())
      {
          ...
      }
      





      The supporting API:
      public static class StaticReflectionExtension
      {
          public static ControllerDetector<T> Verify<T>(this System.Web.Mvc.ControllerBase controller) 
              where T : System.Web.Mvc.ControllerBase
          {
              return new ControllerDetector<T>(controller);
          }
      }
      
      public class ControllerDetector<T> where T : System.Web.Mvc.ControllerBase
      {
          System.Web.Mvc.ControllerBase _controller;
          string _action = "";
          public ControllerDetector(System.Web.Mvc.ControllerBase controller) 
          {
              _controller = controller;
          }
      
          public bool IsTheContext()
          {
              return 
                  _controller.GetType() == typeof(T)
                  && 
                  (
                      _action == ""
      
                      ||
      
                      _action == (string)_controller.ValueProvider.GetValue("action").RawValue
                  );
          }
      
          public ControllerDetector<T> WithAction(System.Linq.Expressions.Expression<Func<T, object>> expression)
          {            
              _action = StaticReflection.GetMemberName<T>(expression);
              return this;
          }
      }
      




      Happy Coding!

      Sunday, October 5, 2014

      Just because you can, doesn't mean you should

      Or to put it another way, just because it compiles doesn't mean it's ok

      Don't do this:
      public DataStore(NHibernate.ISessionFactory sessionFactory)
      {
          _transaction = (_session = (_sessionFactory = sessionFactory).OpenSession()).BeginTransaction();
      }
      


      Do this:
      public DataStore(NHibernate.ISessionFactory sessionFactory)
      {
          _sessionFactory = sessionFactory;
          _session = _sessionFactory.OpenSession();
          _transaction = _session.BeginTransaction();
      }
      

      Saturday, October 4, 2014

      Proper way to query a reference entity

      When caching a query, especially reference entities, select the whole entity; otherwise, the cached query won't be able to cache the entities


      A test:
      [TestClass]
      public class FailingTest
      {
          [TestMethod]
          Test_if_theres_entity_cache_when_cacheable_query_didnt_select_the_whole_entity()
          {
              // Arrange
              var sf = Common.BuildSessionFactory();
      
              using (var session = sf.OpenSession())
              {
                  var q = from c in session.Query<Company>().Cacheable()
                          select new CompanyDto { CompanyId = c.CompanyId, CompanyName = c.CompanyName, TinyLogo = c.TinyLogo };
      
                  q.ToList();
              }
      
      
              // Act
              Mapper.NHibernateSQL = "";
      
              using (var session = sf.OpenSession())
              {
                  session.Get<Company>(1); // this won't be able to get an entity cache from the cacheable query above
              }
      
              // Assert
              Assert.IsTrue(Mapper.NHibernateSQL == ""); // SQL will not be empty
          }
      }
      


      Output:
      Test Name:    Test_if_theres_entity_cache_when_cacheable_query_didnt_select_the_whole_entity()
      Test Outcome:    Failed
      Result Message:    Assert.IsTrue failed.
      NHibernate: 
          select
              company0_.company_id as col_0_0_,
              company0_.company_name as col_1_0_,
              company0_.tiny_logo as col_2_0_ 
          from
              Company company0_
      NHibernate: 
          SELECT
              company0_.company_id as company1_2_0_,
              company0_.company_name as company2_2_0_,
              company0_.company_url as company3_2_0_,
              company0_.tiny_logo as tiny4_2_0_ 
          FROM
              Company company0_ 
          WHERE
              company0_.company_id=:p0;
          :p0 = 1 [Type: Int32 (0)]
      


      As you can see, the cached-entity-aware Get was not able to obtain a cached entity from the cacheable query before it. Inefficient


      Here's the recommended way:

      [TestClass]
      public class PassingTest
      {
          [TestMethod]
          public void Test_if_theres_entity_cache_when_cacheable_query_didnt_select_the_whole_entity()
          {
              // Arrange
              var sf = Common.BuildSessionFactory();
      
              using (var session = sf.OpenSession())
              {
                  var q = from c in session.Query<Company>().Cacheable()
                          select c;
      
                  q.ToList().Select(c => new CompanyDto { CompanyId = c.CompanyId, CompanyName = c.CompanyName, TinyLogo = c.TinyLogo });
              }
      
      
              // Act
              Mapper.NHibernateSQL = "";
      
              using (var session = sf.OpenSession())
              {
                  session.Get<Company>(1); // this will be able to get an entity cache from the queryable cache above
              }
      
              // Assert
              Assert.IsTrue(Mapper.NHibernateSQL == ""); // SQL will not be empty
          }
      }
      

      Output:
      Test Name:    Test_if_theres_entity_cache_when_cacheable_query_didnt_select_the_whole_entity
      Test Outcome:    Passed
      NHibernate: 
          select
              company0_.company_id as company1_2_,
              company0_.company_name as company2_2_,
              company0_.company_url as company3_2_,
              company0_.tiny_logo as tiny4_2_ 
          from
              Company company0_
      


      The session.Get<Company>(1) is able to obtain a cached entity from the cached query before it. Efficient


      Happy Coding!

      Wednesday, July 23, 2014

      Making stringly-typed code palatable via implicit operator

      Bad programmers worry about the code. Good programmers worry about data structures and their relationships.
      -- http://programmers.stackexchange.com/questions/163185/torvalds-quote-about-good-programmer

      Smart data structures and dumb code works a lot better than the other way around.
      -- Eric S. Raymond


      Strongly-typed code is all the rage now, but some of us still manages to stash various information to string instead of structuring the information to a class.



      But if you are in an unfortunate codebase and it has a dumb data structure to begin with, e.g., it has stringly-typed data, at least make a smart data structure facade. Not only smart data structure is easy to code on, it can make the codes that depends on the smart data structure very simple, smaller and easy to read.




      using System;
      
      using System.Collections.Generic;
      
      
      using System.Linq;
      
      
      namespace Craft
      {
          class MainClass
          {
      
              public static void Main (string[] args)
              {
                  var list = new Dictionary<string,decimal> ();
                  list.Add ("1_VariablePayBasis", 1337);
                  list.Add ("1_DecisionAmount", 168);
                  list.Add ("3_BasePay", 5201314);
      
      
                  // Dumb data structure. Smart code.
      
                  foreach (var kv in list) {
      
                      // boilerplate codes. a.k.a. Smart Code
                      string[] strings = kv.Key.Split('_');
                      int pk = Convert.ToInt32(strings [0]);
                      string fieldName = strings [1];
      
      
                      Console.WriteLine ("{0} {1} - {2}", pk, fieldName, kv.Value);
                  }
                  Console.WriteLine();
      
      
                  
                  // Smart data structure. Dumb code.
      
                  // via explicit casting, being explicit with implicit :-)
                  foreach (var fv in list.Select(x => (FieldValue)x)) {
                      Console.WriteLine ("{0} {1} - {2}", fv.PrimaryKey, fv.FieldName, fv.Value);
                  }
                  Console.WriteLine();
      
      
      
                  // Smart data structure. Dumb code.
      
                  // neat implicit! it still feel a bit explicit though. we can't use var here
                  foreach (FieldValue fv in list) {
                      Console.WriteLine ("{0} {1} - {2}", fv.PrimaryKey, fv.FieldName, fv.Value);
                  }
      
              }
          }
      
          public class FieldValue
          {
              public int PrimaryKey { get; set; }
              public string FieldName { get; set; }
      
              public decimal Value { get; set; }
      
      
      
              public static implicit operator FieldValue(KeyValuePair<string,decimal> kv)
              {
                  string[] strings = kv.Key.Split('_');
                  int pk = Convert.ToInt32(strings [0]);
                  string fieldName = strings [1];
      
                  return new FieldValue { PrimaryKey = pk, FieldName = fieldName, Value = kv.Value };
              }
          }
         
      }
      


      Live Code https://dotnetfiddle.net/qX2UeA


      Happy Coding! ツ

      Tuesday, June 17, 2014

      How to avoid the expensive ToList on generic list? Generics' OOPness redux

      Have you questioned C# generics’ OOPness? Why is C# is not allowing us to return List<Autobot> to List<ITransformer> despite Autobot and Decepticon is an ITransformer?

      This won't compile even Autobot implements ITransformer:



      Can fix it with ToList, but it's an expensive operation, as it creates a copy:
      public static List<ITransformer> GetTransformers(TransformerType t)
      {
          if (t == TransformerType.Autobot)
              return GetAutobots().ToList<ITransformer>();
          else if (t == TransformerType.Decepticon)
              return GetDecepticons().ToList<ITransformer>();
               
          return null;
      }   
      


      To cut to the chase, return the List<ConcreteClass> to IEnumerable<Interface>:
      public static IEnumerable<ITransformer> GetTransformersOop(TransformerType t)
      {
          if (t == TransformerType.Autobot)
              return GetAutobots();
          else if (t == TransformerType.Decepticon)
              return GetDecepticons();
               
          return null;
      }
      

      Live code: https://dotnetfiddle.net/K3IcR5

      For further information why List<ConcreteClass> is not compatible to List<Interface> even the concrete class implements the interface, read about covariance

      Saturday, June 14, 2014

      ORM Choice

      ORM choice is a touchy subject, you can't just choose one without riling up some developers or DBAs in your team, it's a choice that must be decided carefully. When you've chosen the right ORM for the project, it is a shared joy for the team; picking the wrong one gives everyone a shared pain


      As ORM has an influence how we model the domain models (facilitates shared vocabulary between the developers and the users), we should have a strategy when choosing one (or even two) for your project. We should also have a strategy when modeling our domain models. When we choose an ORM, we must embrace its principles, advantages, limitations, warts and all


      And also, there are some who hates ORM, I could articulate some of the reasons why some hates ORM, but it's better to leave that to the experts. Here's the takeaway why some hates ORM, and Martin Fowler can't be wrong on positing that:

      much of the frustration with ORMs is about inflated expectations


      Back to the subject on choosing an ORM


      You might think that this ORM drivel is about my repository framework (a repository framework to prevent the high coupling of an application to an specific ORM) I'm trying to endorse. I would not endorse it, it's a half-baked solution for what it's trying to achieve


      I made a repository framework that encapsulates both Entity Framework and NHibernate in my earnest attempt to keep a project from being too coupled to an specific ORM framework. I named it ToTheEfNhX, short for: To The Entity Framework and NHibernate Elimination


      However there are some principles and approaches that varies between those two ORMs that made me cease the development of that repository component project


      Don't abstract out your ORM, don't abstract things out just for the reason it will be easy for you to switch to another ORM if you don't like the performance of your current ORM. Don't add another layer (e.g., repository, or if you really need to, just add very minimal or thin layer) on top of your ORM, just let the power of your ORM flows to your application



      I'm not saying that it's a futile effort to abstract out ORM differences, but there are many differences in approaches between ORMs that will make one cease the effort for doing so


      when in Rome, do as the Romans do


      Case in point, in order to make the domain models work on both NHibernate and Entity Framework, i.e., instead of adding foreign key property to the model, just maintain an object reference, this domain model works on both NHibernate and Entity Framework:

      public class Person 
      {
           public virtual int PersonId { get; set; }
           public virtual string Firstname { get; set; }
           public virtual string Lastname { get; set; }
      
           public virtual Country DreamCountryToTravel { get; set; }
      }
      


      However, a keen Entity Framework enthusiast shall observe: "Isn't that model expensive to populate? The DreamCountryToTravel property is an independent association, it needed be assigned with an eagerly-loaded object."

      person.DreamCountryToTravel = dbContext.Countries.Find(63); // .Find eagerly loads an object from the database
      


      However, an NHibernater would beg to disagree, "that's the right way to model the business domain, it's very OOP, and you don't need to assign an eagerly-loaded object to DreamCountryToTravel. Session.Load is efficient, it lazily loads an object, it doesn't fetch anything from the database"

      person.DreamCountryToTravel = session.Load<Country>(63);
      


      An EF enthusiasts moving to NHibernate should not (and could not) force this kind of domain model to NHibernate:
      public class Person 
       {
            public virtual int PersonId { get; set; }
            public virtual string Firstname { get; set; }
            public virtual string Lastname { get; set; }
       
            
            public virtual int DreamCountryToTravelId { get; set; }
            public virtual Country DreamCountryToTravel { get; set; }
       }
      


      EF enthusiasts only can use foreign key property in NHibernate though, but it's not the OOP way to map relational to object:
      public class Person 
       {
            public virtual int PersonId { get; set; }
            public virtual string Firstname { get; set; }
            public virtual string Lastname { get; set; }
       
            public virtual int DreamCountryToTravelId { get; set; }
       }
      


      Likewise, an NHibernater moving to Entity Framework, should not force this kind of domain model to Entity Framework, as it will only incur performance problems in Entity Framework:
      public class Person 
       {
            public virtual int PersonId { get; set; }
            public virtual string Firstname { get; set; }
            public virtual string Lastname { get; set; }
       
            public virtual Country DreamCountryToTravel { get; set; }
       }
      


      The repository pattern I've made (that works on both NHibernate and Entity Framework) have the above type of a recommended domain modeling. I readied a LoadStub method for EF (4.1 then) in my utmost hope that someday Entity Framework will offer the same functionality as NHibernate's .Load method, that EF will facilitate OOP and drop the relational/persistence concern that foreign key property is. Here's the LoadStub method:

      person.DreamCountryToTravel = countryRepo.LoadStub(63);
      


      But alas, two versions (EF 4.1 was the latest version when I made ToTheEfnhX) and later, the independent association still can only receive eagerly loaded object and it is still expensive to eagerly load an object, there's still no way to just obtain an object stub/proxy with EF. There's a way though to load stub objects only, but it's for many-to-many relationship only



      And the final straw that led me to cease the development of that ORM-agnostic ToTheEfnhX repository, there's a big difference in approach between the two ORMs when fetching multiple collections. It's hard to abstract them out


      If you still want to create a repository pattern/component/wrappers around your ORM, just don't pull a strawman argument to justify creating one. Here's Ayende calling out one person's strawman argument against Ayende's advocacy to not use repository:


      http://ayende.com/blog/153701/ask-ayende-life-without-repositories-are-they-worth-living


      Don't bindly create a pattern just for the sake of creating a pattern, you might just be reinventing the wheel if you don't realized you already have a wheel. There's no shame on not creating repository pattern when your ORM already has a repository pattern bolted-in


      Avoid overengineering: http://ayende.com/blog/4784/architecting-in-the-pit-of-doom-the-evils-of-the-repository-abstraction-layer



      I wrote this to ease out the pain of one of the teams in our company for having to transition from one ORM to another. I hope this blog reaches the whole team and make them embrace their new ORM

      Will the real OOP please stand up?

      Just because something is using a class doesn't mean it's doing OOP. This is not OOP:
      public class Person
      {
          public virtual int PersonId { get; set; }
      
          public virtual string LastName { get; set; }
          public virtual string FirstName { get; set; }
      
          public virtual int DreamCountryToTravelId { get; set; } 
      }
      


      This is OOP:
      public class Person
      {
          public virtual int PersonId { get; set; }
      
          public virtual string LastName { get; set; }
          public virtual string FirstName { get; set; }
      
          public virtual Country DreamCountryToTravel { get; set; }
      }
      

      Friday, June 6, 2014

      Geeks Shared Vocabulary For The Day: FUGLY

      From a bug ticket:

      Remove non-parameterized SQL from many methods used by login and also fix "FUGLY" SQL used to load up the objectives on the summary. It was using a nasty "inlist" function


      Profanity is the most common programming language :D



      If you are Scott Hanselman fan, you should know better:

      Being generally pleasant and helpful isn't sugarcoating, it's being pleasant and helpful.



      I think the rule of the thumb here, if talking in informal, e.g., around friends, colleagues or peers, it’s ok to use profanity. On conferences, presentation, it might not increase impact

      Wednesday, June 4, 2014

      Not in the same field/industry: Shared vocabulary == Highfalutin

      To an application developers hearing two DBAs resolving an issue and using words like page splitting, extent, covering index, fill factors, sargable, archenemy and whatnot, those words are highfalutin. To a DBA hearing two application developers conversing about cascading dropdown, aggregate root, object graph, bounded context, independent association, those words are highfalutin. Words like those appears more highfalutin if one's native language is not English


      If we don't have shared vocabulary or "highfalutin" word like cascading dropdown, we got to explain things in detail to someone who don't share the same set of industry vocabulary as us, we have to say this: "on this form, we need a dropdown that narrows the list of another dropdown based on the item selected from the first dropdown", see? it's too mouthful; so it's a timesaver to just use a shared vocabulary / "highfalutin" word/phrase: "on this form, we need a cascading dropdown." See? easy-peasy!

      If a word is not used on a daily basis, yet you wanted to introduce it to others, the reception on that word is that it is too highfalutin, big word

      For debaters, politicians and whathaveyou, the word strawman is not highfalutin, they know the meaning of strawman when one of them say that the other one is pulling an strawman argument and should refrain from doing so


      When there are important matters that are being discussed, and one just conveniently cite the person #2 use of highfalutin word even the person #2 just used one "highfalutin" word throughout the whole discourse, person #2 might reply with "please don't bikeshed!", but alas! person #2 will be reluctant to say that since he's already labeled of using highfalutin word. See? almost every words are highfalutin if one can't be bothered to learn the meaning of a handy word, er.. "highfalutin" word


      Shared vocabulary is important, it saves us the hassle of explaining things in length when some things related to that vocabulary comes up very often or shall come up again during a conversation or discourse


      Having said that, here are some four of the shared vocabulary (or highfalutin if you may) engineers could use with each other without being sneered at as being too highfalutin:


      1. Bikeshedding: Technical disputes over minor, marginal issues conducted while more serious ones are being overlooked.

      If someone tend to dwell on the syntax(e.g., suggesting to use string.Empty instead of letting the code use "") of the code instead of the code's functionality, go ahead and say "Please don't bikeshed, it's ok not to use string.Empty, let's focus on the functionalities"


      2. Leaky abstraction: In software development, a leaky abstraction is an implemented abstraction where details and limitations of the implementation leak through.

      jQuery is an abstraction layer that makes all browsers behaves and looks the same API-wise. Example, jQuery's .html is consistent on all browsers; though one can use .innerHTML API directly instead of using jQuery's .html, it's not a good idea to do so, some browsers has buggy implementation and/or not consistent with other standards-conforming browsers

      So if someone is unwittingly or deliberately leaking an abstraction, e.g., using .innerHTML, go ahead and tell him "Please don't leak the abstraction, use jQuery's .html"


      3. SARGable: In relational databases, a condition in a query is said to be sargable if the DBMS engine can take advantage of an index to speed up the execution of the query.

      The DBA looking at your query and said "this condition is not sargable, please re-arrange the expression." Comply then


      4. Strawman: Misrepresenting someone's argument to make it easier to attack

      If someone is trying to undermine your point by using something far from the context of your point, you can remind them not to use strawman argument

      Example: After Will said that we should put more money into health and education, Warren responded by saying that he was surprised that Will hates our country so much that he wants to leave it defenseless by cutting military spending.

      Tip: If you hang around slashdot forum, you'll often encounter geeks opposing strawman arguments



      Shared vocabulary prevents ambiguities in communication

      Sunday, June 1, 2014

      There are developers that are too childish and bikesheddin'

      "I simply want to select the last 4 entries from a table, not too much to ask is it really?!!
      You would think M$ would have covered this one by now!!" – http://stackoverflow.com/questions/10634855/opposite-of-select-top

      Bikeshedding definition: https://en.wikipedia.org/wiki/Parkinson's_law_of_triviality

      Wednesday, May 14, 2014

      High-falutin code #3 Deliberately leaking the abstraction

      Even in modern times, there still are developers who would deliberately leak the abstraction even when there's no compelling reason to do so

      <div id='blah'>Meh</div>
      
      .
      .
      .
      
      var e = document.getElementById('blah');
      e.style.color='red';
      e.innerHTML = "bleh";
      


      Most who would do that would use efficiency as an excuse. Those showboating attitude are akin to what snotty attitude C developers exhibit towards C++ when C++ first came out, saying C++ is inefficient as under-the-hood C++ always pushes an extra parameter (class instance reference) to a function; likewise when C language first came out, assembly language developers see the C language inefficient in generating machine code as compared to their handcrafted assembly language code. We should let the API do the heavy lifting and not leak the abstraction when there's no reason to do so


      It's lamentable there are still some developers who would handcraft their DOM manipulation using pure javascript, i.e., sans the framework, and proudly saying they don't know scant (or doesn't want to know) about jQuery, AngularJS, react and whatnot, that's a thinly veiled humblebragging, to them just because old school === hardcore. If someone got to maintain a code mess from developers bringing-their-20th-century-skills-to-the-21st-century who wrote javascript code sans a framework, you can't blame the new developer who knows where they live


      Worser yet, those abstraction leakers put down new technology and blatantly claim that old approaches are more efficient and new technology are inferior

      Tuesday, April 29, 2014

      Imagine there's no country

      "Imagine there's no country..." – John Lennon

      But alas, humans are subjected to suffer, especially the kind of humans called programmers and what have you


      Having said that, sorting across cultures is one of things we must take into account when making our app locale-aware.


      As of the time of this writing, it's not possible to use JavaScript for localization. We have to use server-side languages

      using System;
      using System.Linq;
      using System.Globalization;
      
      public class Program
      {
          public static void Main()
          {
              var list = new[] {
                  "honesty", "courage", "integrity", "character"
              };
               
                       
              list.OrderBy(x => x).Dump();    
              list.OrderBy(x => x, StringComparer.Create(new CultureInfo("cs-CZ"), true)).Dump();
          }
      }
      



      English sorting:
      1. character
      2. courage
      3. honesty
      4. integrity

      Czech sorting:
      1. courage
      2. honesty
      3. character
      4. integrity

      "...I wonder if you can" – John Lennon

      Sunday, March 30, 2014

      High-falutin Code #1

      "By the time you've got multiple joins, query expressions almost always win" -- Jon Skeet


      But.. there are coders who simply love to write more code, perhaps they feel that the more convoluted-looking their code are the smarter they are. Hence most of them even when the code can sometimes use and be made more readable with Linq, will still use lambda instead. They feel they have elite skills just by using lambda.


      var itemsOwner = 
          items
              .Join (people, i => i.OwnerId, p => p.PersonId, (i, p) => new { Item = i, Person = p })
              .Join (countries, ip => ip.Person.CountryId, c => c.CountryId, (ip, c) => new { ItemPerson = ip, Country = c })
              .Select (x => new { x.ItemPerson.Item.ItemName,  x.ItemPerson.Person.PersonName, x.Country.CountryName });
      



      Those coders need to be in the movie Crank, let's see how they can write multiple joins in no time, let's see if they can still breath after two joins.


      Then the continent name needed be shown on the output:

      var itemsOwner = 
          items
              .Join (people, i => i.OwnerId, p => p.PersonId, (i, p) => new { Item = i, Person = p })
              .Join (countries, ip => ip.Person.CountryId, c => c.CountryId, (ip, c) => new { ItemPerson = ip, Country = c })
              .Join (continents, ipc => ipc.Country.CountryId, z => z.ContinentId, (ipc, z) => new { ItemPersonCountry = ipc, Continent = z })
              .Select (x => new { 
                  x.ItemPersonCountry.ItemPerson.Item.ItemName, 
                  x.ItemPersonCountry.ItemPerson.Person.PersonName, 
                  x.ItemPersonCountry.Country.CountryName,
                  x.Continent.ContinentName
              });
      


      That's the problem with lambda joins, the aliases of multiple lambda joins cascades to the aliases of the subsequent joins. The aliases become unwieldy and deeply nested.



      And there's too many variations of that lambda join, some would prefer the code below, deciding early what properties to project during lambda join. Ironically, though Linq and lambda promotes the use of deferred execution, but here we are, we have a coder deciding upfront that it's better to project user-shown properties right there in the lambda joins.


      var itemsOwner = 
          items
              .Join (people, i => i.OwnerId, p => p.PersonId, (i, p) => new { i.ItemName, p.PersonName, p.CountryId })
              .Join (countries, ipc => ipc.CountryId, c => c.CountryId, (ipc, c) => new { ipc.ItemName, ipc.PersonName, c.CountryName });
      




      And then you need to include the brand, oh the DRY headache!

      var itemsOwner = 
          items                   
              .Join (people, i => i.OwnerId, p => p.PersonId, (i, p) => new { i.ItemName, p.PersonName, p.CountryId, i.BrandId })
              .Join (brands, ipcb => ipcb.BrandId, b => b.BrandId, (ipcb, b) => new { ipcb.ItemName, ipcb.PersonName, ipcb.CountryId, b.BrandName })
              .Join (countries, ipcb => ipcb.CountryId, c => c.CountryId, (ipcb, c) => new { ipcb.ItemName, ipcb.PersonName, c.CountryName, ipcb.BrandName });
      


      See the problem with lambda joins? Aside from too many variations (deciding upfront to project the user-shown properties during joinings vs deferring that decision on final join or select), there's also the hard problem of giving a proper alias for the subsequent joins.



      Then there's a change in the requirement to show the brand name after the item name, you feel the aliases should reflect that fact, so you got to change the alias too:

      var itemsOwner = 
          items                   
              .Join (people, i => i.OwnerId, p => p.PersonId, (i, p) => new { i.ItemName, i.BrandId, p.PersonName, p.CountryId })
              .Join (brands, ibpc => ibpc.BrandId, b => b.BrandId, (ibpc, b) => new { ibpc.ItemName, b.BrandName, ibpc.PersonName, ibpc.CountryId })
              .Join (countries, ibpc => ibpc.CountryId, c => c.CountryId, (ibpc, c) => new { ibpc.ItemName, ipcb.BrandName, ibpc.PersonName, c.CountryName });
      




      The highfalutin coder experiences the problems with unwieldy alias names cascading to subsequent joins, nested aliases, and giving good names for aliases, he decided to wise up; he decided he can avoid all the headaches above just by giving a generic (e.g., src) name for all aliases:


      var itemsOwner = 
          items                   
              .Join (people, src => src.OwnerId, p => p.PersonId, (src, p) => new { src.ItemName, src.BrandId, p.PersonName, p.CountryId })
              .Join (brands, src => src.BrandId, b => b.BrandId, (src, b) => new { src.ItemName, b.BrandName, src.PersonName, src.CountryId })
              .Join (countries, src => src.CountryId, c => c.CountryId, (src, c) => new { src.ItemName, src.BrandName, src.PersonName, c.CountryName });
      


      By the time all the original developers in the project are replaced, new developers will be left scratching their heads why the old developers didn't bother to give self-describing names for aliases.



      Let's say you want to switch the join order (MySQL is notorious on requiring certain order on joins to gain performance) of people and brands..
      var itemsOwner = 
          items                   
              .Join (people, src => src.OwnerId, p => p.PersonId, (src, p) => new { src.ItemName, src.BrandId, p.PersonName, p.CountryId })
              .Join (brands, src => src.BrandId, b => b.BrandId, (src, b) => new { src.ItemName, b.BrandName, src.PersonName, src.CountryId })
              .Join (countries, src => src.CountryId, c => c.CountryId, (src, c) => new { src.ItemName, src.BrandName, src.PersonName, c.CountryName });
      


      ..you cannot nilly-willy re-order the joins without incurring changes on code, you can not just cut-and-paste the code, this doesn't compile:
      var itemsOwner = 
          items                   
              .Join (brands, src => src.BrandId, b => b.BrandId, (src, b) => new { src.ItemName, b.BrandName, src.OwnerId })
              .Join (people, src => src.OwnerId, p => p.PersonId, (src, p) => new { src.ItemName, src.BrandName, p.PersonName, p.CountryId })
              .Join (countries, src => src.CountryId, c => c.CountryId, (src, c) => new { src.ItemName, src.BrandName, src.PersonName, c.CountryName });
      




      Now contrast the humble developer's Linq join code to codes above. The code is very readable:

      var itemsOwner = 
          from i in items
          join p in people on i.OwnerId equals p.PersonId
          join b in brands on i.BrandId equals b.BrandId
          join c in countries on p.CountryId equals c.CountryId    
          select new { i.ItemName, b.BrandName, p.PersonName, c.CountryName };
      


      Then switch the join order of people and brands, the changes in Linq-using code is not invasive compared to lambda-using code, you can just cut-and-paste the code, this compiles:

      var itemsOwner = 
          from i in items
          join b in brands on i.BrandId equals b.BrandId
          join p in people on i.OwnerId equals p.PersonId    
          join c in countries on p.CountryId equals c.CountryId    
          select new { i.ItemName, b.BrandName, p.PersonName, c.CountryName };
      



      If the coder doesn't see problems with lambda joins and still prefer to write joins using it instead of Linq, he need to star in the movie Crank. I would hazard a guess he would die by the time he is in the third or fourth join; or worse yet was required to insert another join between the existing joins, good luck breathing with that task!


      Another lambda join variation, not compounding objects in one alias, giving each joined object their own alias. Drawback is, subsequent joins must repeat the objects from the previous joins, a WET code:
      var itemsOwner = 
          items
              .Join (people, src => src.OwnerId, p => p.PersonId, (src, p) => new { Item = src, Person = p })
              .Join (brands, src => src.Item.BrandId, b => b.BrandId, (src, b) => new { src.Item, src.Person, Brand = b })
              .Join (countries, src => src.Person.CountryId, c => c.CountryId, (src, c) => new { src.Item, src.Person, src.Brand, Country = c })
              .Select (x => new { x.Item.ItemName, x.Person.PersonName, x.Brand.BrandName, x.Country.CountryName });
      


      The coder forgot he is using MySQL, it's optimal to join on brands first, then people. As an exercise, try switching the join order of people and brands of the code above, good luck breathing! http://dotnetfiddle.net/3bvQDy



      Another variation, this requires investing another class to assist you in your adventure on joining using lambda, this also requires you to violate DRY principle:
      var itemsOwner = 
          items
          .Join (people, src => src.OwnerId, p => p.PersonId, (src, p) => new JoinHelper { Item = src, Person = p  } )
          .Join (brands, src => src.Item.BrandId, b => b.BrandId, (src, b) => new JoinHelper { Item = src.Item, Person = src.Person, Brand = b })
          .Join (countries, src => src.Person.CountryId, c => c.CountryId, (src, c) => new JoinHelper { Item = src.Item, Person = src.Person, Brand = src.Brand, Country = c } )
          .Select (x => new { x.Item.ItemName, x.Person.PersonName, x.Brand.BrandName, x.Country.CountryName });
      



      Do you still want to showboat your lambda join skills?



      Time to repent your perceived superiority, use Linq to avoid highfalutin lambda code.



      The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague -- Edsger Dijkstra


      There are cases that lambda is an unnecessary trick, just showboating.

      Friday, March 14, 2014

      Our Reaction To New Technology

      Do you feel technologies like AngularJS, SPA, NoSQL, REST and cloud are against the natural order of things(e.g. ASP.NET, ASP.NET MVC, jQuery, WCF)? There must be a reason why





      If you are distraught by revolutionary technologies even you haven't reached 35 yet, what does excite you? Perhaps you aged way too early?


      Are you willing to trim down old jobs from your resume?


      Perhaps we should have an attitude as young as this CTO: https://twitter.com/b4nn0n/status/347020882511818752



      Happy Coding! ツ

      Thursday, January 9, 2014

      I love the word The

      Want to enforce SchemaName.TableName to your domain models (think AdventureWorks)? i.e., you wanted this:

      var personList = 
          from p in session.Query<Person.Person>
          select p;
      
      var storeList = 
          from s in session.Query<Sales.Store>
          select s;
      


      You can't use namespace..

      namespace Domain.Models
      {
          namespace Person
          {
              public class Person
              {
              }
              public class BusinessEntityContact
              {
              }
          }
      
      
          namespace Sales
          {
              public class Store
              {
              }
          }
      }
      


      ..as developers can opt out of Person or Sales namespace by importing the namespace through C#'s using, some would do this:

      using Domain.Models.Sales;
      
      
      .
      .
      .
      
      
      var list = 
          from p in session.Query<Store>
          select p;
      
      



      To achieve enforcement of Schema name on your domain classes, do this instead:

      namespace Domain.Models
      {
          public static class Person
          {
              public class Person
              {
              }
          
              public class BusinessEntityContact
              {
              }
          }
      
          public static class Sales
          {
              public class Store
              {
              }
          }
      }
      

      However that will not work, it's not allowed for the nested class to have the same name as its containing class, e.g., Person.Person. So we must use some convention to eliminate the compiler error through naming convention, e.g.:


      namespace Domain.Models
      {
          public static class PersonSchema
          {
              public class Person
              {
              }
          
              public class BusinessEntityContact
              {
              }
          }
      
          public static class SalesSchema
          {
              public class Store
              {
              }
          }
      }
      

      But I prefer prefixing the word The:


      namespace Domain.Models
      {
          public static class ThePerson
          {
              public class Person
              {
              }
          
              public class BusinessEntityContact
              {
              }
          }
      
          public static class TheSales
          {
              public class Store
              {
              }
          }
      }
      


      Using that convention, reading the code rolls off the tongue quite nicely:


      var personList = 
          from p in session.Query<ThePerson.Person>
          select p;
      
      var businessContactList = 
          from c in session.Query<ThePerson.BusinessContact>
          select c;
      
      
      var storeList = 
          from s in session.Query<TheSales.Store>
          select s;
      


      Sorry Entity Framework, the Set method doesn't cut it:

      var list = 
          from s in context.Set<TheSales.Store>
          select s;
      


      Happy Coding! ツ