How to save the project from extra pounds

Hello! My name is Ilya, I am an iOS developer at Tinkoff.ru. In this article I want to talk about how to reduce duplication of code in the presentation layer using protocols.
What is the problem?
As the project grows, the amount of code duplication grows. This becomes not immediately noticeable, and it becomes difficult to correct past mistakes. We noticed this problem in our project and solved it with one approach, let's call it, conditionally, traits.
Life example
The approach can be used with various different architectural solutions, but I will consider it on the example of VIPER.
Consider the most common method in router - the method that closes the screen:
funcclose() {
self.transitionHandler.dismiss(animated: true, completion: nil)
}
It is present in many router, and it is better to write it only once.
Inheritance would help us in this, but in the future, when we have more and more classes with unnecessary methods appearing in our application, or we cannot create the class we need at all, because the necessary methods are in different base classes, large ones will appear Problems.
As a result, the project will acquire a variety of base classes and classes of heirs with unnecessary methods. Inheritance will not help us.
What is better inheritance? Of course the composition.
You can make a separate class for the method that closes the screen and add it to each router in which it is needed:
structCloseRouter{
let transitionHandler: UIViewControllerfuncclose() {
self.transitionHandler.dismiss(animated: true, completion: nil)
}
}
We will still have to declare this method in the Input Protocol of the router and implement it in the router itself:
protocolSomeRouterInput{
funcclose()
}
classSomeRouter: SomeRouterInput{
var transitionHandler: UIViewController!lazyvar closeRouter = { CloseRouter(transitionHandler: self. transitionHandler) }()
funcclose() {
self.closeRouter.close()
}
}
It turned out too much code that just proxies the call to the close method.
Solution with protocols
Protocols come to the rescue. This is quite a powerful tool that allows you to implement the composition and may contain implementations of the methods in the extension. So we can create a protocol containing the close method and implement it in an extension.
This is how it will look like:
protocolCloseRouterTrait{
var transitionHandler: UIViewController! { get }
funcclose()
}
extensionCloseRouterTrait{
funcclose() {
self.transitionHandler.dismiss(animated: true, completion: nil)
}
}
The question arises, why does the word trait appear in the title of the protocol? It's simple - you can indicate that this protocol implements its methods in an extension and should be used as an admixture to another type to extend its functionality.
Now, let's see how the use of such a protocol will look like:
classSomeRouter: CloseRouterTrait{
var transitionHandler: UIViewController!
}
Yes that's all. Looks great :). We got the composition, adding the protocol to the class of the router, did not write a single extra line and were able to reuse the code.
What is unusual about this approach?
Perhaps you have already asked this question. Using protocols as a trait is quite common. The main difference is to use this approach as an architectural solution within the presentation layer. Like any architectural solution, there should be its own rules and recommendations.
Here is my list:
- Trait's should not keep and change the state. They can only have dependencies in the form of services, etc., which are get-only properties.
- Traits's should not have methods that are not implemented in an extension, as this violates their concept.
- The names of the methods in the trait should clearly reflect what they are doing, without reference to the name of the protocol. This will help avoid name collisions and make the code clearer.
From VIPER to MVP
If you fully switch to using this approach with protocols, the router and interactor classes will look something like this:
classSomeRouter: CloseRouterTrait, OtherRouterTrait {var transitionHandler: UIViewController!
}
classSomeInteractor: SomeInteractorTrait {var someService: SomeServiceInput!
}
This does not apply to all classes, in most cases, the project will remain just empty routers and interactors. In this case, you can break the structure of the VIPER module and smoothly switch to MVP by adding impurity protocols to the presenter.
Like that:
classSomePresenter:
CloseRouterTrait, OtherRouterTrait,
SomeInteractorTrait, OtherInteractorTrait {var transitionHandler: UIViewController!
var someService: SomeSericeInput!
}
Yes, the opportunity to implement the router and interactor as dependencies is lost, but in some cases this is the place to be.
The only drawback is transitionHandler = UIViewController. And according to the rules, VIPER Presenter should not know anything about the View layer and about what technologies it is implemented with. This is solved in this case simply - transition methods from the UIViewController are “closed” by the protocol, for example, TransitionHandler. So Presenter will interact with abstraction.
Change trait behavior
Let's see how you can change the behavior in such protocols. This will be an analogue of replacing some parts of the module, for example, for tests or a temporary stub.
As an example, take a simple interactor with a method that performs a network request:
protocolSomeInteractorTrait{
var someService: SomeServiceInput! { get }
funcperformRequest(completion: @escaping (Response) -> Void)
}
extensionSomeInteractorTrait{
funcperformRequest(completion: @escaping (Response) -> Void) {
someService.performRequest(completion)
}
}
This is an abstract code, for example. Suppose that we do not need to send a request, but simply need to return some stub. Here we go to the trick - create an empty protocol called Mock and do the following:
protocolMock{}
extensionSomeInteractorTraitwhereSelf: Mock{
funcperformRequest(completion: @escaping (Response) -> Void) {
completion(MockResponse())
}
}
Here, the implementation of the performRequest method is modified for the types that implement the Mock protocol. Now we need to implement the Mock protocol for the class that SomeInteractor will implement:
classSomePresenter: SomeInteractorTrait, Mock {// Implementation
}
For the SomePresenter class, the implementation of the performRequest method in the extension where Self satisfies the Mock protocol will be called. It is necessary to remove the Mock protocol and the implementation of the performRequest method will be taken from the usual extension to SomeInteractor.
If you use it only for tests, it is better to have all the code associated with the implementation substitution in the test target.
Summing up
In conclusion, it is worth noting the pros and cons of this approach, and when, in my opinion, it should be used.
Let's start with the cons:
- If you get rid of the router and interactor, as was shown in the example, then you lose the opportunity to implement these dependencies.
- Another disadvantage is the sharply increasing number of protocols.
- Sometimes the code may not look as clear as when using conventional approaches.
The advantages of this approach are as follows:
- The most important and obvious thing is that duplication is greatly reduced.
- Static binding is applied to protocol methods. This means that the definition of the implementation of the method will occur at the compilation stage. Consequently, during the execution of the program, no additional time will be spent on the search for implementation (although this time is not particularly significant).
- Due to the fact that the protocols are small "bricks", of them you can easily make any composition. Plus karma for flexibility in use.
- Easy refactoring, no comments here.
- You can start using this approach at any stage of the project, since it does not affect the entire project.
To consider this decision as good or not is a personal matter. Our experience with this approach was positive and allowed us to solve problems.
That's all!