<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Daniel Sumara on Medium]]></title>
        <description><![CDATA[Stories by Daniel Sumara on Medium]]></description>
        <link>https://medium.com/@daniel-sumara?source=rss-5be825d472db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iJ8Lwz1cPUbjzQP0LK2o2g.jpeg</url>
            <title>Stories by Daniel Sumara on Medium</title>
            <link>https://medium.com/@daniel-sumara?source=rss-5be825d472db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 07:08:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daniel-sumara/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Removing singletons]]></title>
            <link>https://daniel-sumara.medium.com/removing-singletons-4340c6f6398a?source=rss-5be825d472db------2</link>
            <guid isPermaLink="false">https://medium.com/p/4340c6f6398a</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Daniel Sumara]]></dc:creator>
            <pubDate>Thu, 29 Apr 2021 13:24:42 GMT</pubDate>
            <atom:updated>2021-04-29T13:24:42.831Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://daniel-sumara.medium.com/refactoring-for-testability-453fb43de302">Refactoring for testability</a> / Removing singletons</h4><h4>Let’s check what can we do to improve code testability by removing singletons methods calls from methods.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kBL_kOt3hJ0rEoHW" /><figcaption>Photo by <a href="https://unsplash.com/@casparrubin?utm_source=medium&amp;utm_medium=referral">Caspar Camille Rubin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I don’t want to elaborate on is <em>singletons</em> are good, bad, useful, helps solve some problems or introduce ones. I would like to focus on how they affect code testability.</p><p>Code that heavily relies on <em>singletons</em> is commonly considered untestable. It’s very hard to verify our assumptions or fakes input data when we cannot use test double.</p><p>But this kind of code can be easily refactored in few steps to allow testability.</p><h3>A short story about our assignment</h3><p>Imagine our application can generate some kind of report. To do it application makes a network request. The amount of data is quite big, so this operation can take over one minute. To prevent screen lock and request cancellation we need to disable the idle timer. Let’s assume our network session timeouts are configured properly.</p><p>To improve user experience and fulfil his needs we need to add the ability to generate report between selected dates.</p><h3>Iterations</h3><h4>Identifying what to do</h4><p>We should start with identifying the code we need to amend. For my example, I decided to start with the model class which is responsible for communication with the backend service and application layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45d4c76b9d1a53bf863416b6b84f9fd7/href">https://medium.com/media/45d4c76b9d1a53bf863416b6b84f9fd7/href</a></iframe><p>This class uses two singletons: UIApplication.shared and ReportsNetworkService.shared. I would consider this class untestable.</p><p>In terms of unit tests, I would like to test if</p><ul><li>an idle timer is disabled when this method is called</li><li>an idle timer is enabled back again when the network service respond (either with success and failure)</li><li>failure error is passed to the client if the network service fails for some reason</li><li>valid GeneratedReport is passed to the client if the network service didn’t fail</li></ul><p>From the above list, I’m able to check only the first position. The rest of the cases are dependent of ReportsNetworkService which make calls to third party service. We cannot predict the response from this service.</p><p>Considering writing unit tests for the above code:</p><ul><li>we shouldn&#39;t rely on external dependencies (like backend service)</li><li>be able to provide the desired output from dependencies (like response result)</li></ul><h4>The first iteration of <em>refactoring</em></h4><p>The first and the easiest thing to do to make this class more testable is assigning singletons as object properties. <br>We can do this using constructor (initializer) injection like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18f42e7a95c3ae29ec1cabde085eb6a1/href">https://medium.com/media/18f42e7a95c3ae29ec1cabde085eb6a1/href</a></iframe><p>As part of <em>refactoring </em>activities:</p><ul><li>we do not introduce changes outside class (thanks to initializer default parameters)</li><li>we improve code structure (we can identify class dependencies)</li><li>we improve code understanding (application property is used to interact with the application, reportsNetworkService is used to communicate with backend service) — <em>do we?</em></li></ul><h4>Second iteration?</h4><p>Changes we made doesn’t really help make this component more testable. In test target, we can create classes that inherit from our dependencies and override called methods to provide desired behaviour or check if the method was called, but in my opinion, it is not the way we should follow.</p><p>But at this point, we know exactly the dependency interface we are using. We can extract it and make our classes confirm it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0677e179bc42ff35c2fa631f71e05460/href">https://medium.com/media/0677e179bc42ff35c2fa631f71e05460/href</a></iframe><p>After this, we can update the class we are focused on to looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/119f7ae439663dde1110d64f1a413ef4/href">https://medium.com/media/119f7ae439663dde1110d64f1a413ef4/href</a></iframe><p>We didn’t make any changes outside the class. <br>We didn’t introduce any changes in behaviour. <br>We did introduce new focused protocols for dependencies. <br>We did rename properties to be more meaning full.</p><p><strong>At this point, we should finish <em>refactoring</em> activities for this component.</strong></p><p>It is worth making a commit or even pull (or merge) request to let someone evaluate our changes.</p><h3>What’s next?</h3><p>The next step should be writing unit tests (as described above) to cover expected component behaviour.</p><p>As we have focused protocol on which system under test relays we can easily create test double in the test target.</p><p>When we finish with this activity we should again allow someone to review our code.</p><p>From that point, we are free to extend component functionality. Thanks to previous actions we have clear code which we understand. We have also unit tests that should prevent introducing regression.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4340c6f6398a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring for testability]]></title>
            <link>https://daniel-sumara.medium.com/refactoring-for-testability-453fb43de302?source=rss-5be825d472db------2</link>
            <guid isPermaLink="false">https://medium.com/p/453fb43de302</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[testability]]></category>
            <dc:creator><![CDATA[Daniel Sumara]]></dc:creator>
            <pubDate>Wed, 28 Apr 2021 11:03:28 GMT</pubDate>
            <atom:updated>2021-04-29T13:30:05.785Z</atom:updated>
            <content:encoded><![CDATA[<h4>What’s exactly is refactoring and can it improve our application testability?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mJhzv_hecSC3EzeK" /><figcaption>Photo by <a href="https://unsplash.com/@casparrubin?utm_source=medium&amp;utm_medium=referral">Caspar Camille Rubin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What refactoring is?</h3><p>As Martin Fowler point in his book “Refactoring”:</p><blockquote>Refactoring is a controlled technique for improving the design of an existing code base. Its essence is applying a series of small behavior-preserving transformations. [..]</blockquote><p>So <em>refactoring</em> is about improving existing code but without changing its behaviour, by small transformations. <br>For example, this <strong>could be</strong> <em>refactoring</em> activities:</p><ul><li>renaming variables and methods parameters to be more meaningful</li><li>breaking large methods into smaller and more focused methods</li><li>moving responsibilities between components</li><li>extracting interfaces from classes</li></ul><p><em>Refactoring</em> aims to create more readable and understandable code without introducing any behaviour changes. We shouldn’t call activities like:</p><ul><li>adding logging or error handling (change behavior)</li><li>reimplementation of component (redesign/rewriting, big scope)</li><li>extending components (adding new functionalities, change behavior)</li><li>rewriting implementation (redesign/rewriting)</li></ul><p>as <em>refactoring.</em></p><h3>What should be the scope of refactoring?</h3><p>We should <strong>only</strong> <em>refactor</em> the code we are working on. <br>If we spot the “ugly” code in a class that is not related to our current assignment, we shouldn’t do anything with this code. Just let it as is.</p><p>Our entry point should be method or function and we shouldn’t go out of class scope. As changes we introduce should be small and focused, the scope should be the same.</p><p>It’s good to limit our <em>refactoring</em> changes to only a few classes. It helps a lot not to get into a situation where we made more <em>refactoring</em> changes than increment changes. Fewer changes mean more focused code review.</p><p>If refactoring aims to change public API (for instance rename method), a better option is to introduce the new name and mark the old method as deprecated. <br>This way there will be no shadowing changes someone needs to review. After we finish developing our feature, we can create a new commit (pull/merge request) with only API changes (method rename). At the end of the renaming process, we should remove the deprecated method.</p><h3>When do refactoring?</h3><p><em>Refactoring</em> should be a continuous process. We should consider it as part of your daily work. Just like writing unit tests before writing code ;-).</p><p>We shouldn’t expect that we will have some task to do <em>refactoring</em>. We shouldn’t plan <em>to refactor</em> as a future chore to do. This should be part of each increment.</p><h4>Edge cases?</h4><p>We shouldn’t “waste” time <em>refactoring</em> when the project has a short lifetime.<br>For short projects, it’s better to ship functionalities as soon as possible. Making code more clear, when no one will back to it have little sense.</p><p>While <em>refactoring</em> when we identify the obvious bug, we shouldn’t do anything to fix them. We should continue with changes for readability and understandability.</p><blockquote><em>Refactoring</em> aims to create more readable and understandable code <strong>without introducing any behaviour changes</strong>.</blockquote><p>We should put some comments about the identified bug in the code and create a task to fix it in our task management system.</p><h3>What about testability?</h3><h4>Should we <em>refactor</em> the code if we haven’t unit test covering the code we amend?</h4><p>I think we should. If we have a unit test, we can feel more confident doing refactor but in my opinion, it is not required.</p><p>In the case where we haven’t unit tests, we have to be very careful about changes to not introduce a regression. <strong>Small</strong> and <strong>focused</strong> should be our priority. Also, our <em>refactoring</em> activities should be reversible.</p><p><strong>For the above point, code review is very important. </strong>In general, someone should evaluate our changes. What is readability/understandability improvement from our perspective can confuse someone else.</p><h4>Could refactoring improve testability?</h4><p>I would say yes.</p><p><em>Refactoring</em> improves code from a code reader perspective. <br><em>Refactoring</em> activities (like for instance extracting interfaces) could also make classes more testable (or event testable if they weren’t before).</p><p>Writing unit tests for refactored components <strong>shouldn’t </strong>be threaded as <em>refactoring</em> activity, but these activities can open a way to write unit tests for components.</p><h3>Go deeper?</h3><p>If you like to explore more about refactoring for testability I encourage you to take a look at:</p><ul><li><a href="https://daniel-sumara.medium.com/removing-singletons-4340c6f6398a">Removing singleton</a><br>Let’s check what can we do to improve code testability by removing singletons methods calls from methods.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=453fb43de302" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UnitTests multiple inputs]]></title>
            <link>https://daniel-sumara.medium.com/unittests-multiple-inputs-6017cef12e0f?source=rss-5be825d472db------2</link>
            <guid isPermaLink="false">https://medium.com/p/6017cef12e0f</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[xctest]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Daniel Sumara]]></dc:creator>
            <pubDate>Sun, 28 Apr 2019 16:15:14 GMT</pubDate>
            <atom:updated>2021-02-09T17:34:56.981Z</atom:updated>
            <content:encoded><![CDATA[<p>When I started to write unit tests for my code main metrics for me was code coverage. I was proud because Xcode prints almost 100% coverage for all my classes— but sadly QA team starts ping me with tickets for my part of application and I was like “What? I have unit tests for that!” — But I haven’t. I did test one <em>happy path </em>and thats all. Code coverage prints 100% for this method and I assume it is enough.</p><p>I did add new test method which cover bug pointed by QA, refactor my code and run tests again (wow — it was like pro TDD ;)).</p><p>After few new features, few changes in requirements, and couple days off (when my coworkers fixes blocking errors in my code ;)) files with tests for my functionalities looks like mess.</p><p>There was no such thing like structure. Tests methods looks like spaghetti or lasagne. Tests for one method was postponed by test for other methods from API.</p><p>It was time to review test files and do some refactor to cleanup this mess.</p><p>First thing that catches the eye was code duplication. Second was test for one method located between test for other methods.</p><p>Considering trivial example with <em>Calculator </em>my interface for <em>CalendarTests</em> could looks like:</p><pre>final internal class Calculator_Tests: XCTestCase {</pre><pre>    override internal func setUp()</pre><pre>    internal func test_AddingZeroToZeroReturnsZero()<br>    internal func test_AddingOneToFiveReturnsSix()</pre><pre>    internal func test_RemovingOneFromZeroReturnsZero()<br>    internal func test_RemovingTenFromTenReturnsZero()</pre><pre>    internal func test_AddingMinusTenToMinusTenReturnsMinusTwenty()</pre><pre>    // ...</pre><pre>}</pre><p>When there is not too many <em>given/arrange blocks </em>or data preparation cases it is not big deal, but when lot of test cases covers the same <em>given/arrange block </em>file swells very fast and we end up with file of 500 lines of code.</p><p>To solve this this problem I did try provide some structure to test file. I did move all test methods to group them into API references. This eliminate issue where tests for removing values was between adding tests. I close this method in groups like:</p><pre>// MARK: - Calculator.add(_: Int, to _: Int) -&gt; Int</pre><pre>// ...</pre><pre>// MARK: - Calculator.remove(_: Int, from: Int) -&gt; Int</pre><pre>// ... </pre><p>But there was still lot of duplicated code — mostly for setup tests.</p><p>Thanks to Swift syntaks I was able solve this problem too.</p><p>We can define methods in methods (method/function is first class citizen in Swift). So we are able to write test case for multiple input data, but invoke same code. This test case for our trivial <em>Calculator</em> could looks like:</p><pre>private var sut: Calculator!</pre><pre>// Setup code</pre><pre>func test_AddingValues() {<br>    func expect(adding firstValue: Int, to secondValue: Int, is result: Int) {<br>        XCTAssertEqual(sut.add(firstValue, to: secsecondValuend), result, &quot;Adding \(firstValue) to \(secondValue) is not \(result)&quot;)<br>    }</pre><pre>    expect(adding: 0, to: 0, is: 0)<br>    expect(adding: 0, to 1_000, is: 1_000)<br>    // Some more &quot;edge cases&quot;<br>}</pre><p>Providing message argument to <em>XCTAssert</em> function allows results be very clear when something goes wrong.</p><p>Real life examples may be much more complex, but if we trend to follow TDD principles and create pure functions for our API where it is possible I think we will be able structure our tests to accept only data as input.</p><p>Let consider class which looks like:</p><pre>public final class DefaultReportedField: ReportedField {</pre><pre>    // MARK: - Properties</pre><pre>    private(set) var value: String = .empty</pre><pre>    // MARK: - Lifecycle</pre><pre>    public init() {<br>    }</pre><pre>    init(with value: String) {<br>        self.value = value<br>    }</pre><pre>    // MARK: - API</pre><pre>    public func set(_ value: Any) {<br>        // Converts given value to string and store it in value property<br>    }</pre><pre>    public func getValue&lt;ValueType&gt;() -&gt; ValueType? {<br>        return // string value string to ValueType<br>    }</pre><pre>}</pre><p>This class is used as model for some kind of form. At some point <em>value </em>property was used to commit data to backend system. Interface for test file looks like:</p><pre>internal func test_SetBoolValueToTrue()<br>internal func test_SetBoolValueToFalse()<br>internal func test_GetBoolValueIfNoValueWasSet()<br>internal func test_GetBoolValueIfTrueWasSet()<br>internal func test_GetBoolValueIfFalseWasSet()<br>internal func test_SetDateValue()<br>internal func test_getDateValueIfNoValueWasSet()<br>internal func test_GetDateValueIfValueWasSet()<br>internal func test_SetDecimalValue()<br>internal func test_SetDecimalWithFractalValue()<br>internal func test_SetDecimalAsNil()<br>internal func test_GetDecimalValueIfNoValueWasSet()<br>internal func test_GetDecimalValueIfValueWasSet()<br>internal func test_SetStringValue()<br>internal func test_GetValueIfNoValueWasSet()<br>internal func test_GetStringValue()</pre><p>File was almost 300 lines long.</p><p>After some refactor file was about 100 line of code and contains only two tests in interface:</p><pre>internal func test_SetValue()<br>internal func test_GetValue()</pre><p><em>test_SetValue() </em>could<em> </em>looks like:</p><pre>private var sut: ReportedField!</pre><pre>// some setup</pre><pre>func test_SetValue() {<br>    func expect(setting value: Any, produce result: String) {<br>       sut.set(value)<br>       XCTAssertEqual(sut.value, result, &quot;Setting \(value) don&#39;t produce \(result)&quot;)<br>    }</pre><pre>    expect(setting: true, produce: &quot;1&quot;)<br>    expect(setting: false, produce: .empty)<br>    expect(setting: 0, produce: &quot;0&quot;)<br>    expect(setting: 1_234, produce: &quot;1234&quot;)<br>    expect(setting: 12.55, produce: &quot;12.55&quot;)<br>    expect(setting: 12.55786, produce: &quot;12.55&quot;)<br>    expect(setting: Date(timeIntervalSince1970: 0), produce: &quot;1970-01-01&quot;)</pre><pre>    // ...</pre><pre>}</pre><p>I think it is nice improve of my test. What do you think? If you have any comments please leave note.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6017cef12e0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interface localization]]></title>
            <link>https://daniel-sumara.medium.com/interface-localization-a5850927573e?source=rss-5be825d472db------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5850927573e</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[interface-builder]]></category>
            <dc:creator><![CDATA[Daniel Sumara]]></dc:creator>
            <pubDate>Sat, 23 Sep 2017 20:59:12 GMT</pubDate>
            <atom:updated>2017-09-24T11:32:50.839Z</atom:updated>
            <content:encoded><![CDATA[<p>If we target our application in more wide range than our country, it is good to localize application to be understandable by users. Very good habit is localize application in your native language and at least in English.</p><p>Making localizations in iOS application can be little tricky.</p><h4>UI internationalization</h4><p>Old days to localize interface file (xib or storyboard), xCode create clone of that file with in *language-code*.proj.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*3iXNVMXKoIpL_UdgUeqcgQ.png" /></figure><p>We have exact the same file, where we can change properties on UI components like labels, buttons, etc.</p><p>One plus of this approach is that, we can define entirely different UI for different countries.</p><h4>Base internationalization</h4><p>To avoid cloning interface files we can mark <strong>Use Base Internationalization</strong> checkmark in Project General Tab, than we can choose to use Interface File or Strings file to internationalize UI part of our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*4N1DZHTh3Z9t790vOqkM8g.png" /></figure><pre>/* Class = &quot;UIBarButtonItem&quot;; title = &quot;Add&quot;; ObjectID = &quot;aFc-bV-NJn&quot;; */</pre><pre>&quot;aFc-bV-NJn.title&quot; = &quot;Add&quot;;</pre><pre>/* Class = &quot;UINavigationItem&quot;; title = &quot;Presentation&quot;; ObjectID = &quot;cZ7-QZ-PGj&quot;; */</pre><pre>&quot;cZ7-QZ-PGj.title&quot; = &quot;Presentation&quot;;</pre><p>It reduce application size. We haven’t cloned our UI times languages we support, but this files are very hard to read/understand and even harder to maintain. xCode do not support life update strings file when we add new UILabel.</p><h4>Using code to localize UI</h4><p>When we build entire view from code it is very natural to set localized string from code. Wen we have xib or storyboard file it is strange to make outlet to each control and translate presented value. <br>I saw solutions where one use some fancy method which iterate over all subviews in view hierarchy and translate labels base on tags or <strong>User Defined Runtime Attributes</strong> to find translate kay. <br>This lead to invoke some code in viewDidLoad, awakeFromNib or some other initialize method when we add new localized view… lot’s of work.</p><h4>My solution</h4><p>After three years of buildings UI in iOS applications I came to some conclusions how to build easy maintainble and expandable UI. <br>From some time I use custom classes to almost each component which I define in Interface Builder. This allow me smoothly introduce my approach in my applications.</p><p>My class hierarchy connected with UI looks like:<br>* Label: UILabel<br>** AccentLabel: Label<br>** SecondaryLabel: Label<br>* Button: UIButton<br>* TextField: UITextField<br>… and so on.</p><p>in each class on top in hierarchy i have <strong>@IBInspectable </strong>property. For Label class is is defined as:</p><pre>@IBInspectable<br>public var localizable: Bool = false {<br>    didSet {<br>        guard localizable else { return }<br>        guard let text = text else { return }</pre><pre>        self.text = NSLocalizedString(text, tableName: &quot;UIStrings&quot;, comment: text)<br>     }<br>}</pre><p>When this property is set either form Interface Builder or code <strong>didSet</strong> observer is called. When new value is set to true and label have some text, I’m looking for that key in <strong>UIStrings.strings</strong> file, which is localized in main bundle of my application.</p><p>In Interface Builder in Identity Inspector I set class for label as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*5I5eGyTjFgYTo-huwp-KwQ.png" /></figure><p>And in Property Inspector i set inspectable attribute to on as fallow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*2zSqwDs9QElEi4l4oZmD5g.png" /></figure><p>This action add User Defined Attribute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*paMb5xO0Pyx3kHhVmKCWOQ.png" /></figure><p>This attribute will be resolved after class will be loaded into memory and text defined in text property will be translated if there is key in strings file.</p><p><a href="https://github.com/DanielSumara/LocalizationPOC">My POC (Prove of concept)</a> application UI looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*glyTXmOmgqP2kR01kfxWaA.png" /></figure><p>Which is resolved as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0DD4JSYjZAfUi0cebGK6UA.png" /><figcaption>English and Polish UI</figcaption></figure><p>You can sneak into my POC on github.com: <a href="https://github.com/DanielSumara/LocalizationPOC">LicalizationPOC</a></p><p><strong>Pros:</strong></p><ul><li>Lack of multiple xib/storyboard files describing same piece of UI</li><li>Always updated and synchronized localization with UI</li><li>Human readable — You don’t have to jumping between tabs in IB to find object identifier and match it with row in strings file.</li><li>Lack of gradation. Interface localizations are in one string file. They aren’t split into lots of interface files.</li><li>Easy maintainable. If you like localize label, all you have to do is set one switch in Interface Builder.</li><li>Easy extendable. If you add new scene, all you have to do is set one switch in Interface Builder. ;-).</li><li>You can use readable strings (English/Polish/Germany) words while you use it in strings file.</li></ul><p>Of course your have to keep your UIStrings.strings file up to date.</p><p><strong>Cons:</strong></p><ul><li>You have to set class in Identity Inspector.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5850927573e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text formatting in Swift]]></title>
            <link>https://daniel-sumara.medium.com/text-formatting-in-swift-79281ab2768?source=rss-5be825d472db------2</link>
            <guid isPermaLink="false">https://medium.com/p/79281ab2768</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[os-x]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Daniel Sumara]]></dc:creator>
            <pubDate>Sun, 09 Apr 2017 16:49:51 GMT</pubDate>
            <atom:updated>2017-08-18T07:29:11.294Z</atom:updated>
            <content:encoded><![CDATA[<p>In almost every app there comes time when we have to make some formatting. Some time we need to convert Bool into readable string, more often Date object into text literal which will be understandable to people who use our application, not saying about rounding numbers to two spaces after coma/dot sign (depending of country or OS settings) or placing separator between thousandths parts of number.</p><p>Apple come across this requirements and create sets of <a href="https://developer.apple.com/reference/foundation/formatter">formatters</a> which we can consume in our applications. Intension of Apple developer was creating very clear API, which witch will be country independent but also very customizable. They make very good job with this. For example to create DateFormatter to print Date without time in single label on screen we have to:</p><pre>var date: Date = //... 2001-01-02</pre><pre>func setupDate() {<br>    let dateFormatter = DateFormatter() <br>    dateFormatter.dateStyle = .mediumStyle <br>    dateFormatter.timeStyle = .noStyle</pre><pre>    dateLabel.text = dateFormatter.string(from: date)<br>}</pre><p>This will display different strings depend on iOS or OS X language preferences. If we use English as our default language this will display Jan 2, 2001, for French we will get 2 janv. 2001 and for Japanese we get 2001/01/02 .</p><p>Rest of formatters have very similar API. We can use enums to define behavior depending on language preferences, but we also can use string formats to create system configuration independent formatter. When we send date to REST Service as string we can define our formatter as:</p><pre>func getCurrentDateStringForRest() -&gt; String {<br>    let dateFormatter = DateFormatter()<br>    dateFormatter.dateFormat = &quot;yyyy-MM-dd HH:mm:ss&quot;</pre><pre>    return dateFormatter.string(from: Date())<br>}</pre><p>We have very good and useful tool in *Formatter classes, but creating new instance of formatter whenever we needed one can be frustrated. More over <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> is broken, because we repeating exactly same code to create formatter in different places of our application. To solve this problem lot of programmers creates singletons, utilities classes or static properties in viewModels. If it leads to remove duplicated code it is good. If it leads to reduce of created instances of formatters it is even better.</p><p>I decided to create my formatting utility in Swift way, using structs and extensions.</p><p>First step was creating container for my formatters. I end up with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/396626c7e8ba12739e7c1260be1e191d/href">https://medium.com/media/396626c7e8ba12739e7c1260be1e191d/href</a></iframe><p>One file with single structure Formatters which will be container for concrete formatters. If you like you can change struct to enum to get Phantom type (It is type which can’t create any instances — you can achieve same result creating struct with private init). <br>In the very same directory I create another file called Formatters+Numbers.swift where I put:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/236e03e46111ed4c89533da56aa034d9/href">https://medium.com/media/236e03e46111ed4c89533da56aa034d9/href</a></iframe><p>In extension for Formatter struct/enum I create another struct/enum for formatters related with <strong>Numbers </strong>with three properties (<strong><em>static properties are lazy by default) </em></strong>representing my formatters and sets of methods for changing numbers into well formatted strings. Values passed to methods could be optional, in that case I return default value if client define one or empty string. Intelisense for xCode resolve this into:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZuwCYh6Eq0I0AHuhKhvbUg.png" /></figure><p>I create one formatter per one result type. Apple docs says Formatter classes are thread safe, but if we are using one instance in lot of threads much better is use unmutable objects. If you need more overloads, just define it. Business of mine required only that ones, so I decide to not implement more over that I need. It makes my code simpler and cleaner.</p><p>Beyond API to formatting numbers I also need formatters for Date objects. So I create file called Formatters+Dates.swift as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/468ef41e97365b8b8e8d046e36564fbd/href">https://medium.com/media/468ef41e97365b8b8e8d046e36564fbd/href</a></iframe><p>Business required formatting independent of OS (hardcoded strings formats), so I create extra Format enum with strings I need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rw1_D4JaCvd5dcp7KkmMlg.png" /></figure><p>As you can see API is very easy to learn and very clear. Moreover, tapping on format case with option key will show us comment/documentation if one don’t know which format should be used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_AvKku8XVpJCqISkv43mYw.png" /></figure><p>My last formatter type is Boolen. I need convert true or false into “Yes” or “No” strings. So I create another file Formatters+Boolen.swift with single method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe7ba6d9df847e5443e1150bcceb78f1/href">https://medium.com/media/fe7ba6d9df847e5443e1150bcceb78f1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*z77ZVEI4QmSql26gEmAVYA.png" /><figcaption>Intelisense from xCode display my formatter as image show.</figcaption></figure><p>My formatters are grouped in Formatter namespace. My code is grouped in directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*KukhxsXqYVnzUOfW2SkYww.png" /></figure><p><strong>Pros:</strong></p><ul><li>Formatters are grouped by types</li><li>Very clear API</li><li>Thread safe</li><li>No god class — each type have own file with code base</li><li>Easy to extend</li><li>Easy to test (we didn’t mutate formatters)</li></ul><p>We can do more extension :) Let’s extend our UILabel to use our new code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a679d59b9c858e114e5704ab36bf639b/href">https://medium.com/media/a679d59b9c858e114e5704ab36bf639b/href</a></iframe><p>And we can use it in client code as:</p><pre>func set(balance: Double) {<br>    balanceLabel.text(from: balance) // 13 234,56<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79281ab2768" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Targeting Swift framework (AKA preprocessor directives in frameworks)]]></title>
            <link>https://daniel-sumara.medium.com/targeting-swift-framework-aka-preprocessor-directives-in-frameworks-6956c4f2784f?source=rss-5be825d472db------2</link>
            <guid isPermaLink="false">https://medium.com/p/6956c4f2784f</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Daniel Sumara]]></dc:creator>
            <pubDate>Sun, 02 Apr 2017 20:54:05 GMT</pubDate>
            <atom:updated>2017-04-02T20:54:05.959Z</atom:updated>
            <content:encoded><![CDATA[<p>Some times we need some configuration at build level. To present something for one client and hide for other. In Swift projects we have <strong>Swift Compiler — Other Flags </strong>where we can define flags (by adding line with -D prefix like: -DOUR_FLAG in build configuration). <br>Moreover we are restricted to check if flag was defined or not only. We can’t read value from there.</p><p>If we have application splitted over frameworks we have to define ours <strong>Other Flags</strong> in each framework which using them. <br>Let’s say we have product which is shipped to five clients. Each of them have different requirements about visibility of business modules, but some of them are intersecting. We have our code splitted up over seven frameworks. It’s lot of work to configure our projects to works as we want, and keep all of them up to date (in example: if we create new flag in main app (one of clients don’t want orders in his application) we have to add this flag to all frameworks which could using it).</p><p>That kind of configuration leads us to having:</p><ul><li>lot’s of <strong>Preprocessor</strong>/<strong>Swift Other Flags</strong> lines in project configuration</li><li>lot’s of preprocessor tests in code</li><li>splitting up same code over different projects/frameworks (<a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>)</li><li>necessity of keeping frameworks updated (in case when we remove business module or client)</li><li>necessity of synchronization between application and frameworks</li></ul><h4>But what can we do to make it better?</h4><p>We can abstract <strong>Other Flags</strong> to enum, and configure it in main bundle. This allow us to remove duplicated line from all frameworks and we will have Swift type validation — if we make typo in our code compiler will prompt us.</p><p>But we have to do some coding work :)</p><p>I have framework called <strong>Infrastructure</strong> which is included in all my business frameworks. As framework name says, code from this framework is connected with application infrastructure (there are some constants, utility classes or protocols). <br>I put there enum called <strong>Target</strong> with one static property <strong>current</strong>, and cases describing my needs (like client name or target in general).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea73ea4194f53b05e0bff318d8e556e8/href">https://medium.com/media/ea73ea4194f53b05e0bff318d8e556e8/href</a></iframe><p><strong>current</strong> property have weird structure. I will explain it:</p><ul><li>public — we need this property visible in frameworks which include <strong>Infrastructure</strong></li><li>static — we need instance to test, and static variable on type is good place to store it</li><li>internal(set) — this allows change variable value (set new one) only from framework; about how we will set/change value I’ll explain in next few lines</li><li>var — this property can be changed</li><li>name and type din’t need description :)</li></ul><p>Public setter for property current could be little bit dangerous. For example: for purpose of test we change value of Target.current property to tested value and we forget remove it after we finish testing/debuging code.</p><p>I decide to encapsulate setting this property in some struct. I do this with one of Swift mechanisms — extensions. <br>I have empty structure called Configuration. It looks like:</p><pre>public struct Configuration {</pre><pre>}</pre><p>And it is container for all my custom configurations. <br>Next step was creating extension for Configuration to set target and I did it like that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/683492ee2daa1aa12fdb88601274f58f/href">https://medium.com/media/683492ee2daa1aa12fdb88601274f58f/href</a></iframe><p>Before I start describing methods, I should mention something about method implementation.</p><pre>public extension Configuration {<br>    public struct <strong>Target</strong> {<br>        public static func setup(as target: <strong>Infrastructure</strong>.<strong>Target</strong>) {<br>            <strong>Infrastructure</strong>.<strong>Target</strong>.current = target<br>        }<br>    }<br>}</pre><p>Because of name collision between <strong>public struct Target</strong> in <strong>Configuration extension</strong> and <strong>public enum Target</strong> I have to use module prefix. This allows me have Target name in configuration and set Target.current property in different “namespace”.</p><p>I have two methods. First one as comment describe should be used only in appDelegate where we set current target. Second one should is for change value for testing or debuging. It will leave xCode warning while it will be in code. That kind of lines are harder to miss. <br>Ok, we have <strong>Target</strong> enum, know how to set new value to <strong>Target.current</strong> property, but how do we switch over targets?<br>We have to define our <strong>Swift Other Flags</strong> for build configurations, but only in main bundle (project with application) (DRY).<br>In <strong>AppDelegate</strong> class we have to switch over preprocessor directives like:</p><pre>#if APPSTORE<br>    Configuration.Target.setup(as: .appstore)<br>#elseif US_STOCK_MARKET<br>    Configuration.Target.setup(as: .usStockMarket)<br>// ...<br>#else<br>    Configuration.Target.setup(as: .develop)<br>#endif</pre><p>To handle <strong>Target</strong> configuration in client code, we didn’t have to put # if APPSTORE ///… in code any more but we can use verified by compiler enum syntax.</p><p>Client code could looks like:</p><pre>if Target.current == .develop {<br>    Log.info(&quot;Order processing started at: Date()&quot;)<br>}</pre><p>or</p><pre>if [Target.britishStoctMarket, .usStockMarket].contains(Target.current) {<br>    visibleModules.append(QuickOrderModuleConfigurator())<br>}</pre><p>or</p><pre>switch Target.current {<br>case .appStore: contactViewModel = AppstoreConstactData()<br>case .usStockMarket: constactViewModel = UsStockContactData()<br>// ...<br>}</pre><p>We have power of Swift, and we can go further and create extensions for our <strong>Target</strong> enum like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/021bb7ce7b6b7c2ed3b349331fe34695/href">https://medium.com/media/021bb7ce7b6b7c2ed3b349331fe34695/href</a></iframe><p>and us it as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3368878353b0f85d25b588c765bca5ed/href">https://medium.com/media/3368878353b0f85d25b588c765bca5ed/href</a></iframe><p>Let’s summup <br>Pros:</p><ul><li>new target configurations are added only in main bundle (application project) and <strong>Target</strong> enum</li><li>I have strong typed target configuration which are enums</li><li>lack of typos in preprocessor directives</li><li>I can extend Target enum to be more readable</li><li>I can provide configuration (backend address, branding name, etc) implementing computed properties in Target enum or extension</li><li>when I remove one configuration, I’ll clean up after my self (compiler don’t let me leave code with use that configuration — lack of zombi code)</li><li>xCode will generate warning if I left change Configuration code in source code</li><li>fully testable</li><li>clean separation between accessing to Target enum and setting value (one can’t change Target value “by mistake”)</li></ul><p>Cons:</p><ul><li>all frameworks have to include <strong>Infrastructure</strong> framework</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6956c4f2784f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Measure time in Swift]]></title>
            <link>https://daniel-sumara.medium.com/measure-time-in-swift-9004674f1374?source=rss-5be825d472db------2</link>
            <guid isPermaLink="false">https://medium.com/p/9004674f1374</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[os-x]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Daniel Sumara]]></dc:creator>
            <pubDate>Sun, 26 Mar 2017 21:16:50 GMT</pubDate>
            <atom:updated>2017-03-26T21:16:50.551Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometimes we need to know how long our code is executing. Mostly for debug purposes. If we have that knowledge, we can perform some steps to optimize algorithms or find bottlenecks in our code. <br>In some language <a href="https://en.wikipedia.org/wiki/Aspect-oriented_programming">aspect oriented programming</a> (AOP) can solve our problem in some aspects, but Swift is limping in that concept (… for now?).</p><p>While I’m developing my application, I can find lot of places where I put some code to calculate how long my methods are executing. <br>Sometimes it’s naive printing/logging Date() on the very first and very last line of method (sometimes in defer statement) like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/781d93ab92fc28d84ff3f6a95f72de19/href">https://medium.com/media/781d93ab92fc28d84ff3f6a95f72de19/href</a></iframe><p>There was cases where I needed to know how long my code works, not only when method starts and ends. I end up with something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b92061969bb3e90e6fc815eed0d5cf44/href">https://medium.com/media/b92061969bb3e90e6fc815eed0d5cf44/href</a></iframe><p>Moreover sometimes is good to know how long some objects are living or even if they are dealocated from memory. In that cases I create private property let created = Date() in class and in deinit { /* … */ } I’m putting another log message.</p><p>I end up with console full of different messages from different places about how long did something takes. This logs works for me only while I’m debuging or trying optimize my algorithms in one specific place of application. I know what console should prompt and observing this messages, and only that one. Rest of logs was totally trash about things which take places in different places of application. It should be remove… but what if I’ll need back some day to this pice of code? I leave that logs as they was written.</p><h4>There comes time to refactoring</h4><p>In the very first step I define my needs as:</p><ul><li>logging how long did method executes (this is my biggest intention)</li><li>logging place (file) where time was measured</li><li>optional logging some name (or label) to console</li><li>logging enter to the method</li><li>logging exit from the method</li></ul><p>I wont to be very Swifty and create struct called WatchDog as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33bb4bcd7e8a9da3189df00a63d7dbef/href">https://medium.com/media/33bb4bcd7e8a9da3189df00a63d7dbef/href</a></iframe><p>And I create WatchDog object and call this method depend of what I need like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e415ffa7ad5dc188e651dc98c6dba6b8/href">https://medium.com/media/e415ffa7ad5dc188e651dc98c6dba6b8/href</a></iframe><p>After some refactor I have unified logs. All have the same structure:</p><pre>// ...<br>WatchDog[ContextFactory] created at: 2017–03–26 11:01:06 +0000<br>WatchDog[ContextFactory: Create context] lived: 0.190793991088867 seconds<br>WatchDog[ContextFactory] lived: 0.190793991088867 seconds<br>WatchDog[ContextFactory] destructed at: 2017–03–26 11:01:06 +0000<br>// ...</pre><p>This allow me:</p><ul><li>filter logs only from one file</li><li>filter logs with label (like “Create context”)</li><li>find places/methods which takes more time then they should (bottlenecks)</li></ul><h4>But… I’am very lazy :)</h4><p>And typing watchDog.log…() is very annoying. I decide that pros from <a href="https://developer.apple.com/library/prerelease/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html">ARC</a> are more valuable than being “Swifty” by creating structs wherever I can.</p><p>Classes have one big advantage over structs. We know exactly when they are dealocated (removed from memory) and we can use that knowledge.</p><p>Lets assume we change our WatchDog struct to become a class. If we create instance of this class as stored property (and we didn’t pass reference of this object anywhere), this object will be dealocated in the very same time when object which contains it. This knowledge allows me to remove watchDog.logExit() from all deinit { } methods in classes where I want to monitor lifecycle, but I have to put this code in WachDog.deinit method (only once). Not very big effort, but less boilerplate code in future.</p><p>Same thing is about observing method duration. If we create local variable in method (and variable reference isn’t captured by closure or property in class) it is dealocated when execution exit from scope (program finish executing method). I can remove watchDog.logExit() from defer in methods.</p><p>Wait a moment. I have exit message in places where I want have duration only and I still have to type watchDog.logDuration() and watchDog.logEnter()…That’s sux.</p><p>I decided go one step further and add configuration switch in WatchDog.init method. Signature of constructor looks like: init(named label: String, logLifecycle: Bool = false, in file: String = #file) where label is text displayed after file name, logLifecycle is switch for printing creation and destruction of watchDog object (with default value set to false ) and file which is <a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Expressions.html">Swift expression</a> to get filename which invokes code. Next I moved logEnter() method to constructor and call it if logLifecycle is set to true and move logDuration() and logExit() methods to deinit with same condition for logExit() as logEnter() .<br>logDuration() is always printed when object is destructed.</p><p>This allows me to remove all watchDog.log…() calls from application and hide from interface (I make this methods private… and change names to be more clearly).</p><p>My WatchDog class source code looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f3eb7b405486a951d6f1c9266a99ba2/href">https://medium.com/media/7f3eb7b405486a951d6f1c9266a99ba2/href</a></iframe><p>… and my sample client class looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8c539d52f0fc77c38fc9bc699440912/href">https://medium.com/media/c8c539d52f0fc77c38fc9bc699440912/href</a></iframe><p>There is less boilerplate code but the effect is the same.</p><p>Making this refactoring I achieve few things:</p><ul><li>removing measure code which was repeated in different places (<a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>)</li><li>introduce structure for “Time measure” log messages, which allow me filtering console output, and finding bottlenecks</li><li>introduce very clear way to observing lifecycle of objects</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9004674f1374" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>