A few months ago I finished my 17 months long stay in Singapore. It was an amazing time during which I met brilliant people, sweated a lot in tropical weather and worked on a messaging application for iOS.
The company I worked for used eXtreme Programming methodologies for software development. We used XP every business day for 8 hours. Because of that TDD became a habit, lack of companion when programming became a burden, and the legacy code became no fear to me. Let me tell you why XP is useful and why pair programming is helpful when working on a project.
We live in times in which everything changes rapidly. Not longer than 5 years ago (June 2014) majority of production code for iOS apps was written in Objective-C only, whereas today many companies try to minimise Objective-C code in favour of Swift. Not only technology and tools we use evolve and change, but also business requirements for our apps. Companies that can adapt to changing conditions and can develop quality software in an agile way can survive and ship valuable products.
Extreme programming (XP) is a methodology for creating software of high quality in a responsive way to changing requirements. It values a set of good practices and pushes using them to their limits:
I heard about this wrong perception that pair programming is 2 people doing one person’s job. What actually is pair programming?
Two people in front of 2 screens, 2 keyboards and 2 mice connected to a single computer working on the same thing. Pair programming is mainly a discussion about how to solve a certain problem. It leads to coming up with a better design and doing it right the first time. Pair members get instant feedback on their ideas thanks to the continuous conversation about the task at hand and its implementation.
Have you ever had this feeling that it takes ages to merge your PR (Pull Request) to the main development branch? You implement your new functionality, push changes to a remote branch, create a PR and then you wait… and wait… and finally somebody reviews your changes, leaves some comments. You apply them to your work, and then you wait for feedback again… With continues code review a.k.a. pair programming you get feedback right away. It’s a faster way of working and getting better quality of code. You can push directly to the master because the code you worked on with your pair is considered reviewed. Of course, crucial parts can still go through PR if you need another opinion. Be agile and change approach if needed
!
We had these new guys joining our development team. If they had to dive into our legacy codebase solo, they wouldn’t have become effective quickly. Pairing allowed them to ramp up fast. The project’s legacy codebase was extremely complicated, old and lacking unit tests for crucial parts. When they worked with experienced peers they could learn about the project from them. Good practices were spread right away and a knowledge about the project was shared on the job.
Some new teammates didn’t have experience in Objective-C, nor in TDD. If you learnt Objective-C you know how difficult it probably was for you at the beginning and how different it is from Swift. If you practice TDD, you understand that it demands perseverance and skill in unit testing. Our teammates could learn from the experience of other peers thanks to pair programming.
It would be great if knowledge of application components was distributed evenly, i.e. every team member would feel comfortable and capable of working on any part of the app. You can achieve that by rotating pairs. At every daily standup, people would tell what they planned to work on. Then peers agree on what and whom they want to work with. And hey – not every task makes sense to be done in pair programming mode
.
Pair rotation teaches the skill of adaptation to new tasks easily. One person from the initial pair working on the task stays with it till it’s finished and the other person can step back from the task and work with someone else on another task. It also spreads the knowledge and gives fresh look and opinion on solutions when new people joined to pair with you.
Nowadays it’s extremely easy to get distracted. Phone buzzing with notifications, e-mail needs to be answered, new blog post on “XYZ” needs to be read. After an hour you can find yourself still not having started the work…
While you’re pairing, you’re actively involved in the task. You discuss the code and you don’t answer sms or watch YouTube.
A few days ago I was thinking through how to solve a certain problem in the application. Then my colleague waved at me and ask some question about the app. I needed to navigate to a different part of the project and talk about it for a while. When we finished I needed a few minutes to get back on track…
When programmers are pairing people see that they are actively involved in their work. People will wait for the appropriate moment to approach them to discuss things through. What’s also great about pairing is that when somebody approaches the pair one member can handle the interruption while another will stay focused and work on the task.
Pair programming is just fun and rewarding way to work. You have a mutual goal and pursue with your pair to achieve it. This pursuit is accompanied with a lot of laughter and it allows you to get to know your colleagues more and to make this special connection with them.
When you do pair programming you never end up in situations when people start arguing about who will use the keyboard. Of course you have two sets of them, but usually only one is used at a time. Pair agrees on the way they want to work. It can be that one person writes the test and the other implements the code. It can be communicated verbally that one wants to write code – “Hey, let me do it!”
.
But there is more than that. When you practice pair programming constantly for some period you start understanding non-verbal communication.
When you type on a keyboard and you notice by a glimpse of an eye a subtle movement of your peer’s hand approaching their keyboard, you immediately know that it means that they want to start typing and to introduce their concepts so you can react to this non-verbal language right away. You understand your pair with no words.
Sometimes even if we speak the same language we don’t understand each other. Language can mean many aspects – Objective-C/Swift, Polish/English, body language, language of shared experienced.
I spent 17 months where Chinese is one of spoken languages and my friends taught me some of it:
我不说你说的语言
Wǒ bù shuō nǐ shuō de yǔyán in Chinese means I don’t speak the same language that you speak.
Pair programming allowed me to learn non-verbal language, to understand people coming from different backgrounds and cultures. It allowed me to “speak” the same language, share my experience and learn a lot from others.
I can’t sum up pair programming by not quoting my previous manager. It’s just a rewarding way to work. You have a lot of fun while working with others. It’s an exciting adventure which gives new experience. With pair programming you get better code and higher quality much faster than in a standard approach to software development.
| pair programming | |
|---|---|
| wait ages for PR review | instant feedback |
| slow solo discover | fast developer ramp up |
| distraction threat | focus on the job |
If you want go fast, go alone.
If you want to go further, go together.
African proverb
The world has gone crazy. It has made us extremely busy nowadays. Product owners want us to write code fast, to ship new features even faster. Because of that we don’t have time for self-improvement.
We are programmers that may be great in their craft, that may write top notch source code, but we are also – humans. We make mistakes, all the time. We also want to become better people, better engineers. But how can we do that? Why should we review our work?
You know, I have a vision, where unit testing and code review are a standard, not an opt-in feature in iOS development. I’ve been fighting a lot to introduce them at my workplace. Let me tell you what things get reviewed in other industries and why it is so. Join the talk if you want to start code review practices at your company, but you don’t know how to kick it off.
]]>Concentrating on some basics, best practices, tips and just personal feelings about each one.
Important: if you would like to learn more about SwiftLint I recommend visiting our previos post about SwiftLint.
Ready?

Let’s start!
A tool to enforce Swift style and conventions, loosely based on GitHub’s Swift Style Guide.
New version has a few new rules, options and fixes. For example:




Legacy NSGeometry Functions Rule – Struct extension properties and methods are preferred over legacy functions (available for SDK: macOS 10.10+)
New junit report option:
swiftlint lint --report junit
In result we can get a report like the one below:
...warning: Line:16 ... warning: Line:20
It can be very useful for continuous integration system like Bamboo where you can have online dashboard of SwiftLint results:

After almost one year of using it, personally I think it’s a very great tool! Below are main thougts about my experience:


In this way you can configure it very easily.
SonarQube is an open source platform for continuous inspection of code quality. Supports more han 20 languages: Java, C/C++, Objective-C, C#, PHP, Flex, Groovy, JavaScript, Python, PL/SQL, COBOL, Swift, etc. Unfortunately plugins for some of the languages are commercial, as is the plugin for Swift. Additionally it has available more than 50 plugins.
Sonar at this moment has 92 rules for Swift, which are divided into three groups:

They can be marked in aspect of severity as:
Blocker, Critical, Major, Minor, Info:

Some examples below:
Sonar uses following metrics:






What we can also see is:
Wikipedia: "Technical debt is a concept in programming that reflects the extra development work that arises when code that is easy to implement in the short run is used instead of applying the best overall solution. Technical debt is commonly associated with extreme programming, especially in the context of refactoring"
In Sonar technical debt is calculated based on algorithm below:
Debt(in man days) = cost_to_fix_duplications + cost_to_fix_violations +
cost_to_comment_public_API + cost_to_fix_uncovered_complexity +
cost_to_bring_complexity_below_threshold

If you would like to test SonarQube by yourself before buying it, you can visit this demo website
Checkmarx is a security platform providing several tools for introducing advanced static security analysis into applications written in C#, Java, jscript, native C/C++ or APEX.
Checkmarx scanner interprets Swift to Objective-C in the backend before scanning the code. As a result, Checkmarx scans Swift code for over 60 quality and security issues, including twelve of the most severe and most common issues that cannot be left unfixed.
On Checkmarx website you can find a lot of interesting articles dedicated to mobile application, for example:
Checkmarx offers a Web dashboard on which you can find summary for all vulnerabilities found in your projects:

Checkmarx misses rules typical for Swift. I think that it is because Swift is a new and rapidly changing language. For sure there are still a lot of possibilities for defining new rules like they did for the others languages.
At this moment there are not many different libraries for linting Swift. I have only found this one:
I hope that in the future we will see much more alternatives.
In my opinion static code analyzers can make your codebase more consistent, and for sure can really help during your daily coding and speed up the process. Of course we should remember about golden mean in using such libraries. It would be good not to turn our job into a nightmare by using very strict rules:)!
]]>
Swift code.

It is said that a review goes best when conducted on less than 400 lines of code at a time. You should do a proper and slow review, however, don’t spend on it more than 90 minutes
– you definitely will get tired after that time. It’s tiring to write and understand your own code and it’s even more tiring to understand someone’s. Other tips from the Internet are:
After some years of experience in software development you know what common programming mistakes are. You also do realise what solutions to common problems are most efficient. It’s a good practice to write it down and to check code being reviewed against a checklist ✅ – it leads improved results. Checklists are especially important for reviewers because, if the author forgets a task, the reviewer is likely to miss it too.
In the git flow mentioned in issue #13, code can get merged after receiving agreed number of approvals for a pull request. The number should depend on your team size, but it’s good to get at least 1️⃣ !
When you recommend fixes to the code, suggest their importance
. Maybe some of them could be postponed and extracted as separate tasks. Before approving a pull request, verify that defects are fixed 
.
Foster in your company a Good Code Review Culture in which finding defects is viewed positively
. The point of software code review is to eliminate as many defects as possible, regardless of who "caused" the error. Few things feel better than getting praise from a peer. Reward developers for growth and effort. Offer as many positive comments as possible. I always try to put a line saying that a solution is good and clever (if it really is
).
You can also benefit from The Ego Effect
. The Ego Effect drives developers to write better code because they know that others will be looking at their code and their metrics. No one wants to be known as the guy who makes all those junior-level mistakes. The Ego Effect drives developers to review their own work carefully before passing it on to others.
And don’t bother with code formatting style …
… there are much better things on which to spend your time, than arguing ☔️ over the placement of white spaces.
Looking for bugs and performance issues is the primary goal and is where the majority of your time should be spent.
Much better things to look for should be a part of your checklist. When I scrutinise a piece of code I look especially:
if conditions, for and while loops for "off-by-one" errors< versus <= and > versus >=Bool value, hence there’s no possibility not to catch compilation error if one interchanges operatorsWhen performing a review, one can also get extra points
for pointing out a more efficient implementation of used algorithm
.
You should also check for readability. Is the code easy to understand? Do you have to pause frequently during the review to decipher it?
swiftsBoom! Time for some loosely coupled Swift code examples that I look for when reviewing Swift code❗️Wait a moment, this exclamation mark looks strangely familiar … ❗️Look out for code that uses it …
Swift
var foo: Object!
print("\(foo.someString)")
Make sure that your peers (and you as well) use the force unwrapping operator wisely in their code.
If you have ever ended up with code like the one below, then probably something went wrong … 

override init(_ objectId: String?,
viewModel1: ViewModel1,
viewModel2: ViewModel2,
viewModel3: ViewModel3,
viewModel4: ViewModel4,
viewModel5: ViewModel5,
viewModel6: ViewModel6,
viewModel7: ViewModel7,
viewModel8: ViewModel8,
viewModel9: ViewModel9,
viewModel10: ViewModel10,
isSomething: Bool = false) { ... }
This is an excerpt from from one of my projects, object types and names are changed . It’s an initialiser of a ‘container’ view model that encapsulates ‘child’ view models used by a container view controller. If you happen to achieve this and there’s no way to change it, probably usage of a configurator facade, default argument values or convenience initialisers are the best solution to live up with your legacy.
class Configurator {
class func mainViewController() -> MainViewController {
let dependency1 = Configurator.dependency1()
let dependency2 = Configurator.dependency2()
let dependency3 = Configurator.dependency3()
let dependency4 = Configurator.dependency4()
return MainViewController(dependency1: dependency1,
dependency2: dependency2,
dependency3: dependency3,
dependency4: dependency4)
}
}
The off-by-one errors and interchanged greater than & less than were my favourite mistakes at some point of time. I’ve caught myself a few times last year with using if i > array.count instead of if i < array.count ☔️.
Remember local autoreleasepool? For those who answered ‘what!?’ here is some explanation. I pay attention when reviewing body of a loop to check if local autoreleasepool could be used to reduce peak memory footprint.
for i in 1...100
autoreleasepool {
NSString *superImportantString = "Super \(i)"
//strange operations take place
//superImportantString can be released earlier thanks to local autoreleasepool
}
More than a year ago, when Swift was still in its early days, I hated when my team members overused var. It’s ok when needed, but not all the time! Thanks god that now Swift compiler warns about not mutated var.
Another matter is your object’s properties. If it depends on some values, never ever use var. Use let. Always value more immutable state over var! I wonder how many people would argue with me about that☔️
. And if your property really have to be mutable, expose it ‘to the public’ as immutable like that:
private(set) var foo: AnyObject let bar: AnyObject
Swift’s protocols are a great deal – do you prefer composition over inheritance? Is such an inheritance chain ok for you? One superclass would be probably ok, but this becomes an exaggeration:
class ChildViewModel: TableViewModel {}
class TableViewModel: CRUDViewModel {}
class CRUDViewModel: BaseViewModel {}
class BaseViewModel {}
Kofi Annan, Ghanaian ex-Secretary-General of the United Nations, when in primary school, was attending a weekly lesson in ‘spoken English’. He and his peers were asked by the teacher what did they see at the picture:

All shouted together, that they saw a black dot! Professor stepped back and said ‘So, not a single one saw the white sheet of paper. (…). This is the awful thing about human nature. People never see the goodness of things, and the broader picture. (…)’.
It’s also true for code review. We perceive better differences than loads of new code when using a merge tool. We get a cognitive overload if flooded with more content. Have that in mind and use the first rule – review for less than 90 minutes
, take breaks. Remember that:
without review can happen … 
And always – Review your own code first! Before committing a code look through all changes you have made!

Let us know in comments or on Twitter what is on your checklists for code review!

The good old Wikipedia once wrote:
Code review is systematic examination (often known as peer review) of computer source code. It is intended to find and fix mistakes overlooked in the initial development phase, improving both the overall quality of software and the developers' skills.
Far enough. I want to do it!
Wait, but …
Reviews can be done in various forms such as pair programming, informal walkthroughs, and formal inspections. The most known is probably this one – show me your code (aka informal review)! Simply ask your peer to have a look at your code.

Formal code reviews can be performed by using e.g. Atlassian’s Crucible/Fisheye (I don’t like this tool, bad UX, hard to navigate and even start a review) or a pull request on Stash/BitBucket/GitHub or whatever you use. Thanks to those tools you get a nice visualisation of what changes were made to source code, you can comment on them, ask author some questions and they can explain their code in return. It’s like a conversation you would have in real life, but documented – what has been agreed should be performed before merging into develop. Wait, what merging?! We were just talking about a review …
When developing different parts of an application at work we use Git and Git Flow to merge all changes into a parent branch. Once a feature of an app is finished we create a pull request that contains changes to be added to a predecessor branch (usually develop). The best picture showing the flow comes, in my opinion, from GitHub. I still don’t get what the squirrel on it represents… ⁉️

The flow goes like this:
)You definitely should check code integrity – does the style match previous solutions, does it follow agreed conventions? Are features implemented correctly, does the old source code work correctly after changes?
For sure because it ensures code integrity
, catches what others’ eyes didn’t see. It allows to learn and share your knowledge and expertise, strengthens communication in the team and builds good relationships due to conversations about what you have in common – code and programming skills ;)!
Unfortunately, from my experience, unit tests and code review are first things that get removed from project scope
. It takes too much time and there’s no budget for that. Do you encounter the same problems?
Consider code review as an investment into the future. If you don’t catch bugs now you will definitely have to conquer them in the future.
Imagine a company X. It delivers mobile app solutions for multiple clients. Their team is small and at some point they cannot meet clients’ demands. So they decide to outsource some of the work to an external company. They give project requirements to this company and meet again after 3 months to receive app source code. But the app is useless – it freezes at network calls, CoreData.ConcurrencyDebug flag crashes all the time. The project is delayed for a few months, team has to start from a scratch. The wish they had reviewed outsourced code on a daily basis…
Code review culture wasn’t common for mobile teams at my workplace. It still isn’t for some of the due to rapid development and short lifecycle of some of the mobile apps. However, I wanted to improve myself by learning from others. I’ve started with a prank. I’ve developed changes on a branch and have created a pull request for my colleagues. And it got the ball rolling. Now all mobile projects within my division embed code review in their development process.
This is usually the question that gets lack of enthusiasm from the audience :(. But really, are we too busy to improve??

This was an introduction to code review. In the upcoming weeks we’ll get deeper into the process. Stay tuned 
!

There are a few ways we can ensure better code quality of our projects. Starting from unit testing then going through lint-like programs, code formatters, static code analysers, code reviews and ending with all that stuff I forgot to mention … 😉 The most demanding and also worth applying, in my opinion, are unit tests and code reviews, but we can get pretty much hints on code that should be improved from static code analysers.
This issue will briefly show some tools I use on a daily basis to assure good quality of developed code, the main focus though is put in particular on a free web-tool for Swift open-source projects and the ABC that drove me a bit crazy recently. If you are not interested in code quality tools and just would like to get to know what the ABC is and why it got me crazy go straight to the Codebeat section.

Probably every developer had a problem at the beginning of applying unit tests in their workflow. What to test, how to test and many others were the questions probably everyone has asked themselves… The easiest way for me to learn and understand unit testing was to take part in a training on that topic. If you happen to be from Poland you can check out Mobile Academy’s offer on the matter (pss… some workshops are free!). There are also good materials regarding testing on objc.io’s issue #15.
You can tap into the standard XCTest framework to perform testing, however I encourage you to try out the BDD-like style and test interactions between objects instead of method implementation. There’s a great framework for that in Swift called Quick – I use QuickSpec objects to group related tests with a valid description. It’s more natural for me to tap into such framework than to use standard XCTest’s approach. I also use Nimble matchers, which is a counterpart for Quick, for code assertions:
context("ViewController") {
//...
describe("when view loads") {
beforeEach {
sut.viewDidLoad()
}
it("does sth") {
expect(sut.didSomething).to(beTrue())
}
}
}
If you happen to use a CI server then xctool might be a good selection to run tests for you because it can translate XCTest report into jUnit output that is understood by such tools as e.g. Bamboo. Some time ago I also had to write a tool that interprets report from xctool‘s JSON format and converts it into human – friendly output. The xctool had been a great help in doing that!

Do you tap into code reviews in your projects? You should be! Imagine outsourcing development of project features to another developer or company. Their work lasts for two months or so. Spaghetti source code gets delivered to you. You wish you had reviewed it when they had been developing it. You wish your company didn’t lose money because of that. You wish you didn’t have to start from a scratch with those features, cause their code is a mess … It happened a few times to me. This is why Git Flow – development on feature branches, pull requests and code reviews became a normal process for my team. You can check out GitHub guide to understand how it works. Btw., can anyone explain to us what that squirrel represent
?
I was searching for a good Swift code-formatting plugin for Xcode, however it seems there aren’t any at the moment. Then I realised that SwiftLint has the autocorrect option to fix some of code-format-related issues.
I’ve added the SwiftLint to a run script for each Xcode build for my project, but suddenly I realised that it generated over 3000 issues. Thanks to this autocorrect option it went down to more than 1500. It was still to much and we don’t have resources to fix all of them. To silent them I had to disable some of SwiftLint’s rules in the swiftlint.yml configuration file. The tool is nice, however I encourage you to use it from the very beginning than embedding it in project after almost a year of development :)!!!
Have you tried any of those? Some of them we get with Xcode, for some of them we have to pay, but probably the greatest are those we get for free :)!
for a language plugin (5k EUR per plugin per year), and it’s difficult to setup

earlier this year?is at the moment my favourite code analyser. Comparing it to other analysers I feel as if Christmas were earlier this year because we can use this tool for free for open source projects. Additionaly, it’s easy to setup (just login and add a link to your GitHub repository and the analysis begins), has a clean & nice UI and what’s more, it of course supports Swift
! Check how it works here.
The analysis takes into consideration a few simple metrics that are explained in details in their guide . Here are short excerpts about each of them:
and …
In the ABC, an Assignment is understood as an explicit transfer of data into a variable, i.e. by using any variation of = operator, a Branch is understood as a function or method call, whereas a Condition is of course a logical (or boolean) test, e.g. == or switch.
A scalar ABC metric is computed as:
|ABC| = sqrt((A*A)+(B*B)+(C*C))
The measure can be used to indicate how much work a piece of code does. Shorter procedures without many execution paths are desired because they’re simpler to understand and easier to test. But let’s get back for a moment to the Assignment part of the metric: an explicit transfer of data into a variable…
Imagine you had a view controller with three views that were not initialised from a Storyboard or Xib file. You would end up with a code in init or viewDidLoad similar to this one:
init() {
imageView = UIImageView(frame: CGRectZero)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
imageView.accessibilityIdentifier = "image"
imageView.isAccessibilityElement = true
nameLabel = UILabel(frame: CGRectZero)
nameLabel.translatesAutoresizingMaskIntoConstraints = false
nameLabel.numberOfLines = 0
nameLabel.backgroundColor = UIColor.whiteColor()
nameLabel.textColor = UIColor.darkGrayColor()
nameLabel.accessibilityIdentifier = "name"
nameLabel.isAccessibilityElement = true
ratingLabel = UILabel(frame: CGRectZero)
ratingLabel.translatesAutoresizingMaskIntoConstraints = false
ratingLabel.numberOfLines = 1
ratingLabel.backgroundColor = UIColor.whiteColor()
ratingLabel.textColor = UIColor.darkGrayColor()
ratingLabel.accessibilityIdentifier = "rating"
ratingLabel.isAccessibilityElement = true
super.init(nibName: nil, bundle: nil)
}
I usually initialise views in the init in such a way, because I prefer let over var view: UIView! and having focused over distributed setup of objects. The other thing is that I cannot invoke any instance method to initialise a view before calling super.init. Because of that every time I set a property in a variable the ABC metric for that function increases. For one of my old projects I ended up with a metric of size abc = 23.02 for init of a view controller. It was very frustrating since a yellow sad face appeared on the list of my projects. I wanted to fix it. It kept staring at me:

Firstly, I have contacted the support team in order to ask them why an assignment to a property of an object increases the ABC. Thanks to them I have realised that the ABC is about any assignment, not just about too many assignments to a particular variable. The less assignments in a method the better. Knowledge++ ;)!
Then I focused on how to solve the problem. I have performed a small test to check which of the approaches have the least ABC metric.
First approach was to use the standard initialisation in the init method. It’s put in here just for reference, to check how bad the aforementioned stand-alone code behaves. It got the abc=21.54. A bit better than the one from my previous project, because over there I had a few more assignments. Grab the report here and check out the source code here.
Second test was with a usage of Then library. It’s a syntactic sugar that allows to set object’s parameters in a non-escaping closure just after object’s initialisation:
imageView = UIImageView().then { imageView in
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
imageView.accessibilityIdentifier = "image"
imageView.isAccessibilityElement = true
}
In fact, the code was still present in the init method. The metric in the report increased to abc=22.83. Not good …
The 3rd test went well. In fact it went very well. I cannot extract from the report the exact metric I have achieved, but I totally changed the approach. Now views are lazily initialised when used for the first time in the code, when added to their superview:
lazy var imageView: UIImageView = {
let imageView = UIImageView(frame: CGRectZero)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
imageView.accessibilityIdentifier = "image"
imageView.isAccessibilityElement = true
return imageView
}()
Next solution again used lazy var but this time named functions to initialise variables:
func setupImageView() -> UIImageView {
let imageView = UIImageView(frame: CGRectZero)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
imageView.accessibilityIdentifier = "image"
imageView.isAccessibilityElement = true
return imageView
}
I had to use currying though. It’s sad that currying probably won’t be present in the next Swift release, I like it very much ❤️:
lazy var imageView: UIImageView = setupImageView(self)() lazy var nameLabel: UILabel = setupNameLabel(self)() lazy var ratingLabel: UILabel = setupRatingLabel(self)()
No metric in the report for this approach, but no issue with ABC reported.
The 5th attempt also didn’t cause any issues in the report. This time I went back to initialising views in the init method, however I used a Configurator object to set up views for me (remember that you cannot invoke any instance method before initialising super). Grab the full code here.
init() {
//imageView = setupImageView()
//nameLabel = setupNameLabel()
//ratingLabel = setupRatingLabel()
imageView = Configurator.setupImageView()
nameLabel = Configurator.setupNameLabel()
ratingLabel = Configurator.setupRatingLabel()
super.init(nibName: nil, bundle: nil)
}
The last test didn’t change much, again I still have three assignments, use setup*View method but I wanted to show an approach when doing it inside the viewDidLoad method. Surprise, surprise – ABC not an issue in the report. Full code here, an excerpt below:
override func viewDidLoad() {
super.viewDidLoad()
imageView = setupImageView()
ratingLabel = setupRatingLabel()
nameLabel = setupNameLabel()
view.addSubview(imageView)
view.addSubview(ratingLabel)
view.addSubview(nameLabel)
}
It isn’t difficult to invent a few attitudes in making methods simpler. I think I like the approach with the Configurator object the most, because I prefer immutable properties whenever possible. Thanks to codebeat I got a food for thought and I could ponder about the solution that suits me best.
What are your favourite tools for code quality? Share your thoughts in comments or on our Twitter account!
PS. I was also asked by the codebeat support team if I thought that the ABC metric should be relaxed for Swift language. After performing my tests, I think it’s ok the way it is.
PS. They change their algorithms from time to time.
]]>