Search This Blog

2011-02-27

iPhone Development: to Objective-C or not to Objective-C ?

When I think of Objective-C, what comes to my mind is a niche programming language for the MacOS and Apple related products. Thus as far as I know this is the only officially supported language to develop products for iPhones, iPods, iPads and so on ....
On the other hand I really what to develop apps that will work in Windows, Linux and MacOS, and for this purpose I see two options:

1) Develop in C/C++ and try to find tools that translate this code to Objective-C and/or MacOS

2) Use Objective-C to develop any kind of application (at least desktop and mobile apps)

Developing portable iPhone apps outside Objective-C


Swig

For the first option, there is swig ( http://www.swig.org/ ) which is a wrapper for C++ to export its classes and/or functions to several languages (Objective-C is a work in progress).
However it doesn´t really solve the problem because there are libraries.

Mono Touch

The Mono Touch ( http://monotouch.net/ ) is probably one of the most interesting project to develop apps for the iPhone without Objective-C. It makes it possible to develop apps with C#.NET. The same Mono project also make it possible to develop apps for Linux. As a consequence, C#.NET could be seriously considered to develop apps for a wide range of platforms. However unlike Mono one must pay to start using it which may not be a problem if you are familiarized with C#.NET.

PhoneGap

Another options is PhoneGap ( http://www.phonegap.com ) which is an open-source framework whose objective is to let developers to write apps with HTML5+CSS+JavaScript and execute it to the different mobile platforms including iOS.

Objective-C as a portable programming language


I recently read about he mechanics and philosophy of Objective-C language and I got quite impressed by its features. It is not just C with classes as I heard before, it is actually a powerful dynamic language. Everything is an object including the classes itself what reminds me of Smalltalk, LISP and Python.

There are also some options to use Objective-C outside of the Apple ecosystem:

GNU Step

As stated in their website ( http://www.gnustep.org/ ) the objective is to create an open version of Cocoa (former NextStep) for several platforms including Linux and Windows.

Besides porting the API this project also comes with several developer tools such as an IDE named ProjectCenter and a GUI code generator called Gorm.

Publishing ClickOnce winforms applications with command-line MSBuild

One of the most interesting characteristics of tools such as CCNet and Nant is the automated deploy. I found many examples of how to publish an application with pre-configured projects with click-one but I wanted to do it different. In order to make the project file cleaner the approach was to remove all click-once configurations from the project(*.csproj) so that command-line MSBuild will take care of publication configuration in a NAnt script. After some full-days of research, I found the solution below. I hope it helps in your project.
<exec program="${dotnetFrameworkDir}\MSBuild.exe">
  <arg value="${basePath}\MyProject\MyProject.csproj"></arg>
  <arg value="/target:publish"></arg>
  <arg value="/p:IsWebBootstrapper=true"></arg>
  <arg value="/p:SignManifests=true"></arg>
  <arg value="/p:ManifestKeyFile=${basePath}\MyProject\MyCertificate.pfx"></arg>
  <arg value="/p:TargetZone=LocalIntranet"></arg>
  <arg value="/p:GenerateManifests=true"></arg>
  <arg value="/p:PublishUrl=${clickOnceDir}"></arg>
  <arg value="/p:Install=true"></arg>
  <arg value="/p:InstallFrom=Web"></arg>
  <arg value="/p:UpdateEnabled=true"></arg>
  <arg value="/p:UpdateRequired=true"></arg>
  <arg value="/p:InstallUrl=http://myPublishUrlAddress"></arg>
  <arg value="/p:TargetCulture=pt-BR"></arg>
  <arg value="/p:ProductName=MyProject"></arg>
  <arg value="/p:PublisherName=MyCompany"></arg>
  <arg value="/p:MinimumRequiredVersion=${CCNetLabel}"></arg>
  <arg value="/p:CreateWebPageOnPublish=true"></arg>
  <arg value="/p:WebPage=${webPage}"></arg>
  <arg value="/p:OpenBrowserOnPublish=false"></arg>
  <arg value="/p:ApplicationRevision=17"></arg>
  <arg value="/p:ApplicationVersion=${CCNetLabel}"></arg>
  <arg value="/p:CreateDesktopShortcut=true"></arg>
  <arg value="/p:PublishWizardCompleted=true"></arg>
  <arg value="/p:BootstrapperComponentsLocation=Absolute"></arg>
  <arg value="/p:BootstrapperComponentsUrl=${bootstrapperUrl}"></arg>
  <arg value="/p:GenerateBootstrapperSdkPath=${pathBootStrapper}"></arg>
  <arg value="/p:UpdateUrlEnabled=false"></arg>
</exec>

2010-06-03

Tools and Utilities for the .NET Developer

Here is a list I got from the internet that might be useful (at least for a while):

http://geekswithblogs.net/mbcrump/archive/2010/05/25/tools-and-utilities-for-the-.net-developer.aspx

2010-05-09

Using Fluent Builder Pattern to Configure Test Objects

Depending on the complexity of the domain model, configuring mock objects for specific cenarios can make the resulting test code to get messy.

Consider the situation below with C#, NUnit and Moq framework

[Test]
[ExpectedException(InvalidPaymentAgreementException)]
public void PaymentAgreementMustNotBeCreatedWhenThePaymentOptionIsNotValidForTheDebtType()
{
  Mock somePaymentOptionMock = new Mock();
  Mock debTypeMock = new Mock();
  debtTypeMock
    .Setup(debtType.GetPaymentOptions())
    .Returns(new List(){somePaymentOptionMock.Object});

  Mock anotherPaymentOptionMock = new Mock();

  Mock debtMock = new Mock();
  debtMock.Setup(debt.DebtType).Returns(debTypeMock.Object);            

  PaymentAgreement paymentAgreement = new PaymentAgreement(
    new PaymentAgreementCreationParameter()
    {
      AgreementYear = SystemDate.Get().Value.Year,
      AgreementNumber = 1,
      AgreementCreationDate = SystemDate.Get().Value.Date,
      NumberOfInstallments = 1,
      AgreementValue = 100.0m,
      Debts = new List() { debtMock.Object },
      SelectedPaymentOption =  anotherPaymentOptionMock.Object
    });
}

A developer who reads the unit test can take a consirable amount of time to understand what is actually being tested even if a well-designed mock framework such as Moq is in use. Most of this work is about configuring mock objects. Besides the code size, the unit test doesn´t speak the language of the domain (business) and thus it becomes a mass of meaningless mock configuration.
I am on my way to learn how to apply TDD effectvely in software development and I quickly realized that the quality of unit tests are very important in order to this kind of methodology to succeed.

Accidentally some days I read an interesting post from Andrian about Rich Domain Tests at http://adrianhummel.wordpress.com/ and I decided to apply his idea.
After reading his post I got to the conclusion that one way to solve or at least minimize this unit-test-messy-code-problem was by using a fluent builder pattern to configure mock objects by using a builder whose interface could be describe how I am configuring a mock object with an interface closer to domain language.

The unit test below is a rewritten from the example above with the concepts described here:

[Test]
[ExpectedException(InvalidPaymentAgreementException)]
public void PaymentAgreementMustNotBeCreatedWhenThePaymentOptionIsNotValidForTheDebtType()
{
  PaymentOption somePaymentOption = PaymentOptionMockBuilder
                                    .Begin()
                                    .BuildPaymentOption();

  DebtType debtType = DebtTypeMockBuilder
                      .Begin()  
                      .AddPaymentOptionOf(somePaymentOption)
                      .BuildDebtType();
            
  PaymentOption anotherPaymentOption = PaymentOptionMockBuilder
                                       .Begin()
                                       .BuildPaymentOption();          
            
  Debt debt = DebtMockBuilder
              .Begin()
              .WithDebtTypeOf(debtType)
              .BuildDebt();

  PaymentAgreement paymentAgreement = new PaymentAgreement(
    new PaymentAgreementCreationParameter()
    {
      AgreementYear = SystemDate.Get().Value.Year,
      AgreementNumber = 1,
      AgreementCreationDate = SystemDate.Get().Value.Date,
      NumberOfInstallments = 1,
      AgreementValue = 100.0m,
      Debts = new List &lt Debt &gt () { debt},
      SelectedPaymentOption =  anotherPaymentOption
    });

}

The fluent builder for Debt is DebtMockBuilder and can be programmed as follows:

    public class DebtMockBuilder
    {
        private Mock _debtMock;

        public static DebtMockBuilder Begin()
        {
            DebtMockBuilder builder = new DebtMockBuilder();
            builder._debtMock = new Mock();
            return builder;
        }

        public Debt BuildDebt()
        {
            return _debtMock.Object;
        }

        public DebtMockBuilder WithDebtTypeOf(DebtType debtType)
        {
            this._debtMock.Setup(debt => debt.DebtType).Returns(debtType);
            return this;
        }
    }

PaymentOptionMockBuilder follows the same idea.

Although I see that some improvements are needed I could see the following advantages from fluent mock builders:

  • The test code was easier to understand because domain terms were applied instead of specific API language.


  • Specific mock framework calls were encapsulated which theoretically can let programmers to use another mock framework in other projects or using more than one mock framework in the same test (I dont know why someone would do such a thing...).


  • Finally mock configuration becomes more flexible since existing methods don´t have to be modified to include new configuration but only a new configuration method is needed. Thus mock configuration can evolve as needed without loosing the domain interface.

2010-05-08

Test-Driven-Development Best Practices

I recently read a very intersting conversation in StackOverflow.com about test-driven development. I found it very instersting and the principles can be summarized as follows: (not ordered by importance)

1. Write the test first, then the code. Reason: This ensures that you write testable code and that every line of code gets tests written for it. 



2. Design classes using dependency injection. Reason: You cannot mock or test what cannot be seen. 


3. Separate UI code from its behavior using Model-View-Controller or Model-View-Presenter. Reason: Allows the business logic to be tested while the parts that can't be tested (the UI) is minimized. 


4. Do not write static methods or classes. Reason: Static methods are difficult or impossible to isolate and Rhino Mocks is unable to mock them. 


5. Program off interfaces, not classes. Reason: Using interfaces clarifies the relationships between objects. An interface should define a service that an object needs from its environment. Also, interfaces can be easily mocked using Rhino Mocks and other mocking frameworks. 


6. Isolate external dependencies. Reason: Unresolved external dependencies cannot be tested. 


7. Mark as virtual the methods you intend to mock. Reason: Rhino Mocks is unable to mock non-virtual methods.

8. Use creational design patterns. This will assist with DI, but it also allows you to isolate that code and test it independently of other logic.



9. Write tests using Bill Wake's Arrange/Act/Assert technique. This technique makes it very clear what configuration is necessary, what is actually being tested, and what is expected.


10. Don't be afraid to roll your own mocks/stubs. Often, you'll find that using mock object frameworks makes your tests incredibly hard to read. By rolling your own, you'll have complete control over your mocks/stubs, and you'll be able to keep your tests readable. (Refer back to previous point.)


11. Avoid the temptation to refactor duplication out of your unit tests into abstract base classes, or setup/teardown methods. Doing so hides configuration/clean-up code from the developer trying to grok the unit test. In this case, the clarity of each individual test is more important than refactoring out duplication.


12. Implement Continuous Integration. Check-in your code on every "green bar." Build your software and run your full suite of unit tests on every check-in. (Sure, this isn't a coding practice, per se; but it is an incredible tool for keeping your software clean and fully integrated.)

Reference: http://stackoverflow.com/questions/124210/best-practices-of-test-driven-development-using-c-and-rhinomocks

2010-02-24

Name Convention for Object Oriented Apps

Some time ago I came across with a question about naming conventions for different parts of the software: UI, Service, Entities, etc. I decided to share some of the conventions I have been using.


Naming Convention: ( Most used ):

Entities: As it is part of the domain package, no prefixes or suffixes here: Ex: Car, Client, etc.

Repository: Usually a suffix Repository. Ex: ClientRepository, CarRepository, etc.

ValueObject: Value objects are part of the domain so it follows entity´s convention. Ex: Money, Address, etc.

DTO: Usually a suffix DTO. Ex: ClientRegistrationDTO, CarRentDTO, AddressDTO, etc.

Service: Usually a suffix Service. Ex: ClientRegistrationService, CarRentService, etc.

Namespace Convention: (My Suggestion)

Entities, ValueObjects, Repositories Interfaces, Domain Services (Domain Layer)
..Domain.
Ex: Acme.Finantial.Domain.Debt,
      Acme.HR.Domain.CheckOvertimeService,
      Acme.Core.Domain.IPersonRepository    

Application Services 
..Service.
Ex: Acme.Sales.Service.ClientRegistrationService

Presentation Layer
..Presentation.
Ex: Acme.HR.Presentation.IClientRegistrationView, Acme.HR.Presentation.WebClientRegistration

Persistence Layer
..Persistence.
Ex: Acme.Core.Persistence.PersonRepositoryImpl (<--- implementation in NH, for example)

2010-02-22

Unit Testing Linq Queries in Moq

After some google research and experimentation I found that it was not worth to mock methods that return IQueryable or IQueryable because in order to use it programmers have to make use of extension methods. And this kind of methods are not supported by Moq ( a minimalistic mock framework ). This is the DAO interface I want to test.
public interface IDAOFactory
{
  public abstract IQueryable Query();
}
This is the moq unit test that fails, since I can´t use Linq directly.
[Test]
public void LinqQueryTest()
{ 
  // This moq configuration will trigger an exception – Can´t make use of extension methods
  daoFactoryMock.Setup(d => (from o in d.Query()
    where o.Id >= 0
    select o.Id).ToList())
    .Returns( new List() { 1, 2 } );
}
It turns out that the solution is easily solved by using a collection as a data source.
[Test]
public void LinqQueryTest()
{
  // Creates a IQueryable from a Collection
  IList lstOrders = new List() { 
    orderMock1.Object, 
    orderMock2.Object, 
    orderMock3.Object };
  IQueryable orderQuery = lstOrders.AsQueryable();

  // Configures the Query to return IQueryable implementation
  daoFactoryMock.Setup(d => d.Query()).Returns(orderQuery);

  // Now the linq queries can be used naturally 
  IList lstResult = (from o in daoFactoryMock.Object.Query() where o.Id >= 0 Select o).ToList();

  // Checking output results
  Assert.AreEqual(3, lstResult.Count);
}
It is important to notice that the collection elements that should also be mock objects must contain all the necessary data in order to make the correct test.

2009-12-26

Model View Controller with Events in .NET

This is often a confused design pattern and its main purpose is to separate objects that assume different roles in a software.
These roles are:
  • models - objects that actual execute the system tasks
  • views - objects that display the system data
  • controllers - objects that capture the user intentions from the view and route to the right actions
Usually Views have a reference to the controller however another approach below shows how to decouple the views from the controllers.
Views can be implemented in several ways depending on the UI library. For that reason, views are better represented as interfaces. However in order to reduce coupling between views and controllers, events can be used in the interface views.
The example below shows a client registration view:
using System;
namespace MyController
{
  public interface IClientRegistrationView
  {
    public long Id { get; set; }
    public string Name { get; set; }
    public string Registration { get; set; }
    public event ClientEventHandler InsertRequested;
    public event ClientEventHandler UpdateRequested;
    public event ObjectIdEventHandler &lt long &gt RemoveRequested;
    public event ObjectIdEventHandler &lt long &gt RetrieveRequested;
  }
}
Specific event arguments were also created for the Client Registration View:
  • ClientEventArgs - contains client fields so that it can be sent to the underlying layer.
  • ObjectIdEventArgs - contains a generic object id for deletion and queries purposes.

See event argument classes below:

using System;
namespace MyController
{
  public delegate void ClientEventHandler(object sender, ClientEventArgs e);
  public class ClientEventArgs : EventArgs
  {
  public long Id { get; set; }
  public string Name { get; set; }
  public string Registration { get; set; }
  }
}

using System;
namespace MyController
{
  public delegate void ObjectIdEventHandler &lt T &gt (object sender, ObjectIdEventArgs &lt T &gt e);
  public class ObjectIdEventArgs &lt T &gt : EventArgs
  {
    public T Id { get; set; }
  }
}


The controller will have a reference to a view (an interface) and it will access the view´s data fields for the client which is Id, Name and Registration.
Besides that, the controller will also be told to trigger actions by listening to the view´s events.
In this example, the service acts as if it was the model of the system.

using System;
using MyService;
namespace MyController
{
  public class ClientRegistrationController
  {
    private IClientRegistrationView View { get; set; }
    private ClientRegistrationService Service { get; set; }
    public ClientRegistrationController(IClientRegistrationView view)
    {
      View = view;
      View.InsertRequested += new ClientEventHandler(View_InsertRequested);
      View.UpdateRequested += new ClientEventHandler(View_UpdateRequested);
      View.RemoveRequested += new ObjectIdEventHandler &lt long &gt (View_RemoveRequested);
      View.RetrieveRequested += new ObjectIdEventHandler &lt long &gt (View_RetrieveRequested);
      Service = new ClientRegistrationService();   
    }
    void View_InsertRequested(object sender, ClientEventArgs e)
    {
      ClientDTO dto = new ClientDTO() { Id = e.Id, Name = e.Name, Registration = e.Registration };
      Service.Insert(dto);
      this.View.Id = dto.Id;
    }
    void View_UpdateRequested(object sender, ClientEventArgs e)
    {
      Service.Update(new ClientDTO() { Id = e.Id, Name = e.Name, Registration = e.Registration });
    }
    void View_RemoveRequested(object sender, ObjectIdEventArgs &lt long &gt e)
    {
      Service.Remove(e.Id);
    }
    void View_RetrieveRequested(object sender, ObjectIdEventArgs &lt long &gt e)
    {
      ClientDTO dto = Service.Retrieve(e.Id);
      this.View.Id = dto.Id;
      this.View.Name = dto.Name;
      this.View.Registration = dto.Registration;
    }
  }
}
As it can be seen above, the View doesn´t need to have a reference to the Controller. The view is totally decoupled form the controller but it can communicate with it by listening to the events.

2009-09-27

Extreme Programming Impressions

Whe I first read about XP Programming in 2002 ( http://www.extremeprogramming.org/ ) which is one of the agile methodologies for software development I didn't take it seriously.
At that time the authors of this methodology were saying that software didn´t need to be documented, models were not necessary or useful at all, people should be the documentation of the software, etc.
Immediately it came to my mind that it couldn´t work for many small (and big) software companies due to several problems:

– Software companies are constantly loosing and hiring workforce so how can they work if they keep loosing “documentation” which is on people´s minds ?

– How can they know the "what", "where" and "how" in the source code ?

Some years have passed and this methodology has matured and besides that other good methodologies of the same family like Scrum have come up too.
It called my attention that many state-of-art tech companies like Google and Yahoo! were working with Scrum and I started to get curious to know what it is about.

Five years later I decided to attend to a presentation about XP Programming in order to get a broader picture about it. It helped me to remove some miths I had such as the lack of documentation. Actually the Agile Methodology do not remove the activity of producing documentation but it just gave a different meaning for the documentation. The documentation should be provided if relevant for developers. It doesn´t have to include fancy diagrams but only the necessary information such as what is the system about, how to compile source-code, or other information that it is not self-explained in the system.

After reading "The Toyota Way" I noticed that agile methodologies was greatly inspired by this administration model. This model is basically driven to reduce waste, in other words, we should do only the necessary to accomplish our objectives, no more or no less. By reducing waste we are also reducing unnecessary work what can mean different things depending on our project such as no documentation, few documentation, no models, etc.

Therefore to be lean (and consequently agile), one must think on what tasks are been carried out and what tasks in the process should be eliminated if they have no value. Read the book above to have a good idea of the process.

2009-08-27

DynamicProxy: An Elegant Solution for Session/Transaction/Exception Management in NHibernate (or any other ORM)

Session management is a well solved problem for web applications and many detailed solutions can be found in the internet. The same is not true for winforms applications. Although there are solutions available in the internet, many of them are theoretical or just “complicated” for the medium programmer. Besides that it was difficult to find a solution (I have never found one) that could work for both web and winforms applications.

After a while (days), it came up to me the idea of using service proxies with Castle Dynamic Proxies. It turned out to be the easiest and cleanest approach I could think of because it has the ability to inject (aspects) behaviour around the service methods.

The idea can be coded in the following way:
  • Service classes with standard namespace and virtual methods


namespace Sample.Service
{
  public class SystemLogRegistrationService
  {
    public virtual void Modify(long codLogSistema)
    {
      SystemLog systemLog = Repository.Get().Load(codLogSistema);            
      systemLog.SetMachine = "MAQUINA" + DateTime.Now;
      systemLog.SetUserName = "PESSOA" + DateTime.Now;            
      systemLog.SetSystemName = "SISTEMA" + DateTime.Now;
      Repository.Get().Save(systemLog);            
    }
  }
}


Do not get distracted with the service code. The important thing to notice above is that the service does not contain anything else other than processing the domain classes (in this case, SystemLog). Also note that all service methods must be virtual. Without that, dynamic proxy won't work for these methods. The details of Repository implementation are out of the scope of this article and this subject is covered in enough details in several articles throughout the internet. (You can also send me a comment or email if you need information about that)

  • Usage Example


In order to make use of proxified services, one must create some kind of generator whose creation will be explained next. The ProxyGenerator below is a simple static class for didactic purposes that is responsible for dynamically generate proxies from a given type injecting the necessary aspects such as session/transaction management and exception handling or any other aspect you might think about.

SomeService serv = ProxyGenerator.InjectSessionTransactionExceptionAspects &lt SomeService &gt ();
serv.Modify(12048); // <= Modify method has session/transaction/exception management
  • Creating a proxy service factory
The proxy generator can be implemented using Castle Dynamic Proxy API.
using System;
using Castle.DynamicProxy;

namespace Sample.Persistence
{
  public static class ProxyGenerator 
  {
    private static ProxyGenerator _generator = new ProxyGenerator();        
    public static TService InjectSessionTransactionExceptionAspects &lt TService &gt ()
    {
      return (TService)_generator.CreateClassProxy(
        typeof(TService),
        new SessionTransactionExceptionAspect());    
    }
  }
}
  • An interceptor for the service class methods
using System;
using Castle.DynamicProxy;
using NHibernate;
using NHibernate.Context;

namespace Sample.Persistence
{
  /// 
  /// Intercepts service methods (must be virtual) and inject
  /// session / transaction and exception aspects
  /// 
  public class SessionTransactionExceptionAspect: IInterceptor
  {
    /// 
    /// Intercepts service methods and adds the following behaviors
    /// >>> Before executing a method:
    ///     * opens session
    ///     * begins transaction
    /// >>> After executing method:
    ///     * Commits transaction
    /// >>> In case there is exception
    ///     * Rollbacks transaction
    ///     * Handles exception
    /// >>> At the end
    ///     * Closes session
    /// 
    public object Intercept(IInvocation invocation, params object[] args)
    {
      object retorno = null;
      ITransaction tx = null;
      try
      {          
        CurrentSessionContext.Bind(SessionFactory.Instance.OpenSession());
        tx = SessionFactory.Instance.GetCurrentSession().BeginTransaction();
        retorno = invocation.Proceed(args);
        tx.Commit();
      }
      catch (Exception exception)
      {
        if (tx != null) { tx.Rollback(); }
          throw exception;
      }
      finally
      {
        ISession s = SessionFactory.Instance.GetCurrentSession();
        s.Close();
        CurrentSessionContext.Unbind(s.SessionFactory);
      }
      return retorno;
    }
  }
}
Above is the center of the whole idea. The interceptor class above captures only the service methods and ignores the rest. The following tasks are executed inside a try-catch-finally: (when it is a service method)
  • Session is created
  • Transaction is initialized
  • The method itself is executed
  • if method is ok, transaction is confirmed
  • if there is exception, transaction is cancelled and exception is handled
  • Finally session is closed

2009-08-21

Avoid "Tall" DAO Factories

A "tall" DAO factory can be defined as a big class that contains too much methods for each business class that compounds your domain model.

public class DAOFactory
{
IClass1DAO GetClass1DAO() { ... }
IClass2DAO GetClass2DAO() { ... }
IClass3DAO GetClass3DAO() { ... }
IClass4DAO GetClass4DAO() { ... }
IClass5DAO GetClass5DAO() { ... }
IClass6DAO GetClass6DAO() { ... }
IClass7DAO GetClass7DAO() { ... }
IClass8DAO GetClass8DAO() { ... }
IClass9DAO GetClass9DAO() { ... }
IClass10DAO GetClass10DAO() { ... }
: : : :
}


Besides big, these kind of class should be modified every time a new domain class is added to your system.
In order to avoid that to happen, one good option is to use a generic method for all DAO interfaces.

public class DAOFactory
{
ICommonDAO GetDAO < I > ( ) where I : ICommonDAO { ... }
}


The action of searching the corresponding DAO interface implementation can be easily achieved by using .NET reflection support for Assemblies and Types.

2009-06-13

Agile Modeling in Software Projects

Recently Jeff Sutherland mentioned another certification for software programmers since Scrum does not include software engineer techniques but very present in XP (extreme programming) management. That is probably the reason why many software developers work with Scrum and XP methodologies together.

However although XP is very software-programming oriented it is still not enough to have a good software design in large systems projects. Additionally in many organizations it is very difficult to find a product owner that fully understand the business rules and can manage the software functionalities.

In order to efficiently use Scrum, there must be someone responsible for understanding the business. If there is no product owner, one employee must be chosen to study and logically model the business. That is exactly why a good business modeling is imperative before any large software development.

Good software design and business understanding prevents or reduces significantly re-work tasks. It is considered wasted work since these tasks do not devliver anything useful to the client and often happens when developers did not captured well the business rules.

Thus the following software development process is proposed to match DDD and agile approach. In this software process, there can be product owners, developers and scrum masters just like original Scrum the difference is that before the sprints (see Scrum reference) can start, a long DDD session is necessary in order to produce a good business model.

Briefly describing the following steps should be taken:

  1. A selected person assumes the role of Product Owner
  2. Product Owner becomes responsible for studying and building a business model
  3. Product Owner writes all the system features using User Stories (from XP)
  4. Product Owner schedules a Planning Meeting with the Scrum Master and Developers to present User Stories and the Business Model
  5. Scrum Master schedules a Sprint Meeting with developers to plan the Next Sprint based on the Stories
  6. Developers begin the Sprint (from 1 to 2 weeks)
  7. Scrum Master Organizes Daily Meetings with Developers (just like Scrum)
  8. At the end of the Spring, Scrum Master schedules a Weekly Meeting to present the system to the Product Owner but it also includes the developers of the project who makes considerations about the system presented
  9. Scrum Master organized a Retrospective Meeting with the developers to discuss what went wrong or right with the Sprint and then they start planning the next Sprint.
  10. Go to Step 6 until Product Owner gets satisfied

2009-06-10

How the repository pattern works ?

The classes that represent the elements of a domain must contain all the business logic inside it such as tax calculation, name validation, etc. However in many circumstances it is also necessary to access data in order to complete the business logic inside these classes.

Take the example below:

Suppose I want to create an instance from the Client class and that clients must have a name and an address (there may be more information but lets stay with those two data for simplification purposes).
So, this could be instantiated like: (C# code)

// Open database connection (and Begin Transaction)
SessionManager.Open( );
: : :
// Parameters are: name, zipcode, adress number, address complement, country
Client client = new Client(“New Client”,”12500”,12,“Room 14”,Country.US);
: : :
// Close database connection (and Commit Transaction)
SessionManager.Close( );

Although simple, the line above hides many steps such as:
  • Check if client name is valid
  • Check if zipcode exists in the county US
  • Check if address number is correct
  • Check if addres complement id correct
  • Check if there are clients with the same name and address
  • Proceed with the client creation
However in order to complete some of this steps, the Client object should be able to access the data layer and that is the responsibility of the repositories. According to Martin Fowler's website: Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.
Reference: http://www.martinfowler.com/eaaCatalog/repository.html

In order to make it possible the code line above, an Address and Client class must be implemented.

See full code listing below:

// Address is a value object used by Client class
public class Address
{
public Address(string zipCodeNumber,int number,string addrComplement)
{
// Check if zipcode number exists in the country (ZipCode Repository uses SessionManager inside it)
IZipCodeRepository zipCodeRepository = RepositoryManager.GetRepository( );
ZipCode zipCode = zipCodeRepository.Get(zipCodeNumber,country);
if (zipCode == null) { throw new NonExistentZipCodeException(zipCodeNumber,country);
// Check if address number is correct
if (number <= 0) { throw new InvalidAddressNumberException(number); }
// Check if address complement is correct
if (complement.Trim( ) == string.Empty) { throw new InvalidAddressComplementException(addrComplement)); }
// Sets values
this._zipCode = zipCode;
this._number = number;
this._complement = complement;
}
private ZipCode _zipCode = null;
public ZipCode ZipCode get { return _zipCode; }
private int _number = 0;
public int Number { get { return _number; } }
private string _complement = string.Empty;
public string Complement { get { return _complement; } }
}

// Now the Client class
public class Client
{
private long _id;
public long Id { get { return id; } set { this.id = value; } }
private string _name = string.Empty;
public Name
{
get { return _name; }
// Check if name is valid
set
{
if (name.Trim( ) == string.Empty) { throw new InvalidNameException(); }
// Check if there are Clients with same name and address
IClientRepository clientRepository = RepositoryManager.GetRepository();
bool exists = clientRepository.ClientExists(name,zipCodeNumber,number,addrComplement,country);
if (exists) { throw new ClientExistsException( ); }
this._name = value;

}
}
private Address _address;
public Address { get { return _address; } }
public Client(string name,string zipCodeNumber,int number,string addrComplement,Country country)
{
// Creates a Client
this.Address = new Address(zipCodeNumber,number,addrComplement,country);
this.Name = name;
}
}

Repositories have at least two advantages:
  • It removes data specific code from the domain classes which are concerned only about business logic
  • It allows unit tests since repositories are referred as interfaces in domain classes and thus fake repositories can be created without depend on database connection

2009-03-12

Using .NET Nullable Types with NHibernate 1.2

Originally, NHibernate 1.2 does not support nullable types from .NET such as DateTime?, int?, bool?, etc. but that can be solved by implementing specific NHibernate specific user types.
Not all nullable user types are listed for all .NET nullable types are listed below. But it can be easily done by following the example specially for numeric types.
However if you need help you jut send an email.

Nullable user types code listings:

NullableDateTimeType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.UserTypes;
using NHibernate;
using System.Data;
using NHibernate.SqlTypes;

namespace Utilitario.GerenciaDados
{
  public class NullableDateTimeType : IUserType
  {
      #region IUserType Members
      public bool Equals(object x, object y)
      {
          return object.Equals(x, y);
      }
      public int GetHashCode(object x)
      {
          return x.GetHashCode();
      }
      public object NullSafeGet(IDataReader rs, string[] names, object owner)
      {
          //object valor = NHibernateUtil.DateTime.NullSafeGet(rs, names[0]);
          object valor = null;
          if (rs[names[0]] != DBNull.Value)
              valor = Convert.ToDateTime(rs[names[0]]);

          DateTime? dateTime = null;

          if (valor != null)
          {
              dateTime = (DateTime)valor;
          }
          return dateTime;
      }
      public void NullSafeSet(IDbCommand cmd, object value, int index)
      {
          if (value == null)
          {
              NHibernateUtil.String.NullSafeSet(cmd, null, index);
          }
          else
          {
              DateTime? dateTime = (DateTime)value;
              NHibernateUtil.AnsiString.NullSafeSet(cmd, dateTime.Value.ToString("yyyy/MM/dd HH:mm:ss.fff"), index);
          }
      }
      public object DeepCopy(object value)
      {
          return value;
      }
      public object Replace(object original, object target, object owner)
      {
          return original;
      }
      public object Assemble(object cached, object owner)
      {
          return cached;
      }
      public object Disassemble(object value)
      {
          return value;
      }
      public SqlType[] SqlTypes
      {
          get { return new SqlType[] { new StringSqlType() }; }
      }
      public Type ReturnedType
      {
          get { return typeof(string); }
      }
      public bool IsMutable
      {
          get { return false; }
      }
      #endregion
  }
}

NullableBooleanType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.UserTypes;
using NHibernate;
using System.Data;
using NHibernate.SqlTypes;

namespace Utilitario.GerenciaDados
{
  public class NullableBooleanType : IUserType
  {
      #region IUserType Members
      public bool Equals(object x, object y)
      {
          return object.Equals(x, y);
      }
      public int GetHashCode(object x)
      {
          return x.GetHashCode();
      }
      public object NullSafeGet(IDataReader rs, string[] names, object owner)
      {
          object valor = NHibernateUtil.Boolean.NullSafeGet(rs, names[0]);
          bool? caracter = null;
          if (valor != null)
          {
              caracter = (bool)valor;
          }
          return caracter;
      }
      public void NullSafeSet(IDbCommand cmd, object value, int index)
      {
          if (value == null)
          {
              NHibernateUtil.Boolean.NullSafeSet(cmd, null, index);
          }
          else
          {
              bool? caracter = (bool)value;
              NHibernateUtil.Boolean.NullSafeSet(cmd, caracter.Value, index);
          }
      }
      public object DeepCopy(object value)
      {
          return value;
      }
      public object Replace(object original, object target, object owner)
      {
          return original;
      }
      public object Assemble(object cached, object owner)
      {
          return cached;
      }
      public object Disassemble(object value)
      {
          return value;
      }
      public SqlType[] SqlTypes
      {
          get { return new SqlType[] { new StringSqlType() }; }
      }
      public Type ReturnedType
      {
          get { return typeof(string); }
      }
      public bool IsMutable
      {
          get { return false; }
      }
      #endregion
  }
}

NullableCharType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.UserTypes;
using NHibernate;
using System.Data;
using NHibernate.SqlTypes;

namespace Utilitario.GerenciaDados
{
  public class NullableCharType : IUserType
  {
      #region IUserType Members
      public bool Equals(object x, object y)
      {
          return object.Equals(x, y);
      }
      public int GetHashCode(object x)
      {
          return x.GetHashCode();
      }
      public object NullSafeGet(IDataReader rs, string[] names, object owner)
      {
          object valor = NHibernateUtil.Character.NullSafeGet(rs, names[0]);
          Char? caracter = null;
          if (valor != null)
          {
              caracter = (Char)valor;
          }
         return caracter;
      }
      public void NullSafeSet(IDbCommand cmd, object value, int index)
      {  
          if (value == null)
          {
               NHibernateUtil.Character.NullSafeSet(cmd, null, index);
          }
          else
          {
              Char? caracter = (Char)value;
              NHibernateUtil.Character.NullSafeSet(cmd, caracter.Value, index);
          }
      }
      public object DeepCopy(object value)
      {
          return value;
      }
      public object Replace(object original, object target, object owner)
      {
          return original;
      }
      public object Assemble(object cached, object owner)
      {
          return cached;
      }
      public object Disassemble(object value)
      {
          return value;
      }
      public SqlType[] SqlTypes
      {
          get { return new SqlType[] { new StringSqlType() }; }
      }
      public Type ReturnedType
      {
          get { return typeof(string); }
      }
      public bool IsMutable
      {
          get { return false; }
      }
      #endregion
  }
}

NullableDecimalType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.UserTypes;
using System.Data;
using NHibernate.Util;
using NHibernate;
using NHibernate.SqlTypes;

namespace Utilitario.GerenciaDados
{
  public class NullableDecimalType : IUserType
  {
      #region IUserType Members
      public bool Equals(object x, object y)
      {
          return object.Equals(x, y);
      }
      public int GetHashCode(object x)
      {
          return x.GetHashCode();
      }
      public object NullSafeGet(IDataReader rs, string[] names, object owner)
      {
          object valor = NHibernateUtil.Decimal.NullSafeGet(rs, names[0]);
          Decimal? inteiro = null;
          if (valor != null)
          {
              inteiro = (Decimal)valor;
          }
          return inteiro;
      }
      public void NullSafeSet(IDbCommand cmd, object value, int index)
      {
          if (value == null)
          {
              NHibernateUtil.Decimal.NullSafeSet(cmd, null, index);
          }
          else
          {
              Decimal? inteiro = (Decimal)value;
              NHibernateUtil.Decimal.NullSafeSet(cmd, inteiro.Value.ToString().Replace(',','.'), index);
          }
      }
      public object DeepCopy(object value)
      {
          return value;
      }
      public object Replace(object original, object target, object owner)
      {
          return original;
      }
      public object Assemble(object cached, object owner)
      {
          return cached;
      }
      public object Disassemble(object value)
      {
          return value;
      }
      public SqlType[] SqlTypes
      {
          get { return new SqlType[] { new StringSqlType() }; }
      }
      public Type ReturnedType
      {
          get { return typeof(string); }
      }
      public bool IsMutable
      {
          get { return false; }
      }
      #endregion
  }
}

NullableDoubleType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.UserTypes;
using NHibernate;
using NHibernate.SqlTypes;
using System.Data;

namespace Utilitario.GerenciaDados
{
  public class NullableDoubleType : IUserType
  {
      #region IUserType Members
      public bool Equals(object x, object y)
      {
          return object.Equals(x, y);
      }
      public int GetHashCode(object x)
      {
          return x.GetHashCode();
      }
      public object NullSafeGet(IDataReader rs, string[] names, object owner)
      {
          object valor = NHibernateUtil.Double.NullSafeGet(rs, names[0]);
          Double? valorD = null;
          if (valor != null)
          {
              valorD = (double)valor;
          }
          return valorD;
      }
      public void NullSafeSet(IDbCommand cmd, object value, int index)
      {
          if (value == null)
          {
              NHibernateUtil.Double.NullSafeSet(cmd, null, index);
          }
          else
          {
              Double? valor = (Double)value;
              NHibernateUtil.Double.NullSafeSet(cmd, valor.Value.ToString().Replace(',','.'), index);
          }
      }
      public object DeepCopy(object value)
      {
          return value;
      }
      public object Replace(object original, object target, object owner)
      {
          return original;
      }
      public object Assemble(object cached, object owner)
      {
          return cached;
      }
      public object Disassemble(object value)
      {
          return value;
      }
      public SqlType[] SqlTypes
      {
          get { return new SqlType[] { new StringSqlType() }; }
      }
      public Type ReturnedType
      {
          get { return typeof(string); }
      }
      public bool IsMutable
      {
          get { return false; }
      }
      #endregion
  }
}
NullableInt32Type.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.UserTypes;
using System.Data;
using NHibernate.Util;
using NHibernate;
using NHibernate.SqlTypes;

namespace Utilitario.GerenciaDados
{
  public class NullableInt32Type : IUserType
  {
      #region IUserType Members
      public bool Equals(object x, object y)
      {
          return object.Equals(x, y);
      }
      public int GetHashCode(object x)
      {
          return x.GetHashCode();
      }
      public object NullSafeGet(IDataReader rs, string[] names, object owner)
      {
          object valor = NHibernateUtil.Int32.NullSafeGet(rs, names[0]);
          Int32? inteiro = null;
          if (valor != null)
          {
              inteiro = (Int32)valor;
          }
          return inteiro;
      }
      public void NullSafeSet(IDbCommand cmd, object value, int index)
      {
          if (value == null)
          {
              NHibernateUtil.Int32.NullSafeSet(cmd, null, index);
          }
          else
          {
              Int32? inteiro = (int)value;
              NHibernateUtil.Int32.NullSafeSet(cmd, inteiro.Value, index);
          }
      }
      public object DeepCopy(object value)
      {
          return value;
      }
      public object Replace(object original, object target, object owner)
      {
          return original;
      }
      public object Assemble(object cached, object owner)
      {
          return cached;
      }
      public object Disassemble(object value)
      {
          return value;
      }
      public SqlType[] SqlTypes
      {
          get { return new SqlType[] { new StringSqlType() }; }
      }
      public Type ReturnedType
      {
          get { return typeof(string); }
      }
      public bool IsMutable
      {
          get { return false; }
      }
      #endregion
  }
}

2008-12-26

Extremely Short Introduction for Ruby on Rails

Ruby on Rails

This file contains brief descriptions of a Ruby on Rails project.

Important Rails Commands

Here a list of the most relevant rails command-line programs organized by task:

  • Starting a Rails Project: rails

  • Executing a Rails Project: ruby script\server ( on application directory )

  • Generating a new Model: ruby script\generate model

  • Generating a new Controller: ruby script\generate controller


Directory Contents

app

Holds all the code that's specific to this particular application.

app/controllers

Holds controllers that should be named like weblogs_controller.rb for automated URL mapping. All controllers should descend from ApplicationController which itself descends from ActionController::Base.

app/models

Holds models that should be named like post.rb.

Most models will descend from ActiveRecord::Base.

app/views

Holds the template files for the view that should be named like weblogs/index.erb for the WeblogsController#index action. All views use eRuby syntax.

app/views/layouts

Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the layout :default and create a file named default.erb. Inside default.erb, call <% yield %> to render the view using this layout.

app/helpers

Holds view helpers that should be named like weblogs_helper.rb. These are generated for you automatically when using script/generate for controllers. Helpers can be used to wrap functionality for your views into methods.

config

Configuration files for the Rails environment, the routing map, the database, and other dependencies.

db

Contains the database schema in schema.rb. db/migrate contains all the sequence of Migrations for your schema.

doc

This directory is where your application documentation will be stored when generated using rake doc:app

lib

Application specific libraries. Basically, any kind of custom code that doesn't belong under controllers, models, or helpers. This directory is in the load path.

public

The directory available for the web server. Contains subdirectories for images, stylesheets, and javascripts. Also contains the dispatchers and the default HTML files. This should be set as the DOCUMENT_ROOT of your web server.

script

Helper scripts for automation and generation.

test

Unit and functional tests along with fixtures. When using the script/generate scripts, template test files will be generated for you and placed in this directory.

vendor

External libraries that the application depends on. Also includes the plugins subdirectory. This directory is in the load path.

How does Model, View and Controller relate to each other ?

The application directory is structured like below:

app

|-controllers

|-models

|-views

The fastest way to generate a complete crud for a model is to generate a controller with the scaffold option:

> script/generate scaffold blog title:string content:text date_created:datetime

After understanding of ruby-on-rails it is considered better practice to generate models, views and controllers separately:

  • To generate a blog controller, one must type:

> script/generate controller blog

Result: a BlogController class will be generated at app/controllers in BlogController.rb

  • To generate a blog model, one must type:

> script/generate model blog

Result: a Blog class will be generated at app/model in blog.rb

  • views can not be generated, you have to go to app/views/blog and create a blog.html.erb.

Views for BlogController are automatically assigned in app/views/blog by name convention. ( Since BlogController will have a blog directory in app/views ).

Views in app/views/blog, must have a *.html.erb extension and an index.html.erb must be created for initial page. Other auxiliary pages can be created in the same directory with different names.

In order to add/remove/update models fields, one must only update the corresponding table in the data model only. After that the following command should be executed to update the models in Ruby-on-Rails:

> rake db:migrate

2008-11-23

Generating Software Documentation from Unit Tests

In the beginning of my career as a software developer I participated in two software projects with the traditional approach of document-first and code later. It didn't take too much time for me to realize this was a not a good aproach. We passed months capturing requirements and writing use cases just to find later that many use cases was actually different from what the stakeholders needed and many requirements have changed.

Then I came across with agile software development. The idea behind made perfect sense for me and some work colleagues and we started to introduce slowly this new paradigm in our department. Projects that lasted 1 year ( yes ! 1 year ) or more now lasted only a couple of months. Besides that because we were demonstrating the software every week or two to the stakeholders and thus we had feedback often from them.
This made us more productive and the final product (the software!) gained more quality and more confidence. But what happened to our business documentation ? We didn't drop a line of it.

Many agilists advocate that agile software development is about absence of documentation. Recently many agilists say it is not removing documentation but that it is seen from a different perspective from document-oriented traditional approach. Only the real necessary documentation is produced. Although it sounds perfectly reasonable we still need a way to document business rules for the IT sector managers and also stakeholders. They couldn't read and understand these rules directly from the source-code since they were not programmers or technicians. So I started to think of a way to automatically generate this documentation.

I was talking to Anselmo from Siemens and he gave me an interesting idea: Automatic generation of business documentation from unit tests. I started thinking how could I implement this alternative in our software architecture model where we have a service class for each use case and I got to the idea below:

For a Client Registration use case we could have the following unit tests:
[TestFixture][BusinessRules] // Business rule attribute means this test must be documented
class Client_Registration_Use_Case
{
[Test]
void Normal_Flow__Check_if_name_is_not_null() { ... }

[Test]
void Normal_Flow__Check_if_address_is_valid() { ... }

[Test]
void Normal_Flow__Check_if_there_is_another_client_with_same_name() { ... }

[Test]
void Normal_Flow__Save_New_Client() { ... }

[Test ExpectedException(typeof(NullClientNameException)) ]
void Alternative_Flow__If_client_name_is_null_raise_message_to_the_user() { ... }

[Test ExpectedException(typeof(InvalidClientAddressException)) ]
void Alternative_Flow__If_client_address_is_invalid_raise_message_to_the_user() { ... }

[Test ExpectedException(typeof(ClientNameAlreadyExistsException)) ]
void Alternative_Flow__If_another_client_with_the_same_name_was_found_raise_message_to_the_user() { ... }
}


At the end, a script in the continuous integration process can read this file or assembly and transform very easily this information and save to a documentation file such as Docbook, ODT or Word Doc. It is important to note that test methods should be placed in the right order so that the right documentation can be generated. The only work is reading the class and methods names and generate the documentation as follows:

-----------------------------------------------------------------
Client Registration Use Case:

Normal Flow:
  1. Check if name is not null
  2. Check if address is valid
  3. Check if there is another client with same name
  4. Save New Client
Alternate Flows:
  1. If client name is null raise message to the user
  2. If client address is invalid raise message to the user
  3. If another client with the same name was found raise message to the user
-----------------------------------------------------------------

This idea has the following advantages:
  • Documentation reflects exactly what was implemented in the software code and never gets outdated
  • If a new check or action is needed in a use case documentation, the implementation and NOT documentation is changed
  • In order to update the documentation, new unit tests are required what can force discipline among the programmers
  • Every time a release is generated the entire application documentation is updated since the proper unit tests are written
There disadvantages as well:
  • Unit tests become more verbose what can slow down its implementation a little bit
  • Test methods descriptions may not reflect the test performed inside
However I still believe the benefits are higher and I wonder if someone is not applying this idea since it sounds so simple. If you have any ideas for agile business documentation please get in touch with me.

2008-08-19

Efficient Software Development Process with Open-Source Tools for .NET

When a software is been built, a series of characteristics must be pursuit in order to deliver a quality product during the development process:
  • Agility
  • Testability
  • Readability
  • Extensibility
  • Automated Documentation
It it important to say that I presume many readers of this text are already convinced about the advantages brought by object oriented programming when compared to traditional development and the tools presented below support this kind of programming paradigm besides the goals specified above.

Object-Relational Mapping Tool: Castle Project Active Record

One of the most time-consuming things in software development is mapping classes in tables.
This process is partially automated by tools such as NHibernate but the Active Record offered by Castle Project not only maps classes to tables but it is also capable to generate the database from the object model which confers agility to the software process.
http://www.castleproject.org/activerecord/index.html

Source-Code Standards: FXCop

Although it is free, FXCop is not a free-software since its code is private owned by Microsoft.
Anyway it is very a useful tool whose objective is to verify if quality metrics and/or naming conventions of a project are been followed appropriately by the team members.
By using naming well defined and known programming conventions, code readability is enhanced and different projects can be understood by every programmer in a software company.
http://msdn.microsoft.com/en-us/library/bb429476(VS.80).aspx

Unit Tests: NUnit

It is the most used automated testing tool for .NET . These tests play an important role in a software project since they bring more confidence to developers to change software when needed since they can point out when a certain piece of the software might be broken due to some modification. Obviously NUnit brings testability to the software development environment.
http://www.nunit.org/index.php

Test Coverage: PartCover

How can you know what parts of your code is being covered by automated tests ?
This process is called test coverage and it is the objective of PartCover.
Altough NCover is largely mentioned in the net, PartCover is becoming increasingly
important as a test coverage open-source project.
http://sourceforge.net/projects/partcover/

Automated Documentation: NDoc

Documentation can be a time consuming task but without it, the software extensibility and maintainability can slow down considerably specially for people outside the project and unaware of coding practices. One of the fastest ways to get documentation is generating it from the source-code. NDoc can generate developer level documentation from the XML tags in the C# source-code.
http://ndoc.sourceforge.net

Web Framework: MonoRail

The Castle Project seems to understand what is to have an agile development. Having this in mind, MonoRail is a web framework that truly obeys the MVC Design Pattern without slowing developers down. Besides agile, this framework lets us to have an improved readability also compared to traditional ASP.NET programming.
http://www.castleproject.org/monorail/gettingstarted/index.html

Continuous Integration: Cruise Control .NET

Prior sections some tools for software quality were presented such as FXCop, NUnit, PartCover and NDoc. Although useful it is very easy for one of the team members to forget to manually execute some of this tools during the development process. Remembering and executing these tools can also be error prone since some member of the team can forget to execute some of these tools.
In order to overcome these drawbacks and others, continuous integration rised as one the most known practices from Extreme Programming (XP). ( See XP in http://www.extremeprogramming.org/ )
Basically continuous integration is performed by a build tool such as Cruise Control ( http://cruisecontrol.sourceforge.net/ ) that is responsible for executing specified tasks necessary prior to software delivery to the users such as compilation checking, unit tests executing, quality metrics verification and finally publication. However another combination of tasks can be though such as email notification and many others.
Generally the continuous integration process is executed manually or during the night when there is low activity but it is possible to trigger this process through a version control system such as SVN prior to accept a commit requested by a team programmer.

2008-07-24

Scrum as a criteria for Venture Capital Groups

I just read a Foreword from Jeff Sutherland ( co-creator of Scrum ) from the book "Scrum and XP from the Trenches" where he comments how he chooses companies who really apply Scrum framework ( an agile framework or methodology to develop software ) for a venture capital group as an agile coach.

The more time pass the more I realize how agile software development will play an important role in near future. It already plays an important role but it can become a requirement for startup companies in search for funding from venture capital groups.

If a company can not deliver its products in time or can not deliver working software or can not deliver something that was not what the client was expecting, it should not be expected that they would receive funding. As Mike Cohn cited in the same book in his foreword, agile development is not about beautiful documentation or future-problem-proof code, it is about software done and working. And that's exactly what clients need and expect from a software company.
At the same time, Scrum as well as other kinds of agile software ideas ( be it frameworks, methodologies or practices ) is very easy to put in practice. Any company or organization can start using this idea anytime they want.

If you have an idea about how is the Scrum process in five minutes or so, take a look at this articles: http://www.softhouse.se/Uploades/Scrum_eng_webb.pdf

Addionally the book "Scrum and XP from the Trenches" mentioned in the beginning of this post can be downloaded here: http://www.infoq.com/minibooks/scrum-xp-from-the-trenches

Personally, as a software developer and a small investor I will take Jeff's tip for future investments in tech companies.

2008-07-18

5 Things You Should Remember about NHibernate

NHibernate is probably the most used ORM (object-relational mapping tool) for .NET applications and it is based in Hibernate the most used ORM in Java for years.
The learning curve to start working with NHibernate can be reduced if you remember the take the following steps:

1) The domain class should have at least one public or protected parameterless constructor

2) The domain classes' public properties and methods must declared with the virtual reserved word

3) For XML mappings, remember to rename your mapping files ending with *.hbm.xml not only *.xml

4) Also for XML mappings, remember to set the property of each file to embedded resource instead of content

5) Avoid using composite-id's classes as much as you can since they don't work very well when used in cascade collections and they make development more difficult

Unit Tests Rule Software Development

Even after a relatively long time using object oriented systems we still couldn't deal well with a growing problem. The lack of automated tests.

The absence of unit tests reduce the programmers confidence about the system and makes it very difficult if not impossible to modify the source-code. Since each modification can cause a lot of other bugs and undesired side-effects in other parts of the system or in other systems, the system can not evolve with the changing business rules and the changing technological knowledge.

Well that was true some months ago, now we are building a lot of unit tests for the systems already in production. Ironically due to some good architectural choices such as persistence isolation and POCO objects, it was not difficult to start testing with the Stub technique. It was all there, we just started creating test cases.

In reality, although not the ideal way, a set of use-case tests are being implemented in order to assure the right execution of what was working before. So the service layer is tested not the business objects at this time.

Now we are looking for automated ways to create mode real test cases in other to produce all the tests we need as fast as we can. Perhaps a testing framework will be necessary.