Prajwal Tuladhar’s Blog
 
programming, life and some random thoughts

Archive for the 'Patterns' Category

Dec 30 2008

Fat Model and Skinny Controller

Published by Prajwal Tuladhar under MVC, PHP, Patterns

Few days ago, I read a post (the post is a bit old) about the the design concept of fat model, skinny controller. After going through that post and this one, for few days I have been thinking and trying to analyze the implementation impact of the concept. I guess I have been petty much impressed after doing some research on the web and going through blogs of experts in this subject.

Fat + Skinny
It won’t be wrong if MVC is called the de-facto pattern of developing web applications. But still, the implementation mechanism of MVC and understanding the overall logic of MVC can be different from developer to developer.
MVC, being mostly implemented in the presentation layer provide powerful mechanism to developers to reuse code (reusing could have been easy if there were only one language or platform to deal with but while developing web applications developers need to deal with many languages and technologies that may or may not integrate well with each other) and significantly apply the concept of object oriented principles and agile methodologies.
Most of the developers and their code I have encountered especially in the PHP seem to embrace the idea of putting business logic in the controller rather than in the model. They regard model as the way only to deal with CRUD operations. It is true that MVC frameworks like Cake and Symphony provide quite powerful ORM capabilities without the need of writing a single SQL query embedding the principles popularized by Rails i.e. convention over configuration, DRY and YAGNI.
But in my opinion, models should not be treated as the the component for dealing with CRUD operations. Model should be responsible for more than that. It’s also true that applying business logic only through models is almost kinda impossible. It’s something like coupling which needs to be reduced but can’t be eliminated completely.
I view controllers as a tunnel that should be responsible for accepting input from the view and passing to the model and accepting raw output from the model and passing it to the view. Making the controller petty fat could make the code difficult to re-use. In reality all these things are easier to say but making the best use of the MVC by making model responsible for most of the business logic and let controllers and views perform their native task can be quite difficult because of the complex nature of the web. Complexity in the sense that there are other languages and technologies as well in the same layer that needs to be integrated and be dealt with. For eg; Server side Flash / SilverLight components, JavaScripts and so on.
So I have been trying for few days to apply the concept of fat model and skinny controller and as expected facing some difficulties especially to make my model more responsible and controller more light or in other word more skinny. Since I was involved in that project from middle so, attaching the business logic only to the model seems quite impossible. So, I am looking forward to do some small project in MVC applying the concept of Fat Model and Skinny Controller.
Until then, I can not claim that this concept must be followed though I still believe this concept should be followed to write re-usable and loosely coupled code.
As usual it would be great if you provide comments and criticisms and I can also know if I am wrong or right.


Comments

Dec 15 2008

Public versus Published - What I have understood

Published by Prajwal Tuladhar under Patterns, Programming

In my previous post, I had posted a link about the interview with the design patterns guru Erich Gamma. After reading that article, I came to know about the concept of public and published method in a component, class or interface.

“Something can be public but that does not mean you have published it.” - Martin Fowler

For past few days, I have been trying to justify this statement. In the process, I did google the term, but I was unable to find any interesting post until I found the white paper written by Martin Fowler himself (I am damn lucky ;) ). The white paper and two answers I got in the stackoverflow about my question regarding public and published concept has helped me a lot to understand and difference between these almost identical terms.

The scenario of public and published arises especially in the distributed environment when one has to publish his/her code in the form of API to other developers. Once the method or interface or class is published, changing it later will certainly break other’s code.

In JAVA and .NET, with release of new version number of methods, class or interface are treated as deprecated. Changing the behavior of those legacy modules means breaking the code being dependent on them. So, attributes like deprecated are used to inform the clients or service caller to updated their code. APIs are not defined by their source rather by contracts usually in the form of documentation or with the use of refactoring tools and sometimes with the help of reverse engineering with the use of Reflection (System.Reflection in .NET)

Here are the list of advices given by Fowler on publishing interfaces:

  • Don’t treat interfaces as published unless they are
  • Don’t publish interfaces inside a team (this one related to code ownership)
  • Publish as little as you can as late as you can
  • Try to make your changes additions

My Implementation

Boeing Dreamliner                           RollsRoye Engine

Lets suppose, Boeing’s Dreamliner uses engine made by Rolls Royce (in reality it does use). For efficient use, there must be a contract between Boeing which call and invoke APIs and services and Rolls Royce which is responsible for designing the contract.

In this scenario, Rolls Royce’s services invoked by Boeing should be according to the contract and the interfaces provided within that contract are all published.

If the contract provides only one interface i.e. IRollsRoyceEngine as published and while other interface as public but not published then, Rolls Royce should be responsible for the change in the IRollsRoyceEngine interface only not IRollsRoyceEngineAnalyzer.

Boeing can of course use IRollsRoyceEngineAnalyzer but Roll Royce is not bind to inform the change in the interface if it happen in the future.

 

Conclusion

Differentiating published and public interface while designing the contract and API can be encouraging thing to do in the context that change will happen and it is inevitable and it’s just the matter of time. Updating an interface should not break the legacy interface.

Hmm…quite easy to say but certainly not so easy to implement in real projects. Now I am really eager to implement the concept of published and public interfaces and see what it is truly worth of!


Comments

Dec 14 2008

A must read design patterns article

I have found relatively old article about the design principle of design patterns dating around June 6, 2005. Though, the article is a bit old dated ( about 2.5 years), after reading it I have definitely learn something new and refreshing about design patterns and especially about the power and flexibility that can be gained from the use of interface.

Old is gold

The four page article in the form of interview with the design pattern guru Erich Gamma, famous for his landmark book Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, 1995) and also a member of popular GoF (Gang of Four) is certainly worth to read if you are interested in design patterns and test driven development.

After reading it, I was able to summarize following points that seem quite interesting and important to me:

  • Program to an interface, not an implementation.
  • Integration between current refactoring tools and XP.
  • Composition over inheritance for low coupling and design flexibility in the sense that sub-class always have to make assumptions about the context of the method it overrides (my favorite).
  • Something can be public but that does not mean you have published it. Quote from Martin Fowler, but I’m still a bit confused about it and still researching. I have even posted a question in the stackoverflow but have been unable to get any response clarifying my confusion.
  • Interface inheritance. I have seen this when I was going through Repository Pattern in NHibernate.
  • Smaller objects configuring the container and customizing the behavior of the container.
  • Consistency in API design (for example: using depravation support in JAVA, .NET). Seems easy but really hard to achieve especially for beginners like me :)
Technorati Tags:

Comments

Oct 15 2008

Introducing Model View Controller (MVC) Pattern

Published by Prajwal Tuladhar under MVC, Patterns, Programming

Model-view-controller (MVC) is both a design pattern and an architectural pattern used in software engineering. - Wikipedia

Historical Background

MVC was started by Ward Cunningham and Kent Beck who were working with SmallTalk and designing GUIs at Xerox PARC. The original implementation is described in depth in the influential paper Applications Programming in Smalltalk-80: How to use Model-View-Controller.

What is Pattern?

A pattern is a solution to a problem in a given context. Christopher Alexander says each pattern is a three-part rule which expresses a relation between a certain context, a problem, and a solution. Pattern in the software development was especially popularized from the publication of the book named Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides or often referred to as Gang of Four (GoF). Design patterns represents a solutions to problems that arise when developing software within a particular context.

What is MVC?

MVC Architecture

MVC can be defined as an architectural pattern that is used while developing interactive application on the web. As the name suggests there are three major components of MVC:

  • Model: Encapsulates core data and logic. Model is often related with the business logic of the application. It knows all the data that needs to be displayed. It is always isolated from the User Interface (UI) and the way data needs to be displayed.
  • View: It is the UI part of the application. It uses read-only methods of the model and queries data to display them to the end users. It may be a window GUI or a HTML page. View encapsulates the presentation of the data, there can be many views of the common data
  • Controller: It acts as a interacting glue between models and views. It accepts input from the user and makes request from the model for the data to produce a new view.

How it works?

How MVC Works

Advantages

  • Separation of Concern: Since MVC has three components whose operations are quite isolated from each other. For example; people working on view part can concentrate only on the UI and the part visible to the end users; people working on model part can concentrate on the business logic and the functional requirements of the system or ‘What’ part of the system and finally people working on the controller section may have knowledge of both view and model section so that interaction between other two components could be made easily. There is clear designation of roles for each stakeholder of a system.
  • Modularized Development: Modularization is the process of dividing any complex problem into smaller sub-modules and we human have been following this approach from the time unknown. In MVC, we divide our system into three parts in order to reduce complexity.
  • Pattern based development: As defined in the earlier section, pattern is the proven solution for any problem in a particular context. MVC itself is a pattern implemented in the presentation layer where it handles user’s interaction (controller) with a particular model through view. MVC is a proven solution for many contexts especially interactive web applications so following it in order to build a system may be comparatively more effective and trust worthy.
  • More Control over URLs: Almost all MVC based frameworks have the feature of URL routing that gives us more control over the URL we desire. For example; http://www.foo.com/prajwal/edit where ‘prajwal’ may be unique ID and ‘edit’ may be controller action.
  • Maintainability and Code Reuse: The Modular design of MVC supports the design goal of reusable software. As MVC requires a definite rule and style for coding, the result can be much more maintainable and reusable software.
  • Test Driven Development: By following MVC, one can easily tests each and every part of the system. Moreover, most of the MVC frameworks do have one or more built-in testing frameworks.
  • Platform and language independent: MVC is simply a pattern which can be implemented in any language or any platforms. Most of the popular languages and platforms like Java, .NET, PHP, Ruby, Python have one or more MVC based frameworks. So you once you know the MVC funda, you can implement in the platform of your choice.

Disadvantages

  • Adds additional level of complexity: MVC can increase the level of complexity of a system since. MVC requires in depth planning so, any wrong decision taken early could impact the whole application life cycle.
  • More files to manage means more headache: This may be context dependent. Some people might feel odd when dealing withe more files. A MVC based system has comparatively more number of files than a non-MVC based system.
  • Rigorous separation between the model and view can sometimes make debugging more difficult: In my experience, debugging a MVC application is still quite difficult as compared to a non-MVC application. I am talking about my experience while working with CodeIgniter, a PHP based MVC framework. But the same is not true when talking about ASP.NET MVC.

Implementations of MVC as web-based frameworks

.NET

PHP

Python

Ruby

Java

Conclusion

As the benefits of MVC out number the disadvantages, in my opinion one should follow this approach when creating interactive web applications with high degree of agility.


Comments

Oct 10 2008

Abstract Class versus Interface

Published by Prajwal Tuladhar under .NET, C#, Patterns, Programming

In software engineering, an abstract type is a type in a nominative type system which is declared by the programmer, and which has the property that it contains no members which are also not members of some declared subtype.
Interface generally refers to an abstraction that an entity provides of itself to the outside. This separates the methods of external communication from internal operation, and allows it to be internally modified without affecting the way outside entities interact with it, as well as provide multiple abstractions of itself. It may also provide a means of translation between entities which do not speak the same language, such as between a human and a computer. Because interfaces are a form of indirection, some additional overhead is incurred versus direct communication. -Wikipedia

In Java, .NET and PHP 5 there are three ways to create and object i.e. inheritance, composition and interface.

  • Inheritance defines “is-a” relationship. Example: Student and Programmer is a Person
  • Composition defines “has-a” relationship. Example: Class Student contains class Book
  • Interface only models the behavior of an object. Example: Student and Programmer are both Nameable and both may have actions.

In Java, .NET and PHP 5, multiple inheritance (child class with more than one parent class) is not allowed so, interface can be used as a powerful tool to separate implementation. Interface is not a strict “is a” relationship. Abstract class represents some sort of implementation and it is a strict “is a” relationship. For example: A dog is a mammal and a reptile is not a mammal showing strict relationship whereas both dog and reptile may be nameable and both may have some actions.

abstract interface example

As we know that interface and abstract class both provide abstract methods so, making the best use of them is crucial in the object oriented paradigm. Abstract class provides both concrete and abstract methods whereas interface provides only abstract methods. Lets go through an example:

Assume that we have an abstract class Person and its concrete implementation class Student and Programmer. We have an interface called IWork that may or may not be implemented by the concrete classes Student and Programmer. We also have a composite class Address, though it is not required while distinguishing between interface and abstract class, using composite class will help us to clarify the scenario.

Class Diagram

Abstract Interface Class Diagram

Abstract Interface Class Diagram

C# Code

Abstract Class - Person

Abstract Class - Person

Interface - IWork

Interface - IWork

Class Address

Class - Address

Class - Programmer

Class - Programmer

Class - Program

Class - Program

Conclusion

  • Classes in a strict inheritance relationship must be related.
  • Interfaces can be used for classes that are not related. In the above example, only Programmer class is implemented but it is not necessary that Student also implements the IWork interface.
  • An interface never provides any implementation, only behavior.

References

You can download the example from here.


Comments

Next »

RSS Feed
Subscribe by email
Follow me @ Twitter