Using implicits to improve your models

Published by on
Tags:

Using implicits can improve the quality of your code and how easy it is to read the code. Lets take for example a simple address, this class is going to have street, town and postcode properties. I want to ensure that only valid postcodes are passed to the class but I still want to be able to assign the postcodes easily. This is where implicits come in. Below is the Postcode class, you can see it has two implicit methods, one to convert a string to the postcode class and one to convert the postcode class to a string.

    public class Postcode
    {
        string _postcode;
        public Postcode(string postcode)
        {
            if (!Regex.IsMatch(postcode, @"^[\w\s\d]*$")) 
                throw new ApplicationException("Not a valid postcode");

            _postcode = postcode;
        }
        public override string ToString()
        {
            return _postcode;
        }
        public static implicit operator Postcode(string postcode)
        {
            return new Postcode(postcode);
        }
        public static implicit operator string(Postcode postcode)
        {
            return postcode.ToString();
        }
    }

An here is my address class:

    public class Address
    {
        public string Street { get; set; }
        public string Town { get; set; }
        public Postcode Postcode {get;set;}
    }

I can then assign and read the postcode as shown below. I know that only a valid postcode can be assigned to the class because of the regular expression. Using this method there is no way an invalid postcode could be passed to the property.

            Address newAddress = new Address();
            newAddress.Street = "3 Nice Road";
            newAddress.Town = "Smallville";
            newAddress.Postcode = "BAZ ER1";

            Console.WriteLine(newAddress.Postcode);

Repositories and factories - Creating a more complex entity

Published by on
Tags:

Following from my post about repositories and factories I am going to look at a more complex entity. This entity will represent a person who can have multiple address. The entities will look something like this:

    public class Person
    {
        public Guid Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public IEnumerable<Address> Addresses { get; set; }
    }

    public class Address : IAddress
    {
        public Guid Id { get; set; }
        public Guid OwnerId { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string Town { get; set; }
        public string County { get; set; }
        public string PostCode { get; set; }
        public AddressType Type { get; set; }
    }

Assuming we are using a database for persistence I don't want to store the individuals details in the same table as the addresses. Our application may have other class that use the Address class and it makes sense to store these together and keep the database properly normalised. We start by making an interface from the Person class to pass to and from the repository that does not include Addresses.

    public interface IPerson
    {
        Guid Id { get; set; }
        int Age { get; set; }
        string FirstName { get; set; }
        string LastName { get; set; }
    }

We can now update the Person class to inherit this interface and pass in the repository that will be used to persist the Person class:

    public class Person : IPerson
    {
        IPersonRepository _repository;

        public Person(IPersonRepository repository)
        {
            _repository = repository;
        }

	.....

We can quickly create a repository and factory class that will retrieve Person objects for us, I won't show the code here but it is included in the source code at the end of the application. So now we can look at populating the list of addresses. To do this we do exactly the same as we did for the simple element, except we must ensure that there is method on the factory called GetAddresses(Guid ownerId) which returns all the addresses for a given Person ID. You may have noticed that we called the parameter ownerId instead of Person ID, this goes back to the fact that multiple classes may have addresses and uncouples the Address class from the Person class. We also need to update the Address class to accept the repository and create methods to persist the address class. The code for the address interface, factory and repository is exactly the same as our simple entity example so I won't go into to much detail.

Now we just need to start putting everything together. Start by updating the PersonFactory to accept the AddressFactory. This will allows use to call the GetAddresses(Guid ownerId) when we populate a Person object.

    public class PersonFactory : IPersonFactory
    {
        IPersonRepository _repository;
        AddressFactory _addressFactory; 

        public PersonFactory(IPersonRepository repository, AddressFactory addressFactory )
        {
            _repository = repository;
            _addressFactory = addressFactory;
        }

        ....

We can now modify the MapToDomain method to call

GetAddresses(Guid ownerId)
on the AddressFactory object to populate the address list.

        private Person MapToDomain(IPerson person)
        {
            return new Person(_repository)
            {
                Age = person.Age,
                FirstName = person.FirstName,
                Id = person.Id,
                LastName = person.LastName,
                Addresses = _addressFactory.GetAddresses(person.Id)
            };
        }

With that done we now have a way of creating a Person with Addresses with each piece of information coming from a different storage location. We can now make use of these classes as below:

            IAddressRepository addressRep = new MemoryAddressRepository();
            IPersonRepository personRep = new MemoryPersonRepository();
            
            AddressFactory addressFact = new AddressFactory(addressRep);
            PersonFactory personFact = new PersonFactory(personRep, addressFact);

            Person somebody = personFact.GetPerson(new Guid("{1BB25355-6ABD-48d3-9FE6-5528C6DAE8E7}"));
            somebody.FirstName = "John";
            //this assumes there is at least one address
            somebody.Addresses.First().Address1 = "32 My House";
            somebody.Addresses.First().Save();
            somebody.Save();

Download: Source Code (.RAR 37.5Kb)

Repositories and factories - Creating a simple entity.

Published by on
Tags:

This post continues on from my first post "Repositories and factories - Introduction". In this post we will look at how to create a simple entity using a repository and a factory.

To start we need to design the properties that our entity is going to have. We are going to use a simple class called Product, this is going to have just a few properties:

public class Product{
	 public Guid Id { get; internal set; }
	 public string Name { get; set; }
	 public string Description { get; set; }
	 public double Price { get; set; }
}

We now need a way to retrieve Product entities, this is where our factory class comes into use. First we need to create an interface for our factory detailing the methods we want:

public interface IProductFactory
{	 
	 Product GetProduct(Guid id);
	 System.Collections.Generic.IEnumerable<Product> GetProducts();
}

Now we need to implement the interface in my concrete class. The factory is not responsible for retrieving the data from the data source, this will be handed of to the repository class. The factory will be responsible for building the product entity based on the data returned by the repository. To make the communication between the repository and factory clearer we are going to create an interface for the Product class. The interface makes it clear the repository what properties need to be persisted and returned from storage, this makes it a lot easier when writing a concrete implementation of the repository.

public interface IProduct
{
        string Description { get; set; }
        Guid Id { get; }
        string Name { get; set; }
        double Price { get; set; }
}

With this we can now create the concrete factory class, the factory class calls methods on the IRepository interface which is detailed further down the post, however you can see that each method called on the IRepository interface returns objects of type IProduct. These are then mapped to domain entities using the MapToDomain method:

    public class ProductFactory : InterfaceTest.IProductFactory
    {
        IProductRepository _repository;
        public ProductFactory(IProductRepository repository)
        {
            _repository = repository;
        }
        public Product GetProduct(Guid id)
        {
            IProduct product = _repository.GetProduct(id);
            return MapToDomain(product);    
        }
        public IEnumerable<Product> GetProducts()
        {
            IEnumerable<IProduct> products = _repository.GetProducts();
            return MapToDomain(products);
        }
        IEnumerable<Product> MapToDomain(IEnumerable<IProduct> products)
        {
            return products.ToList().Select(x => MapToDomain(x));
        }
        Product MapToDomain(IProduct product)
        {
            if (product == null) return null;
            return new Product()
            {
                Description = product.Description,
                Id = product.Id,
                Name = product.Name,
                Price = product.Price
            };
        }
    }

So we have out factory class that builds our entities for use. Now we need to persist them back to the database. Ideally as we don't want to pass the entity back to the factory to save it, if we did we would have to pass a reference to the factory around our application and this would get messy. If we ensure that when the Product entity is created it requires a reference to the repository it came from then we can added a save method to the entity and persist the entity straight back to the repository, so we need to updated the constructor and add a save method:

    public class Product : InterfaceTest.IProduct
    {
	IProductRepository _repository;
        public Product(IProductRepository repository )
        {
            _repository = repository;
            Id = Guid.NewGuid();
        }    
        public void Save(){
            _repository.Save(this);
        }

    }

I then need to update the MapToDomain method in the factory to pass in the repository:

        Product MapToDomain(IProduct product)
        {
            if (product == null) return null;
            return new Product(_repository)
            {
                Description = product.Description,
                Id = product.Id,
                Name = product.Name,
                Price = product.Price
            };
        }

With all this done the IProductRepository should look something like this, I am not going to give any code for a concrete implementation of this interface because the code is pretty straight forward.

public interface IProductRepository{
     void Save(IProduct product);
     IProduct GetProduct(Guid id);
     IEnumerable<IProduct> GetProducts();
}

With all this done we can now use this in our application:

IProductRepository repository = new MemoryRepository();
IProductFactory factory = new ProductFactory(repository);

Product prod = factory.GetProduct(new Guid("{0441907B-45B6-471e-8F7D-A187B81991FC}"));
prod.Name = "box of bananas";
prod.Description = "50 bananas in a large box for a monkey";
prod.Price = 4.5;
prod.Save(); 

This may seem like a little extra working having the factories and repositories but it will allow for my flexibility later on. You can also make the whole task easier using dependency injection to save you having to write so much code.

This post deals with a single entity from a single repository. In the next post I will look at more complex entities that may require multiple repositories.

Repositories and factories - Introduction

Published by on
Tags:

In my next few blogs I will explain how I have used factories and repositories to create entities that are easily testable and allow for a clear separation of responsibilities and are easily testable.

So that it is easier to understand each components task it is best to think of each component as a real world equivalent; so a repository could be thought of as a company that produces a raw material like iron or wood, this is then shipped to a factory to make a product or entity. Like real world factories our factories may require multiple sources of raw material (repositories) to create an entity. For me this analogy makes it a lot easier to start thinking about where different responsibilities live.

When designing how this works I found it best to think of how a product would normally be designed and then produced. The product is designed first before a factory is built or a source of materials found and this makes sense for our entities. I know some developers start by opening their favourite database management tool and designing tables. However by doing this you start to dictate how your entities should be structured and will cause problems later if you find that your entities don't fit this rigid setup. You may also design your application to rely on special features provided by your data source, this will cause problems if your data source changes for some reason, say a database to REST services.

Once we have designed the properties on our entites we want to start thinking about how we want to get these entities, these can be thought of as order lines in the factory, and each line equates to a method we can call on the factory. So I call a method on the factory, the factory then makes requests to the relevant repositories to get the raw materials in needs to make an entity. The entity is then constructed by the factory and the entity is return to my application.

The application then manipulates the entity and needs to save the changes or delete the entity. So for each entity I have a save and delete method which map to an underlying repository which is hidden by the entity. This way the application does not need to worry about where the entity is returned to it just needs to save/delete the entity and the entity takes care of itself.

So in this blog I have given an overview of how my thoughts behind how I use the factories and repositories, in the next post I will give some example code on how to create a simple entity using factories and repositories.

Simple tag cloud calculator

Published by on
Tags:

This is a simple algorithm to create a tag cloud. Once the algorithm has run it outputs a tag container which contains the tag and a group number between 0 and 5 to represent how often that tag is used with 1 being the least used and 6 being the most used.

This was only something I came up with in about 10 minutes so if someone has some great examples of other ways to produce tag clouds please send me a link.

The image on the right is an example of what is outputted.

IEnumerable<Tag> tags = _repository.GetAllTags();

            int totalCount = tags.Max(x => x.Count);
            int boundary = totalCount / 5;
            //if boundary is 0 for some reason this stops an divide by zero error
            boundary = boundary == 0 ? 1 : boundary;

            List<TagContainer< containers = new List<TagContainer>();
            foreach (Tag tag in tags)   
            {
                containers.Add(
                    new TagContainer()
                    {
                        Tag = tag,
                        Group = tag.Count / boundary
                    });
            }

            _view.TagContainers = containers;
 

All blogs tagged with 'csharp'

Projects

Have you read?

My first jQuery plug-in - Element Expander



Blogs by date