Maybe Responsive Design is not such a good idea?

responsive-web-template3

While working on a side project and researching about node.js, I stumbled upon an interesting comment, made by Kiran Prasad, head of the LinkedIn’s mobile development team.

Responsive design might work for uncomplicated, one-off websites, but for applications or networks (such as LinkedIn is), responsive design is actually bad. We’re looking at

  • the entrenched use case [for desktop users],
  • the coffee-and-couch use case [for tablet users],
  • and the two-minute use case [for mobile phone users].

You can’t take a mobile app and just scale it up to tablet or desktop. A lot of responsive design is building one site that works everywhere. This might work for some websites. But it’s a bad approach for others and especially for apps… You have to come up with a completely different design for each of the above use cases.

It made me think, and brought back to mind what a colleague was recently recommending to a client (a cabinet maker company) when they asked about building a mobile version of their website. Others might have jumped on the opportunity and would have suggested a complete website redesign to make it responsive. Instead, he brought up the use case of the user who access their site from their mobile phone. “When could that happen?” he asked. “When would a person browse a cabinet maker’s website on their mobile phone? It could happen when they are at the Home Depot, looking for cabinets and they want to make some quick comparisons. So no need to put on the mobile website any media heavy content, no need to focus on the company history, or on the cabinet maker application. Just simple info about their products, with measurements and prices.

I liked his approach, use-case based. As software engineers we often end up falling to deep into the technical trenches and forget about the end user, who in fact are the people for whom we are ultimately building our products. And working from a use case perspective, responsive design, makes really no sense, because, even though it’s a really cool concept from a technical perspective, it doesn’t necessarily address any of the needs of the end users. It seems to me that it’s just another case of “just because you can do it, it doesn’t mean you should be doing it” type of scenario.

Advertisements

How to use CSS to style a one page web application

This is a cross-post from the digitalian

When building regular web pages we don’t often use absolute positioning in CSS. Recently, though, while building the layout for a one page web application I have been playing around with, I wanted to divide the page in three distinct areas:

  • a fixed header DIV at the top of the page,
  • a fixed footer DIV at the bottom of the page,
  • a content DIV that would stretch between the header and the footer, using the entire space no matter how much content was placed in it.

After some research, I stumbled into a CSS feature (trick?) that allows to easily stretch a DIV vertically by explicitly setting both the top and bottom properties at the same time.
Here is the CSS:

/* The html and body elements cannot have any padding or margin. */
html,
body {
    width: 100%;
    height: 100%;
}

.container {
    width: 100%;
}

/* rows and columns */
.onepage-row, .onepage-col {
    overflow: hidden;
    position: absolute;
    border-radius: 0;
}
.onepage-row { left: 0; right: 0; }
.onepage-col { top: 0; bottom: 0; }
.onepage-scroll-x { overflow-x: auto; }
.onepage-scroll-y { overflow-y: auto; }

/* define header, content and footer areas */
#onepage-header { height: 50px; top: 0; }
#onepage-content { top: 50px; bottom: 50px; }
#onepage-footer { height: 50px; bottom: 0; }

Every onepage-row DIV stretches horizontally from the left edge to the right edge by using left:0 and top:0.

In the HTML (see below) I placed three onepage-row DIVs one on top of the other, and then I positioned them as follows:

#onepage-header { height: 50px; top: 0; } — this anchors the header at the top and sets the height of the header to 50px

#onepage-footer { height: 50px; bottom: 0; } — this anchors the footer at the bottom and sets the height of the footer to 50px

#onepage-content { top: 50px; bottom: 50px; } — this stretches the content DIV all the way from the bottom of the header to the top of the footer, even when no content is placed within it.

<body>
<div class="navbar-inverse onepage-row" id="onepage-header" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <a class="navbar-brand" href="#">header</a>
        </div>
    </div>
</div>
<div id="onepage-content" class="onepage-row">
    Lorem ipsum dolor...
</div>
<div id="onepage-footer" class="onepage-row">
    <div class="container">
        <p>This is a sticky footer</p>
    </div>
</div>

This is the result:

Screen Shot 2013-11-20 at 11.23.44

I have given the content DIV a light gray background color so that it is obvious that the DIV stretches all the way from the header to the footer even though the content doesn’t fill up all the space.

Next, I wanted to divide the content DIV into two areas:

  • a right sidebar of fixed size on the right
  • a main DIV that should use the entire available space on the left

First, I inserted a DIV inside the content DIV with position set to relative. This allows me to place other DIV inside of it in absolute mode, resetting the top / bottom / left / right properties to the container, instead of the browser window.

/* new absolutely positioned rows and columns can be placed relative to this container */
.relative-to-this {
    position: relative;
    width: 100%;
    height: 100%;
}

/* define main content area and right sidebar */
#onepage-main { left: 0px; right: 400px; }
#onepage-right { width: 400px; right: 0px; }

Next, I used the same trick, this time horizontally. I added inside the relative container two onepage-col DIVs (which stretch from top to bottom of the relative container) and I positioned them as follows:

#onepage-right { width: 400px; right: 0px; } — this anchors the DIV to the right margin of the relative container and sets the width to 400px

#onepage-main { left: 0px; right: 400px; } — this stretches the main DIV from the left margin of the relative container to the left margin of the right DIV.

<div id="onepage-content" class="onepage-row onepage-scroll-x">
    <div class="relative-to-this">
        <div id="onepage-main" class="onepage-col onepage-scroll-y">
            Lorem ipsum dolor...
        </div>
        <div id="onepage-right" class="onepage-col onepage-scroll-y">
            Lorem ipsum dolor...
        </div>
    </div>
</div>

This is the result:

Screen Shot 2013-11-20 at 11.24.34

This time I also added to each DIV a onepage-scroll-y class to the two columns so that a scroll bar is automatically added when the content is longer than what can fit in the DIV.

Finally, I wanted to further subdivide the main content DIV into three columns of equal size. In order to achieve this, I first placed another relative-to-this DIV to reset again the top / bottom / left / right properties to the size of the main DIV.

/* divide the main content area in three columns of equal width */
.content-leftcol { left:0; width: 33%; }
.content-centercol { left: 33%; right: 33%; }
.content-rightcol { right:0; width: 33%; }

Next, I placed three onepage-col DIVs, which I positioned as follows:

.content-leftcol { left:0; width: 33%; } — this anchors the left column to the left margin of the relative container and sets the size of the column to 33% of the size of the relative container

.content-rightcol { right:0; width: 33%; } — this anchors the right column to the right margin of the relative container and sets the size of the column to 33% of the size of the relative container

.content-centercol { left: 33%; right: 33%; } — this anchors the center column to the left margin of the right column and to the right margin of the left column

            <div id="onepage-main" class="onepage-col onepage-scroll-y">
                <div class="relative-to-this">
                    <div class="content-leftcol onepage-col onepage-scroll-y">
                        Lorem ipsum dolor...
                    </div>
                    <div class="content-centercol onepage-col onepage-scroll-y">
                        Lorem ipsum dolor...
                    </div>
                    <div class="content-rightcol onepage-col onepage-scroll-y">
                        Lorem ipsum dolor...
                    </div>
                </div>
            </div>

This is the final result:

Screen Shot 2013-11-20 at 11.25.03

For those of you who could be interest in playing with this as well, I “fiddled” the basic concept at http://jsfiddle.net/cy4RR/

How to Set the CSS Class in a Sitecore FieldRenderer

Today I was trying to set the CSS class of a Sitecore FieldRenderer tag. I tried in different ways, using the CssClass attribute, both directly in the sc:FieldRenderer tag and from the codebehind. Didn’t work. Finally I found a post that explains that the correct way is the following:

<sc:FieldRenderer runat="server" ID="myRenderer"
    Parameters="class=myCSSClass" FieldName="My Field" />

Sitecore XAML application Syntax

I’ve been trying to write my own XAML application recently for a client that needed a specific context-menu click function. Sitecore documented this a while back, and although it doesn’t state how to incorporate a dialog, I was able to look into how the existing controls work in the sitecore/shell directory, and figure out how to show the dialog. What I was then missing was how to write the XML layout for the application.

I was able to get together what I needed for this specific application, but then I was curious as to what else I could do. I went through the XAML documentation, but I eventually found the Sitecore documentation that is more relevant. So, for reference, this is the link that explains all the different controls available and the functionality available:

http://sdn.sitecore.net/Articles/XML%20Sheer%20UI/My%20first%20XML%20application.aspx

So – if you want to begin from scratch, this is the place to begin. The important thing to note here is the almost all controls from the Sitecore.Web.UI.HtmlControls namespace is available, and the examples show few of the important ones.

Some other links that helped:

An edited version of this post also appears on The Runtime Report, Mickey Rahman’s Other Persona.

Some interesting features of Sitecore 7

I was just reading the Sitecore 7 preview by MVP Dan Solovay, and I think these are very interesting new features that I look forward to being able to use:

  • Datasources finally support GUIDs, which means that renderings won’t break when items are moved. This is wired into the LinkManager, which means that you will get a warning if you delete an item referenced in a datasource field.
  • Datasources can also be built on search queries. I’d like to see more details on this one, but it certainly feels as a step in the right direction.
  • Search providers are now a pluggable component, with support for enterprise-grade Solr in addition to Lucene, and with support for RESTful-based ElasticSearch on the way. Tim Ward stressed that while Lucene is an acceptable option for normal (fewer than 100 million documents) implementations, Solr offers compelling scalability features (such as support for multiple servers and auto sharding) and can handle billions of documents.
  • All configuration settings for Lucene are now exposed through Sitecore configuration. This gives the developer a number of new knobs to turn in optimizing search performance.
  • LinqToSitecore has been updated from LinqToBuckets by providing IQueryable interfaces to Lucene and Solr. Dan highlights the significance of this explaining that while IEnumerable simply provides an enumeration of items, forcing you to do filter logic in memory (clearly not scalable if you are dealing with large number of objects), an IQueryable implementation builds a query that is executed against an index. Dan also brings up an example, to better explain this: “for instance, suppose you wanted to write a query for all product items that have a price under $10, and let’s say you had a very large number of products. An IEnumerable query would force you to iterate over all of them to select the qualifying items, whereas IQueryable pushes this work to the index.
  • You can reindex a small part of a content tree and you can configure an index to auto-swap, so that a new one is built in a temporary location so that a rebuild does not impact site functionality.
  • HTML caching can now be triggered by an index rebuild (“Clear on Index Update”). Again Dan clarifies the usefulness of this with an example: “This is helpful if your rendering uses index values, in the following scenario: You publish a change, the HTML cache is purged by the publish, but the index has not yet been updated. Bam, you are stuck with a stale value in cache until the next publish. This setting prevents that.
  • Search indexing and retrieval performance is vastly improved. Tim Ward cited that rebuilding an index with 10 million items on Sitecore 6.6 took 27 hours, and this was reduced to 98 minutes on the same equipment with Sitecore 7. Simple retrieval searches time was slashed from 3.9 seconds to 0.3 seconds, and complex searches (sort, date, and wildcard) that produce .Net exceptions on Sitecore 6.6 now work and take the same 0.3 seconds as simple searches.

Dynamic Placeholder Keys

This post is just a bookmark for ourselves to this very interesting solution by Nick Wesselman to resolve the problem we have in Sitecore when adding multiple sublayouts of the same type into another sublayout.
Here is his solution: http://www.techphoria414.com/Blog/2011/August/Dynamic_Placeholder_Keys_Prototype

Even more goodies about Page Editor from Nick in this must-see post: http://www.techphoria414.com/Blog/2012/May/Sitecore_Page_Editor_Unleashed

My Personal Quest towards a Better Dependencies Management

In OOP/OOD, whenever we have a class (let’s call it the consumer) that uses a functionality provided by another class (let’s call this the provider), we have what is called a dependency. The consumer class needs a reference to the provider class in order to be able to access its functionalities. The easiest and most intuitive way to achieve this, is for the consumer to create an instance of the provider class calling one of the constructors of the provider (i.e. to “new” the provider).

Direct Reference

Direct Reference

This creates a tight coupling between the consumer and the provider. Changes to the provider class might require changes to the consumer class as well.

In the introduction of the best-selling book Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, 1995) – often referred to as the Gang of Four (GoF) book – the first principle that is mentioned is: “Program to an interface, not an implementation.” Erich Gamma, one of the author, describes this principle:

Once you depend on interfaces only, you’re decoupled from the implementation. That means the implementation can vary, and that’s a healthy dependency relationship. For example, for testing purposes you can replace a heavy database implementation with a lighter-weight mock implementation. […] So this approach gives you flexibility, but it also separates the really valuable part, the design, from the implementation, which allows clients to be decoupled from the implementation.

Translating this into UML, ideally we should get to the solution defined as a plugin by Martin Fowler in Patterns of Enterprise Application Architecture (P of EAA):

Program to an interface, not an implementation

Program to an interface, not an implementation

This is actually only an ideal solution since the consumer class somehow needs to have a reference to an instance of the provider class and cannot directly instantiate the IProvider interface. A common solution is to introduce a factory in the mix, as show in the following UML diagram. The consumer calls the factory asking it to produce a concrete instance of the Provider class that implements the IProvider interface (the dotted line in the figure shows that, this way, the Consumer class gets a reference to the concrete Provider object).

Using Abstraction

Using Abstraction

This eliminates the tight coupling between the consumer and the provider, but introduces coupling between the consumer and the factory, therefore it is still not an ideal solution.

The generally accepted solution to this problem is to use Inversion of Control (IoC), in which object coupling is bound at run time by an assembler object.

Two common techniques used to achieve this are:

  • Service Locator Pattern
  • Dependency Injection

Service Locator Pattern

Let’s begin by diving into a code snippet that shows how to implement the service locator pattern:

public class Consumer
{
    private readonly IProvider _provider;

    public Consumer()
    {
        _provider = IoCContainer.Get<IProvider>();
    }
}

Using the service locator pattern is easy. A developer just needs to ask the IoC container for a specific service class. The IoC container looks to see if the request class has been configured and based on the lifetime management rules for the class it will either create a new instance or return a previously created instance to the requester. The major drawback to using this pattern is your code needs to direct access to the IoC container, which could introduce a tight coupling between your code and the API of the IoC container.

Dependency Injection

There are many ways in which an object can get a reference to an external module at run time. The two most commonly used are:

  • Constructor Injection, in which the dependencies are provided through the class constructor.
    public class Consumer
    {
        private readonly IProvider _provider;
        public Consumer(IProvider provider)
        {
            _provider = provider;
        }
    }
    
  • Setter Injection, in which the dependent module exposes a setter method that the framework uses to inject the dependency.
    public class Consumer
    {
        private IProvider _provider
        public IProvider Provider {
            get { return _provider; }
            set
            {
                if (value == null) throw new ArgumentNullException("value");
                _provider = value;
            }
        }
    
        public Consumer()
        {
            // code using Provider
        }
    }
    

* * *

Ok, let’s stop here for a second. We mentioned above the Service Locator Pattern. Mark Seemann, author of the book Dependency Injection in .NET, also wrote an interesting blog post in which he declares that the Service Locator is an anti-pattern and should be absolutely avoided. In his words, the problem is that

the Service Locator hides the dependency from a class, causing run-time errors instead of compile-time errors.

Look again at the tiny example of Service Locator few paragraphs above, and imagine that the Consumer class is something that we didn’t code ourselves and that we got from a third party in a DLL assembly, without the source code. As soon as we look at the constructor, all we can see from the outside is that the class has a constructor with no parameters. When we try to call it, though, we get an exception at run-time, because we have not properly configured the IoCContainer before calling the constructor of the Consumer class.

* * *

After having more or less digested all the above, one question I have is: “What is the difference between using the Service Locator anti-pattern and using the Castle Windsor container?” (click the question if you would like to try to help me out)

And when I have a question like that, the first place I go to find help is StackOverflow. Over there, while searching for an answer, I stumbled into an interesting and very controversial answer by Joel Spolsky, co-founder and CEO of Stack Exchange, to a similar question (note: bold in the following quote is mine):

IoC containers take a simple, elegant, and useful concept, and make it something you have to study for two days with a 200-page manual. I personally am perplexed at how the IoC community took a beautiful, elegant article by Martin Fowler and turned it into a bunch of complex frameworks typically with 200-300 page manuals.

I try not to be judgemental (HAHA!), but I think that people who use IoC containers are (A) very smart and (B) lacking in empathy for people who aren’t as smart as they are. Everything makes perfect sense to them, so they have trouble understanding that many ordinary programmers will find the concepts confusing. It’s the curse of knowledge. The people who understand IoC containers have trouble believing that there are people who don’t understand it.

The most valuable benefit of using an IoC container is that you can have a configuration switch in one place which lets you change between, say, test mode and production mode. For example, suppose you have two versions of your database access classes… one version which logged aggressively and did a lot of validation, which you used during development, and another version without logging or validation that was screamingly fast for production. It is nice to be able to switch between them in one place. On the other hand, this is a fairly trivial problem easily handled in a simpler way without the complexity of IoC containers.

I believe that if you use IoC containers, your code becomes, frankly, a lot harder to read. The number of places you have to look at to figure out what the code is trying to do goes up by at least one. And somewhere in heaven an angel cries out.

And that, at least for me, is a clear point against IoC containers. I mean, come on, the fact itself that this answer is the most controversial answer on StackExchange shows that I am certainly not the only one out there that doesn’t get this… at least not yet :)

On the other hand, when I take a look at the following example, I start to see where IoC containers could  be helpful:

IoC Containers are also good for loading deeply nested class dependencies. For example if you had the following code using Depedency Injection.

public void GetPresenter()
{
    var presenter = new CustomerPresenter(new CustomerService(new CustomerRepository(new DB())));
}

class CustomerPresenter
{
    private readonly ICustomerService service;
    public CustomerPresenter(ICustomerService service)
    {
        this.service = service;
    }
}

class CustomerService : ICustomerService
{
    private readonly IRepository repository;
    public CustomerService(IRepository repository)
    {
        this.repository = repository;
    }
}

class CustomerRepository : IRepository;
{
    private readonly DB db;
    public CustomerRepository(DB db)
    {
        this.db = db;
    }
}

class DB { }

If you had all of these dependencies loaded into and IoC container you could Resolve the CustomerService and the all the child dependencies will automatically get resolved.

For example:

public static IoC
{
   private IUnityContainer _container;
   static IoC()
   {
       InitializeIoC();
   }

   static void InitializeIoC()
   {
      _container = new UnityContainer();
      _container.RegisterType<ICustomerService, CustomerService>();
      _container.RegisterType<IRepository, CustomerRepository>();
   }

   static T Resolve()
   {
      return _container.Resolve();
   }
}

public void GetPresenter()
{
   var presenter = IoC.Resolve();
   // presenter is loaded and all of its nested child dependencies
   // are automatically injected
   // -
   // Also, note that only the Interfaces need to be registered
   // the concrete types like DB and CustomerPresenter will automatically
   // resolve.
}

* * *

As it often happens, my quest brought me back to another post by Mark Seemann, and so I finally decided to buy his book “Dependency Injection in .NET” – if not for anything else, just to show my appreciation.

Turned out to be a very good decision, mostly because Mark has the uncommon talent to explain complex software engineering concepts in a way that would make them more or less understandable even by a person who is not a software engineer.

Just to give you an example, in the very first chapter, Mark revisits the common analogy between software interfaces and the electrical socket-and-plug model, and pushes it to the limit using it to explain all the following principles and design patterns:

  • tight coupled composition vs. loosely coupled composition – through the use of the use of abstracted interfaces, where the implementations can be changed and multiple implementations could be created and polymorphically substituted for each other – in other words, the Open/Closed Principle (the “O” in SOLID) 
  • the Liskov Substitution Principle (the “L” in SOLID), which states that “we should be able to replace one implementation of an interface with another without breaking either client or implementation
  • the Null Object design pattern – which states that, instead of using a null reference to convey absence of an object (for instance, a non-existent customer), one uses an object which implements the expected interface, but whose method body is empty. The advantage of this approach is that a Null Object is very predictable and has no side effects: it does nothing.
  • the Single Responsibility Principle (the “S” in SOLID), which states that every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class
  • the Decorator design pattern, which allows to intercept one implementation with another implementation of the same interface. This pattern is designed so that multiple decorators can be stacked on top of each other, each time adding a new functionality to the overridden method(s).
  • the Composite design pattern, which makes it easy to add or remove functionality by modifying the set of composed interface implementations
  • the Adapter design pattern, which can be used to match two related, yet separate, interfaces to each other.

And that’s just in the first chapter.

In the next chapter, Mark takes a simple but realistic example of a standard three-layer application architecture, implementing it twice. The first time he uses a traditional approach, what you and I probably have used many times – well, I don’t really know about you, but I know I did. The second time he uses Dependency Injection (DI). In the end, the architecture is completely reversed, as the final dependency graphs of the two implementations clearly shows:

two-approaches

Following his reasoning behind every architectural choice was an eye opening experience. Nonetheless, while the exercise was incredibly useful, at this point I really didn’t need him to convince me that using DI is better. I already knew that.

Remember, at this point, I still haven’t found the answer to my question: “what is the difference between using the Service Locator anti-pattern and a DI Container?” In other words, I need to learn more about using DI containers, in particular where to use them and how to use them.

I finally found the answer I was looking for in Chapter 3 of Mark’s book, and it turns out that it really is not that difficult to deduce if only we go back to the way Dependency Injection works. We have seen it at the beginning of this (long) post, when I showed the two most common ways of injection, Constructor Injection and Setter Injection. When we use DI, we defer the decision about selecting the dependency to the assembler class, right? And if the assembler class also uses DI, and it should, in order to maintain a loosely coupled architecture, it will also defer that decision to its own assembler class. And so on… all the way to the Composition Root. Mark says:

The longer you defer the decision on how to connect classes together, the more you keep your options open. Thus, the Composition Root should be placed as close to the application’s entry point as possible. […]

You shouldn’t attempt to compose classes in any of the modules because that approach limits your options. All classes in application modules should use Constructor Injection and leave it up to the Composition Root  to compose the application’s object graph. Any DI Container in use should be limited to the Composition Root.

I think this is a good place where to close this long post. The quest continues, obviously, but I think I have shared enough information and resources to allow you to take it from here and continue on your own. I would love to hear your opinions and ideas in regards, so please leave those in the comments to this post.