Reactive bindings with MutableProperty. ReactiveCocoa

MutableProperty is an easy way for keeping track of value changes and reacting on this changes.

NOTE: Here I am using ReactiveCocoa playground form ReactiveCocoa. If you want to use ReactiveCocoa in your project you need to instal it wit Carthage or CocoaPods.

I will take an example with simplified View and Presenter form VIPER architecture.

Let’s say your View has a label and its text should be changed any time the corresponding data source for this label changed in presenter. You can make this to be automatic with MutableProperty.

Here we have View and Presenter. View has only one simple label. Presenter a bit more interesting. It has instance of a View, that is set via init, MutableProperty of type String, viewDidLoad and updateLabel methods.

To construct Presenter you need to pass an instance of a View to Presenter’s init. Then viewDidLoad is being called. And this is the most interesting part. ReactiveCocoa adds reactive extension for UILabel. And text in view.label.reactive.text is bondable target of type String?. If you press Option key and click on it you will see:

bind MutableProperty to BindingTarget

We can bind MutableProperty to BindingTarget and the label’s text will be updated automatically any time the value of MutableProperty is changed. This is done by <~ operator.
updateLabel method is for updating value of our mutable property. Here we just set incoming string to value of mutableProperty text. Anyone can call it on presenter and the label on View will be updated.

So, let’s check it out:

First we initialise View, then we initialise presenter and pass created View as incoming parameter. Then we call viewDidLoad on presenter. Remember that binding is happening here. The last thing is calling updateLabel on presenter and printing text of View’s label.

After viewDidLoad got called, any time someone calls updateLabel on presenter text of View’s label will be updated without directly touching the label.

I hope this was useful for you, Subscribe and get more posts from me.

The Decorator Pattern in Swift

The Decorator Pattern is used when we need to extend or change object’s functionality dynamically (at runtime). It allows the behavior of individual objects to be changed without requiring changes to that classes, or to classes that are using those objects. The changes in behavior created with the decorator pattern can be combined to create complex effects without needing to create large numbers of subclasses.

Implementation

Decorator Pattern Implementation

The participants objects in the decorator pattern are:

Component – Interface for objects that can have responsibilities added to them dynamically.
ConcreteComponent – Defines an object to which additional responsibilities can be added.
Decorator – Maintains a reference to a Component object and defines an interface that conforms to Component’s interface.
ConcreteDecorator – Concrete Decorators extend the functionality of the component by adding state or adding behavior.

The most important detail in the Decorator Pattern is that Decorator confirms to Component interface and also has a Component object. This means that Decorator has a Component and it is a Component at the same time. And that allows us not only decorate some concrete components but also to decorate other decorators, as they are components too. Doing so we can create complex layers of decorations.

Decorations layers

From the Decorator perspective it always looks like it decorates a Component because each previous decorator is, in fact, a Component :

Decorator perspective on Decoration layers

Example

Let’s start with component interface, for simplicity I will call it TheThing.

In TheThing protocol we say that each Thing should have getDescription method.

So let’s create a few Things:

Now we will work on decorators. Firstly we need to create decorator interface.

Remember, decorator should be a component and also it should have a component. By confirming to TheThing protocol we made it to be a component, the same way as FirstThing and SecondThing. But additionally it has theThing property.

Next we will create a few concrete decorators:

Look closely to getDescription method in DecoratorOne and DecoratorTwo. This is the most interesting part. Here we alter behaviour of a component the decorator will decorate. We take results of getDescription from theThing, that is assigned in init method, add what we want and then return all together.

Let’s see how it works:

Let’s add one more layer of decoration.

As you can see print(decoratorTwo.getDescription()) prints all our chain, from original “First Thing” of component to “, With Second decorator” of second decorator. Each time we decorate an object the decorator sees it as a component, it has no idea that it also was a decorator. The decorator just takes behaviour of whatever object it decorates, and adds its own behaviour.

We can also completely ignore the behaviour of component and return what we want. All what we need is one decorator, something like this:

Here in getDescription we ignore getDescription from theThing and just return “Final decoration”.

Now let’s decorate our previously crated decoratorTwo with our new FinalDecorator:

It works as we expected.
I hope this post was useful for you. If so, please, subscribe.
Thank you for reading =)

P.S. I highly suggest you to watch video of my friend Christopher Okhravi about Decorator Pattern. And check out other his videos too, he is very good at explaining complex programming concepts.

Meaningful Names

I am reading one brilliant book : Clean Code, by Robert C. Martin. You can find it here: Clean Code: A Handbook of Agile Software Craftsmanship. In this post I want to write summaries to chapter Meaningful Names.

The naming in software is very important. We always make names for variables, methods, classes and other objects. We need to make names as clear as possible in order to make our code easy to understand. And we must make our code easy to understand if we want to be efficient. In order to write new code we need to read surrounding code. And usually we spend much more time reading code than writing new cod. And the quicker we can read and understand code, the quicker we can write new code.

It was a problem for me to find some consistent guidelines for naming. So now I decided to go with Uncle Bob’s suggestions. I think it is good idea to follow suggestions of programmer with more than 50 years of experience.

Use Intention-Revealing Names

The name of variable, class or function should answer the most important questions:

  • why it exists ?
  • what it does ?
  • how it is used ?

It takes time to choose a good name, but it saves more than it takes. Names should reveal intent. If a name requires a comment, then the name does not reveal its intent.

The name d reveals nothing. We should choose a name that specifies what is being measured and the unit of that measurement:


Avoid Disinformation

We must avoid leaving false clues that obscure the meaning of code. We should avoid words whose entrenched meanings vary from out intended meaning.

Do not refer to a grouping of accounts as an accountList unless it is actually a List ( an Array in Swift ). If it is not an Array it is better to use names like: accountGroup, bunchOfAccounts or accounts (maybe the best one). And it is probably better not to encode the container type into the name.

A truly awful example of disinformative names would be the use of lower case L or uppercase O, especially together :


Make Meaningful Distinctions

If names must be different, then they also should mean something different. Because we can not use the same name to refer to two different things in the same scope, we might be tempted to change one name in an arbitrary way, just to satisfy compiler.

We should distinguish names in such a way that the reader knows what the differences offer. We should not use redundant noise words. Imagine that we have a Product class. If we have another called ProductInfo or ProductData, we have made the names different without making them mean anything different.

Use Pronounceable Names

Names should be pronounceable. If we can not pronounce it, it is hard to read and we can not discuss it. There was a company that had genymdhms (generation date, year, month, day, hour, minute, and second) so it can be pronounced like “gen why emm dee aich emm ess”. It would not be an easy time discussing things that involve that genymdhms. Compare:

to:

ntelligent conversation is now possible.

Use Searchable Names

Single-letter names and numeric constants have a particular problem in that they are not easy to locate across a body of text. Likewise, the name e is a poor choice for any variable for which a programmer might need to search. It is the most common letter in the English language and likely to show up in every passage of text in every program.

Single-letter names can ONLY be used as local variables inside short methods. The length of a name should correspond to the size of its scope.

Compare:

to:


Avoid Encodings

We have enough encodings to deal with without adding more to our burden. Encoding type or scope information into names simply adds an extra burden of deciphering. And it is an unnecessary mental burden when trying to solve a problem. Encoded names are seldom pronounceable and are easy to mistype.

Interfaces and Implementations

Prefer to leave interfaces unadorned. The preceding I is a distraction at best and too much information at worst. If you must encode either the interface or the implementation, you should choose the implementation.

In case of Abstract Factory ShapeFactory and ShapeFactoryImp is preferable than IShapeFactory and ShapeFactory.

Almost all interface names in my previous posts is prefixed with I. I am not doing that anymore.

Avoid Mental Mapping

Reader shouldn’t have to mentally translate your names into other names they already know. This is a problem with single letter variable names. Loop counter may be named i or j or k (never l !) if scope is very small and no other names can conflict with it. This is because those single letter names for loop counters are traditional. But, in most other contexts a single letter name is a poor choice; it is just a place holder that the reader must mentally map to the actual concept. There can be no worse reason for using the name c than because a and b were already taken.

is preferable than:

One difference between a smart programmer and a professional programmer is that the professional understands that clarity is king. Professionals use their powers for good and write code that others can understand.

Class Names

Classes and objects should have noun or noun phrase names like Customer, WikiPage, Account, and AddressParser. Avoid words like Manager, Processor, Data or Info in the name of a class. A class name should not be a verb.

You can find a word Manager many times in my code examples, like here: Dependency Inversion Principle. But from now I will not use it anymore.

Methods Names

Methods should have verb or verb phrase names like postPayment, deletePage, or save. Accessors, mutators, and predicates should be named for their value and prefixed with get, set and is.

like so:

I hope this post was useful for you. If so, please, subscribe.
Thank you for reading =)

The Adapter Pattern in Swift

Before I was talking about Creational Patterns, like: The Factory Method Pattern, Singleton Pattern in Swift and Abstract Factory Pattern in Swift. Also I have touched one of the Behavioural Pattens : The Strategy Pattern. Today I want to talk about one of the Structural Patterns : The Adapter Pattern.

  • Target – defines the domain-specific interface that Client uses.
  • Adapter – adapts the interface Adaptee to the Target interface.
  • Adaptee – defines an existing interface that needs adapting.
  • Client – collaborates with objects conforming to the Target interface.

The adapter in software is the same thing as an adapter in a real world. It is used to be a bridge or an interface between objects. The adapter pattern allows two components with incompatible APIs to work together by introducing an adapter that maps from one component to the other. It allows us to integrate objects which we can not modify into our application.

Third party libraries

We should use The Adapter Pattern with third party libraries. And the main reason here is decoupling. We don’t want our application to be dependent on the code that we don’t have control on. What would happen if the author will make some changes that we don’t agree with? We want to have flexibility, we want to be able to change the framework that we were using to new one without complications. 

So the good solution would be to create adapter between our application and the third party library. This way we will couple our application to the adapter instead of coupling to third party library directly. And it will be much easier in the future to swap frameworks.

Example

In this example I will be using methods like map filter and flatMap. If you don’t familiar with them I suggest you to read this post : Swift Guide to Map Filter Reduce.

Let say we have some ToDo app. It has its data structure and basic functionality. The problem that we will be solving here is that we want to integrate new data source that doesn’t confirm to our protocols.

Our application has ToDoItem struct, that represents toDoItem objects:

Interface for datasource. It requires toDoItems array and two search methods:

Base implementation class:

And two derived classes, one for new items and one for completed:

Additionally we have Searcher class. It provides searching functionality. It can search for ToDoItem in any data source that confirms to ToDoItemDataSource protocol.

The code can be used like this:

prints:

prints:

New Dara Source

The new data structure that we want to integrate is very similar, but not the same. 

ToDoItems look like this:

Title and description are private, we don’t have direct access to them. Instead we have two methods: getTitle and getDescription.

New data source looks like this:

It uses NewToDoItem array, that is private, and it doesn’t have any search functionality.

Adopting

In order to integrate NewToDoItemsDirectory in our system we need to make it confirm to our ToDoItemDataSource protocol. Otherwise we can not use it with our Searcher.

In Swift we can use extension on NewToDoItemsDirectory to make it confirm to ToDoItemDataSource protocol.

We also can use a wrapper class for adaptation, which is good for Two-Way Adapter, but it doesn’t have any advantages in this situation.

In this example I will use extension:

First of all we need to map toDos array of NewToDoItem to toDoItems array with ToDoItem inside. In order to do so we have created createToDoItems method. It uses getToDoItems method of NewToDoItemsDirectory to map each NewToDoItem to ToDoItem. Then, based on toDoItems array, we implement required search methods: searchBy(title text: String) and searchBy(description text: String).

Now we can use NewToDoItemsDirectory in our Searcher:

prints:

Summary

In this post I haven’t talked about another variation of The Adapter Pattern: Two-Way Adapter. I don’t want to make this post too long, so I will talk about this in one of the following posts.

I hope it was useful for you. If so, please, subscribe.
Thank you for reading =)

Table Driven Methods in Swift

I was reading a book “Code Complete 2” and I came across with very interesting topic: “Table driven methods”. This is a very powerful programming concept.

“A table-driven method is a scheme that allows you to look up information in a table rather than using logic statements (if and case) to figure it out. Virtually anything you can select with logic statements, you can select with tables instead. In simple cases, logic statements are easier and more direct. As the logic chain becomes more complex, tables become increasingly attractive.”

Table driven programming based on Dictionaries. I’ve used Table driven approach in my post Abstract Factory Pattern in Swift.

You can see it here:

factory(id: FactoryID) method in FactoryCreator class uses factories Dictionary in order to return IDetailsFacroty. factories Dictionary uses FactoryID as a key and IDetailsFacroty as a value. All factories are stored in factories Dictionary. This way if you want to add a new factory you don’t need to touch factory(id: FactoryID) method, you just add it into the dict.

The Problem

In this post I will use an example from Code Complete 2 book.

The task is to parse and print messages. The number of messages is over 500 and there are around 20 kinds of messages. The messages come from buoys. They are about water temperature, the buoy’s location, and so on.

Each message has several fields, each message starts with a header to let you know which of the 20 kinds of messages you are dealing with.

The format of the messages is volatile, and you don’t have control to stabilise it. Aside from the message header, each kind of message has its own format.

If we used a logic approach we would probably read each message name, and then call a method that designed to read and print that specific kind of message. If we had 20 kinds of messages we would have 20 different methods.

Here is a pseudocode of how this could look like:

Each of the 20 kinds of messages will have its own method for printing its message. Each time the format of any message changed, we’d have to change the logic in the method responsible for that message.

Here is a pseudocode of how method for printing the buoy temperate message could look like:

And this is the code just for one kind of message. Each of the other 19 kinds of messages requires a similar code. If new kind of message was added, new method would need to be added.

With Table Driven approach we can describe the format of each message in a table rather than hard coding it in program logic. We will split each message into number of fields, and create separate methods for each possible type of data in a field.

Let’s say, for simplicity, that there can be only 3 types of data in the fields: double, string and integer.

We start with creation FieldType struct with types of data:

Instead of creating 20 kinds of methods we can create a limited number of methods that print each of the primary data types.

To make it shorter, I’ve created only 3 types of messages (you can see them on the image above):

Next we will create low level methods for printing field label, reading values and printing values:

Here is how we can solve the problem right now without table driven approach:

We are going through messages array, printing message names, then looping through all message field. Depending on FieldType we select a low level methods for printing field data.

Table-Driven Approach

A way better and more elegant approach would be using Object Oriented Approach with Table Driven Approach.

We will create a class for each field type, and then put them in a dictionary. Let’s see:

We have created IField interface and based on that we also created a few classes for each field data type.

Now we can use it like that:

Almost all the work that we needed 20 methods before now is done by these lines of code:

Maybe I am crazy but it looks beautiful to me =)

And as usual in Object Oriented Design we have very flexible system. The code we have written is easy to maintain without changing the user code.

I hope it was useful for you. If so, please, subscribe.
Thank you for reading =)

Tell, Don’t Ask and Law of Demeter in Swift

Tell, Don’t Ask

Tell, don’t ask is an Object oriented design principle.

The idea behind TDA is to reduce control coupling. Control coupling is like a dialog between your objects. When object A asks object B about its internal state, and based on that, object A makes a decisions for object B.

The TDA tells us that Object A should not interrogate the state of object B in order to make a decision about what object B should do. Instead, object A should just tell object B what it wants it to do. And Object B should decide can it do this or not.

Example

We have a class ToDoItem, that has isActive property and setReminder method:

If we want to set a timer for a toDoItem we need to check if it is active, otherwise we will do nothing.

This is clear example of violation of TDA principle because we are trying to decide on behalf of ToDoItem, when it can decide by itself.

Let’s fix that.

And now we can just tell setReminder:

The ToDoItem will check its internal state and will make a decision on its own.

The main goal of TDA is to put correct responsibility in the right classes. And with that we have better separation of responsibilities and loose coupling, which should make for better maintainability.

Law of Demeter

The Law of Demeter sometimes can look similar to Tell Don’t Ask Principle in implementation. But it has different underlying purpose.

The main points of Law of Demeter:

  • Each unit should have only limited knowledge about other units: only units “closely” related to the current unit.
  • Each unit should only talk to its friends; don’t talk to strangers.
  • Only talk to your immediate friends.

If object A has an instance of object B it can ask for some service from object B. But object A should not reach through object B to access another object C. To do so object A requires greater knowledge of internal structure of object B. Instead, object B should provide functionality as a level of abstraction to hide its internal structure.

 

 

Example

As an example let’s take a look at implementation of Delegate and DataSource for TableView. I think TableView is used almost in every app in the AppStore, maybe with the exception of some games.

The worst case of how it can be implemented is when ViewController is set to be a DataSource and a Delegate for its TableView. This is bad because It leads to massive ViewController. And it will be hard to maintain system like that later on.

In OOP what we want is a clear separation of responsibilities between objects.

One way to implement Delegate and DataSource could look like this:

This code shows a clear example of violation of Law of Demeter.

In numberOfRowsInSection method we go to count property on toDoItems array in ToDoItemsModel class.

In cellForRowAt method we go to names of toDoItems in toDoItems array of ToDoItemsModel class.

ToDoItemsListDataProvider class has too much knowledge of ToDoItemsModel. That leads to tighter coupling, which is always a bad thing.

To make it better, firstly we will change ToDoItemsModel class to look like this:

We’ve hidden toDoItems array and added functionality to operate on it. toDoItemsCount returns number of toDoItems, toDoItem returns toDoItem for asked index.

Now we can change our ToDoItemsListDataProvider to look like this:

Here we are using a new layer of abstractions provided by ToDoItemsModel class. We can get what we need without direct access to toDoItems array on ToDoItemsModel.

Now we have much cleaner separation, and, as a result, much flexible system.

Of course we can do even better. We can make 2 separate objects for Delegate and DataSource. But in this example it would be overkill.

I hope this post was useful for you. If so, please, subscribe.

Thank you for reading =)

Abstract Factory Pattern in Swift

Abstract Factory Pattern is similar to The Factory Method Pattern, that I was talking about in one of my previous posts. The Abstract Factory offers an interface for creating a family of related objects, without explicitly specifying their classes. The pattern hides the details of which classes are used to create the objects and the reason why they were selected from the calling component.

Abstract Factory Pattern consists of these objects:

  • AbstractFactory. It declares an interface for creating abstract products.
  • ConcreteFactory. It implements logic for creation concrete products.
  • AbstractProduct. It declares an interface for a type of product objects.
  • Product. It defines a product to be created by the corresponding ConcreteFactory.
  • Client. It uses the interfaces declared in AbstractFactory and AbstractProduct classes.

Abstract Factory Pattern makes it possible to change the classes that are used without needing to change the components that consume them.

It will be more clear with an example.

Example

let’s assume that our application needs to construct some Products. Those Products are very similar and can be created from a set of similar details. The Products are different only by types of details that it consists of. Abstract Factory Pattern can help us by providing factories for each type of product. These factories will create specific details for specific Product. The factories will have the same interface. But they will return different types of details depending on what type this factory is. Since the factories have the same interface, client can talk to any of them using one interface. And, therefore of this we can hide creation logic of details for products in concrete factories. Client just needs to select which factory it wants to use.

Let’s see some code.

First we will create our details:

We’ve declared two protocols, IDetailA and IDetailB. For each of them we’ve created 2 classes. IDetailA can be DetailAOne and DetailATwo. IDetailB can be DetailBOne and DetailBTwo. Each of four classes has printDesctiption method. Later we can use it to see what type is created product of.

Next we will work on our factories.

We’ve created Abstract Factory by defining IDetailsFacroty protocol and two concrete factories: DetailsFactoryOne and DetailsFactoryTwo. Lastly we’ve made them as a singletons by making init method be fileprivate and by creating global constants. Please, note that each concrete factory should be declared in separate file with their global constants. fileprivate allows to access init method inside the file, but you will not be able to access it outside. This makes concrete factories be singletons. Please, read more about Singleton here: Singleton Pattern in Swift.

The next object is FactoryCreator. We need it to get a pointer to concrete factory from client object.

In order to use FactoryCreator efficiently we’ve created FactoryID enum and factories dict. We pass FactoryID to factory method and, using this id, the method returns appropriate factory. To avoid switch statement we are using factories dict with FactoryID as a key and pointer to global concrete factory as a value.

So, now about our Product. It looks like this:

Client can create a new product this way:

But we can do even better by encapsulating Product construction in init method inside Product struct:

Note, I used forced unwrapping in example code. In a real project you should not do that, add some protections, like guard statement.

Now we just need to pass a FactoryID in Product’s init method, like so:

Abstract Factory Pattern allows us to build much better code by making it more flexible. As well as other OOP principles and design patterns. Let’s use them and build a better applications!

I hope this post was useful for you. If so, please, subscribe.
Thank you for reading =)

Singleton Pattern in Swift

In my last post I was talking about The Factory Method Pattern. It is common practice to combine Factory Method Pattern or Abstract Factory with Singleton.

Singleton is one of the most commonly used design patterns. We should use the Singleton Pattern when we need to encapsulate shared resources or when we need to represent real world resources. The Singleton Pattern ensures that only one object of a given type exists in the
application. Singleton also provides a global point of access to itself.

Singleton makes it impossible to create new instance of itself each time it is being invoked. Instead the same instance is being used from everywhere.

We will know that the pattern has been implemented correctly when there is only one instance of a given type, when that instance can not be copied and when we can not create a new instances of that type.

Examples

The singleton can be created only with classes because it is a reference type. Structs and other value types copied when they are assigned to a new variable. Reference type can be copied only by creating a new instance.

Easiest Singleton Implementation

The easiest singleton implementation would be by using global constant. In Swift, global constant or variable will be initialised lazily, and lazy initialisation is thread-safe. It means that singleton object will not be created until the value of the global constant is read for the first time. And even if another thread tries to read the value while the singleton is being initialised, only a single instance of singleton object will be created.

We mark the class as final to prevent subclassing. Initialiser is marked as fileprivate so that we will not be able to create instances outside of file where Singleton class is declared. Also we can not change global instance because it is a constant.

Conventional Singleton Implementation

In conventional implementation singleton defines a getInstance method which returns the unique instance. The method exposes private instance of the singleton class, or, in case it is not created yet, creates its class unique instance.

But Swift doesn’t support type stored properties. So we need some ingenuity to apply the singleton pattern in the conventional way.

Now the Singleton is to be used this way:

We have defined a struct called SingletonWrapper that has a static stored property called singleton. We create new Factory object and assign it to the singleton property. And then we return the value of the singleton property as the value of the sharedInstance property.

This implementation relies on the way that Swift processes struct definitions and static stored properties. This way we ensure that only one instance of Factory class is created.

Singleton Implementation in Multithreaded Application

In a multithreaded application different objects can perform simultaneous operations on the singleton. We need to be protected against potential problems.

Swift arrays are not thread safe. That means that if two or more object at the same time can call append method and it can corrupt data structure. Singletons that use arrays need protection against concurrency.

To solve this problem we need to ensure that only one block at a time is allowed to call the append
method on the array. We will use GCD to solve it.

We have created a serial GCD queue. In the log method we are using sync method to take a set of asynchronous blocks and force them to be performed serially. This ensure that only one block calls the append method on the array at the same time.

Most common problems

The main problem is using reference types (which can be copied) or classes that implement the NSCopying protocol (which can be cloned).

The most difficult problem is due to multithreading. We need to protect shared data structures, that are not thread safe from being accessed by multiple threads concurrently. If you don’t have protection against it, you are in a risk of situation where two ore more threads can corrupt your data.

I hope it was useful for you. If so, subscribe to get more posts like this one.

Thank you for reading =)

The Factory Method Pattern

The Factory Method is one of the most used design patterns. It creates objects for a client without requiring the client to know anything about the implementation of these objects. This way the client relies only on the top-level protocol or base class. It doesn’t need any knowledge about the implementation of classes, or how they are selected.

At the end of my last post The Dependency Inversion Principle I was talking about the problem with objects creation. Even if we perfectly follow DIP, client class is the place where we create concrete objects. That means that we are exposing the instantiation logic to the client. Every time we want to create different object we need to modify the client class. Doing this we are violating The Open Closed Principle. With The Factory Method Pattern we can avoid this.

We will know if we implemented The Factory Method Pattern correctly when the appropriate class is instantiated without the client knowing which class was used and how it was created.

The Factory Method Pattern is easy to implement. Basically it looks like this:

  • When the client needs an object, instead of creating it directly, it asks the factory class for a new object providing the information about the type of object it needs.
  • The factory class creates new concrete object and returns it to the client, without telling the client about what exactly this object is.
  • The client uses returned object as an abstraction, knowing only about the protocol it confirms to or the base class of this object.

An Example

We will start with creating a protocol and a few concrete objects:

We’ve also created simple enum to use it as an id for products. Next, we will create Factory class. We will make it to be a singleton. I will tell more about The Singleton Pattern in one of my next posts. For now, it is a class which only allows one instance of itself to be created.

What we have here is a simplest implementation of Factory Method. The problem here is that if we introduce a new type of Product we need to modify the factory class. That is because createProduct method uses a switch statement to decide what product it should return. A new product type adds a new case.

A client can create a new product like this:

A new product was created, but the client doesn’t know what type is it of, only its name/id. The client will treat myProduct as an abstraction.

Currently, Factory class violates The Open Closed Principle. Let’s fix this.

We need to remove switch statement from createProduct method. A good way to do that is to use dictionary. Keys will represent names/ids and values will be concrete products. Like this:

Thats is good but we need to make it global, so any client can access that. Let’s make a struct:

Now we can change our Factory object to:

We can use it like before:

Only thing I’ve changed is a name of desired Product in creation call.

Now, if we want to create new product type, the only things that need to be changed is Products dict and ProductName enum.

A bit more interesting

I like it! And you? =) 

Let’s make it a bit more complicated and more interesting.

What if we want a new kind of Product. Say, a product that requires another object, like some Processor.

We will add a new product name in our ProductName enum:

Then, we will create IProcessor protocol and one concrete Processor:

And ProductThree:

And after adding this new Product to Products dict:

We can create a new product like this:

We even haven’t touched our Factory class, and client has changed only name of desired Product in creation call. Isn’t it cool?

Thank you for reading. I hope you like it as I do =)
Subscribe and you will get more of interesting stuff from world of OOP.

Cheers!

Dependency Inversion Principle

The Dependency Inversion Principle is D in SOLID object oriented design principles.

As Uncle Bob said: The Open Closed Principle is a goal of Object Oriented Architecture, The Dependency Inversion Principle is its primary mechanism.

The Dependency Inversion Principle states:

Depend upon Abstractions. Do not depend upon concretions.

High-level modules should not depend on low-level modules. Both should depend on abstractions.

Abstractions should not depend on details. Details should depend on abstractions.

So what does this all mean?

We can consider high level classes as the classes that have complex logic. Low level classes are the classes that implement basic operations. It is the details. Since high level classes have complex logic, they should not depend on low level classes. Complex logic generally care little about the details of implementation. The abstraction layer should not depend on low level classes. It should not be created based on low level classes. Low level classes should depend on abstraction.

We will not have flexible design if we make our high level classes depend on low level classes. Even if it looks like a natural way of how this things should work. This way we will depend upon concretions, and our dependency structure will be weak.

   Weak dependency structure.

This is bad design If we need to change our low level classes we will also need to make changes in our high level classes. And, we need to retest all this code. This will take a lot of time. Plus, the more changes we do to our code the more bugs we can introduce.

Instead, what we should do is to point majority of all our dependencies to abstractions. An abstraction should be between high level classes and low level classes. Heigh level classes should depend on abstraction. Low level classes should not be depended upon, instead, they should depend itself on abstraction by confirming to an interface.

That’s why it is called The Dependency Inversion Principle. The dependencies should be inverted. Every dependencies should point towards abstractions. No dependency should target concrete class.


    Flexible dependency structure.

We should follow The Dependency Inversion Principle as much as we can. The reason to do so is to avoid dependencies upon volatile classes. Concrete things change far more often than abstract things.

In Object Oriented Architecture abstractions represent the places where we can change or extend our design without modifying the abstractions. This is the goal of Object Oriented Architecture.

The Dependency Inversion Principle brings many advantages:

  • We have small classes with limited responsibilities;
  • We can change behaviours of our application by writing new classes and   injecting them instead of rewriting old ones;
  • We have modular design;
  • We have increased flexibility;
  • We have clean separation;
  • Our code is easy to extend and reuse;
  • Our classes have single responsibilities;
  • The application is easy to maintain.

Code example

For code example I will use simplified code from one of my sample projects. You can find it here.

In the project there are 2 screens with table views. The first should display names of car manufacturers. The second one should display names of car models for selected manufacturer. I need an object to manage car objects. I want to use it to feed data provider. Here we will focus on manager object.

So let’s start with manufacturers screen. We are creating Manufacturer structure with name and id:

Then we are creating ManufacturerManager with basic functionality:

Here we have private manufacturers array to store manufacturers. We don’t want anyone to have access to it, that’s why it is private. Instead, we have created basic functionality that can modify the array. We can add manufacturer, remove all and return manufacturer for desired index.

This looks clean and easy. It works fine for the first screen. But this code violates the Dependency Inversion Principle. We’ve built our manager the way, that it depends on concrete object: Manufacturer. Even the name shows it clearly: ManufacturerManager.

What will we do for the second screen, where we need to show car models names? Build a new, almost identical manager, but for model objects? It wouldn’t be great design for sure.

In the second screen we will use models. The model looks like this:

Both first and second screens should display names, whether it is manufacturer names or model names.

So it doesn’t matter for a manager whether it works with manufacturers or models. The only thing the manager needs is that this thing has a name. We can make the manager depends upon abstraction. The abstraction is an interface:

It has only a name. Now we can make our manager depends on that interface:

Then, we will make Manufacturer and Model depend on the same ICarElement interface:

With these corrections, we made our code much more flexible. Now we can use CarElementsManager with manufacturers, as well as with models. Great!

Conclusion

With all that said about DIP, we still have a place where we depend upon concretion. That place is where we crate instances, we can not create instance of abstract class. But there is a solution for this problem. It is some of the Creational design patterns, such as Factory Method and Abstract Factory. I will make posts about them, so stay with me.

If you like this post, please subscribe. I have a ton of interesting topics that I will write about.

Thank you for reading =)