<?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 Declan Stewart McPartlin on Medium]]></title>
        <description><![CDATA[Stories by Declan Stewart McPartlin on Medium]]></description>
        <link>https://medium.com/@declanmcp?source=rss-ac75c6dc3afe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3JdzPfb_DMrHy7JR.</url>
            <title>Stories by Declan Stewart McPartlin on Medium</title>
            <link>https://medium.com/@declanmcp?source=rss-ac75c6dc3afe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 21:33:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@declanmcp/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[Clean Code - part #3]]></title>
            <link>https://medium.com/@declanmcp/clean-code-part-3-d73261af2470?source=rss-ac75c6dc3afe------2</link>
            <guid isPermaLink="false">https://medium.com/p/d73261af2470</guid>
            <category><![CDATA[coding-conventions]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Declan Stewart McPartlin]]></dc:creator>
            <pubDate>Sat, 21 Jan 2017 19:43:03 GMT</pubDate>
            <atom:updated>2017-01-21T19:43:03.875Z</atom:updated>
            <content:encoded><![CDATA[<p>The third and final part. If you missed the previous part, read it here:</p><p><a href="https://medium.com/@declanmcp/clean-code-part-2-ba021561daad">Clean Code - Part #2</a></p><p><strong>Formatting</strong></p><p>Formatting code is important. It helps with navigation, it helps communicate the code to the reader. As humans, we recognise shapes and spaces faster than we can read, use this to your advantage. A lot more could be said about our visual capabilities, instead I will leave it at this: formatting code is important, but it is useless without proper consistency.</p><p>There are a few options as to how to keep you code consistent, here are two:</p><ul><li>One option is code dependent and environment dependent: set the formatting rules inside the environment, share it with your coworkers.</li><li>The second option is more fool proof but requires more work: using git hooks. Nowadays there should be scripts to check the formatting of every popular language out there. Just make sure non of your coworkers excessively use bypassing git hooks.</li></ul><p><em>Vertical formatting</em></p><p>Each line represents an expression. Each group of lines represent a thought that are divided with an empty line. Bad habits like excessive comments and a full line just for an opening bracket break these visual dividers, making code harder to read.</p><p>It is said that a file should read like a newspaper article. If we are using an object oriented language, each file should contain one class. It should start with the headline, the class name. It should then state the most important information at the top, the attributes. It should then proceed with the main summary, the constructor and public functions. The details follow afterwards, the level of detail should grow the further down we go.</p><p><em>Horizontal formatting</em></p><p>The maximum length of a line is up for debate. But what is for certain is that there should be a maximum length enforced in the formatting. In the early years of programming, the length of each line used to be much shorter, because of the capabilities of standard computer screens. Today, usually there is no reason why a line should be any longer than 120.</p><p>As with vertical spacing, you should visually group and divide elements using spacing. As an example, an equality statement should have spacing on both sides of the equality operator (<em>Potato potato = new Potato(selectedColor, size);</em>). But when a function is called, there should be no spacing between the input values and the function itself, but spacing should be used between the input values (as shown above).</p><p>Indentation is an important part of the readability of your code. Sometimes you may be indulged to shorten if (or other block) statements into one line, I recommend you refrain from doing this, since it reduces readability and consistency.</p><p>Whatever you decide should be the formatting rules, make sure you do it as a team and not alone, as individuals. As they say, whatever happens, don’t forget the team rules.</p><p><strong>Concurrency</strong></p><p>This is probably the most important chapter in this article. Non concurrent code that is written badly leads to bugs. These bugs are repeatable and debuggable. Concurrent bugs are neither. It is essential that concurrent code is kept clean and kept in an isolated place, away from non concurrent code.</p><p>Although concurrency really deserves a whole article for itself, I will present a highly summarized version of what you as a developer should look out for first and foremost when writing clean concurrent code. I recommend to read much more about writing concurrent code afterwards, if you plan on working on a project using concurrency.</p><p>Some projects do not need concurrency. But for those that do need algorithms with concurrency, the design of the whole system should be impacted by the decision to use concurrency. Basically, if you decide to support concurrency midway through developing your project, make sure you implement your design change project wide.</p><p>Minimize the number of occurrences where concurrent code may appear. Isolate such code, do not duplicate concurrent code. Makes sure data that is used concurrently is encapsulated appropriately.</p><p>Instead of passing references to an instance of a concurrent object, pass a copy of it. If any changes were done to the copy, merge the changes after inside a single thread.</p><p>Research the capabilities and restrictions of the libraries and frameworks you use when it comes to concurrency. Some data structures may only work properly on specific threads, or might not support concurrency at all, so make sure you do your homework.</p><p>There are situations where resources must be locked so that only one thread can execute code on it at once. It is essential to make sure this code is kept to a minimum. As little code as possible should be locked to avoid <em>deadlocks</em>, <em>livelocks</em> and other concurrency issues.</p><p>Testing in concurrent code is a much more complex task than testing in a single threaded solution. Here, unit tests will not suffice. Before testing your concurrent code, make sure all your non concurrent code works as expected.</p><p>Things to keep in mind when testing concurrent code:</p><ul><li>Make it possible for your code to be tested with a specific number of threads. Test it with more threads than processors.</li><li>Make a test double that interacts with the concurrent code that can have a configured speed.</li><li>Set these tests so that they can run iteratively.</li><li>Make sure you test the code with all supported deployment environments.</li><li>Try to force failures. Add function calls (like <em>sleep()</em> or <em>wait()</em>) to change the order of the execution of code. Do this either manually or with automatics tools if possible.</li></ul><p>Writing concurrent code is hard, there’s no way around it. But with careful planning ahead, properly designing your project to accommodate concurrency, writing clean code and testing your code properly, you can minimize the possible issues that can arise with concurrency.</p><p>So here we are, we have covered the very basics of clean coding. Sticking to these policies is not just about being disciplined, but about being professional. Learning how to write clean code is a never-ending journey and our knowledge on clean code must be updated and reinforced regularly.</p><p>Enlighten your coworkers and friends with this knowledge, there’s few things worse than working on a project where you are the only one writing clean code. Thanks for reading such a long article, here’s a potato:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*0WyvB-tqf7GjL4qBWtDn6w.jpeg" /></figure><p>Links:</p><ul><li><a href="https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design">https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design</a></li><li>Clean Code: A handbook of Agile Software Craftsmanship, Robert C. Martin, 2009</li><li><a href="https://www.agilealliance.org/glossary/gwt/">https://www.agilealliance.org/glossary/gwt/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d73261af2470" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Code - Part #2]]></title>
            <link>https://medium.com/@declanmcp/clean-code-part-2-ba021561daad?source=rss-ac75c6dc3afe------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba021561daad</guid>
            <category><![CDATA[coding-conventions]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Declan Stewart McPartlin]]></dc:creator>
            <pubDate>Sun, 15 Jan 2017 17:56:25 GMT</pubDate>
            <atom:updated>2017-01-21T19:44:53.999Z</atom:updated>
            <content:encoded><![CDATA[<p>Here we will continue on where we left off from the first part:</p><p><a href="https://medium.com/@declanmcp/clean-code-part-1-f20880f427b0">Clean Code - Part #1</a></p><p><strong>Functions</strong></p><p>Now let’s focus on functions, all types of functions. It is so easy to turn a well written function into an absolute mess. To help with this, whenever you review a function, keep these rules in mind.</p><p><em>Have one responsibility</em></p><p>Functions should be carrying out one task only. If you can see that the function is actually carrying out several tasks, move one responsibility to a new function.</p><p>As an example, if a function contains a block (if-else, loops, …), that block should have one line for each block (a call to another function) since that responsibility should be handled by another function.</p><p>Another way to notice a function is handling multiple responsibilities, is if the function handles code at different levels of abstraction. Let’s say a function calls the function <em>getPotatoDescriptions()</em> but then also makes a very low level call like <em>potatoDescriptions.append(“;”)</em>. These two lines are at very different levels of abstraction, this should not occur in one function.</p><p>Make sure your function does not have side effects. Name your function carefully and appropriately, and make double sure it does only what it says it does. If the function is <em>initialize()</em>, make sure it doesn’t also set all the settings to default, as an example.</p><p>Probably one of the most important things to keep track of is to never ever duplicate code. Abstract that code to a point where it can be applied in every case in which it is being used.</p><p><em>Functions should be small</em></p><p>The first an foremost important aspect of a function is that is should be small. I cannot emphasize how important this is. Strive to make your functions no longer than four lines — of course there will be situations when this rule is broken, but very very few functions have a good reason to be longer than twenty lines.</p><p>Whenever you notice a function is too long (or even worse, using duplicated code), create a new function, name it carefully and carry out one responsibility there and keep doing this until the function sizes are acceptable.</p><p><em>The written order of functions</em></p><p>Previously we mentioned the level of abstraction within functions. As long as a function only carries out one level of abstraction, it is then easy to group and order functions within a file (or class, which in that case these functions are methods).</p><p>The functions with the highest abstractions should be at the top, those with the lowest should be at the bottom, this is called the <em>step down rule</em>. Imagine function 1 is called within function 2. Function 1 should always be below function 2, in every situation (unless it is a recursive function, then this is of course impossible).</p><p><em>Function arguments</em></p><p>A simple rule to summarize the topic of arguments is to keep them at a minimum. Watch out for tell tale signs of other broken rules like a flag argument (it is most likely that function is breaking the <em>one responsibility rule</em>). The best number of arguments is zero, acceptable numbers of arguments are also one and two in certain situations. Very few exceptions can justify three, and none can truly justify four.</p><p>There are two main reasons to keep argument numbers to a minimum. One is because conceptually it is hard to understand what a function is doing if it has many arguments. The second is that it is exponentially harder and longer to test a function with every extra input.</p><p>Output arguments can create a lot of confusion. Back in the days before OO programming, this was common place, but now it is no longer needed. Logic makes us expect that arguments that go in are solely input arguments and what comes out, the return value, is the output, or a function called upon an object solely manipulates the object itself. Stick to this notion whenever possible.</p><p>A solution to minimizing the number of input arguments could be to wrap the inputs into a class (or struct) of their own, especially if the combination of inputs occurs often. Another is to make the function a class method, and so on.</p><p><em>Error Handling</em></p><p>If you’re ever contemplating how to handle errors, if throwing exceptions is an option in the language you’re working with, that’s most likely the best way to do it.</p><p>Other options like custom error codes and similar solutions are messy, usually unclear and requires maintenance of its own, and it can get worse than that. At best, such errors are defined in enums, which are used throughout the project and become dependency magnets.</p><p>Using try/catch blocks can get messy quickly in their own right too. Remember, one function, one responsibility, so make sure the logic and the error handling are encapsulated in their own functions respectively.</p><p><strong>Tests</strong></p><p>In the modern age of programming, tests have become vital. It is no longer a question either to create tests or not — tests must be created. Why? Imagine you refactor a module in a large project. There are countless possibilities that bugs have been introduced, but tests cover that and allows us to continue to refactoring without worrying about creating new bugs, since with well written tests, these bugs will be caught and fixed.</p><p>One of the more progressive ideologies of how tests should be created is Test Driven Development, TDD for short. The main goal of TDD is to write tests before the production code is even written. But in practice, write the tests just before writing the production code, it is not good practice to write them weeks in advance.</p><p>Keep the tests clean. Irrelevant if the code is test or production code, keep it clean, keep it readable. The only real attribute that production code must have and test code can live with less is efficiency. But don’t let your tests rot, you will regret it in the future.</p><p>One test should have one assert. It may seem like overkill, but it helps to make sure the test has one goal, one responsibility. It makes the tests concise and to the point. If you decide to break this rule, make sure one test has only one concept.</p><p>Tests should be made of three parts: given, when, then.</p><ul><li><em>Given</em> sets the context for the test</li><li><em>When</em> carries out an action to be tested</li><li><em>Then</em> validates the outcome</li></ul><p>A set of rules regularly quoted are called FIRST.</p><ul><li>Fast: Although tests don’t need to be as efficient as production code, if they take too long to run, programmers will avoid using it and code will start to rot.</li><li>Independent: Tests should be independent from each other. One test should not set up the context for the next, such situations create cascading effects that make testing harder.</li><li>Repeatable: Tests should be repeatable anywhere, in any condition. With or without an internet connection or any specific device. There should be no external excuses as to why a test is failing.</li><li>Self-validating: Tests should return either passed or failed, logs and other forms of output are unacceptable for tests, since this leads to subjective views as to whether the test passed or not along with many other issues.</li><li>Timely: As previously explained, tests should be written right before the production code being tested is written.</li></ul><p>I could easily write a whole article about tests, but since this article is about clean code, let’s leave it at that.</p><p><strong>Comments</strong></p><p>A good way to encapsulate comments in programming as a whole is calling them failures to express ourselves through our code. If your code needs an explanation it is not good code, instead of investing your time writing a comment, you should invest it in refactoring your code.</p><p>The biggest problem with comments is that they do not have to be correct and truthful for the program to work. Of course in most cases when a comment is written, the comment is correct. But code is cut and copied, rewritten, removed. As for the comments, they may or may not be in the right place anymore, propagating false or even damaging information.</p><p>There are certain situations where comments make sense.</p><ul><li><em>Copyright purposes</em>: Sometimes we need to add a copyright statement for corporate coding standards at the beginning of each file.</li><li><em>Display of intent</em>: In some situations, a decision on why a certain feature was implemented can be documented inside the code, since this cannot be expressed in code.</li><li><em>Warning</em>: Especially in situations like running a test, it makes sense to warn the user of the consequences of using the code: the possibility of high CPU usage, a long run time, etc.</li><li><em>TODO</em>: many environments detect TODO comments nowadays, and it is sometimes acceptable to use them, since it helps the reader understand why a function is a stump.</li><li><em>Reinforcement</em>: some code needs extra reinforcement so the user knows this code is important. This is used as an effort to avert the user from accidentally removing code that may seem excessive.</li><li><em>Documentation</em>: Especially in libraries and frameworks, comments (or in Java and some other languages, special types of comments) are used as a fast and accessible way of documenting code. Be aware of the dangers of excessive comments as explained above, the same rules apply here. Also, when you estimate the time it will take to write code for a library or framework, keep in mind the time it will take to create and maintain the documentation comments.</li></ul><p>Thanks for reading, here’s another potato:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*frJgrMWSr7RJ2Ts_8gAoYg.png" /></figure><p>Continue reading here:</p><p><a href="https://medium.com/@declanmcp/clean-code-part-3-d73261af2470">Clean Code - part #3</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba021561daad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Code - Part #1]]></title>
            <link>https://medium.com/@declanmcp/clean-code-part-1-f20880f427b0?source=rss-ac75c6dc3afe------2</link>
            <guid isPermaLink="false">https://medium.com/p/f20880f427b0</guid>
            <category><![CDATA[coding-conventions]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Declan Stewart McPartlin]]></dc:creator>
            <pubDate>Fri, 06 Jan 2017 21:07:09 GMT</pubDate>
            <atom:updated>2017-01-15T18:00:20.431Z</atom:updated>
            <content:encoded><![CDATA[<p>Since the dawn of programming, there has been talk of clean coding, the dos and don’ts to save time in the long run. Programming in essence is a craft that requires education and also experience. Through the decades, this craft has been evolving, changing — so too have the principles of clean coding. What is relevant now, may not be anymore in five years. That is why we have to keep track of what is relevant today, and not what was twenty years ago.</p><p>In this article we will have a look through the principles that still stand today, everything from the old to the new. I will also put more focus on the recurring mistakes I have witnessed more often over the years. Most of these principles should be applicable to most languages as well as design patterns.</p><p><strong>SOLID principles</strong></p><p>The goal of these principles is to have clean, extendable and easy to refactor code. Even though the SOLID principles is based upon Object Oriented Design (OOD), many of these ideas can be applied to any design.</p><ul><li><em>Single-Responsibility principle (SRP): </em>Every class should only have one reason to change. A class should have one job only. As an example, the class <em>Potato </em>should only return the weight (or mass) of the <em>potato </em>instance, and not offer a given unit in which it should return. That should be handled by the class <em>WeightConverter </em>(or <em>MassConverter</em>).</li><li><em>Open-Closed Principle: </em>Classes should be open to extension, but closed to modification. Classes shouldn’t need to be modified to be extended. In context, <em>WeightConverter </em>shouldn’t have to be modified every time a new weight unit is supported. For each new weight unit we should create a <em>WeightUnit </em>subclass, which should support a <em>convertedValue </em>function (that <em>WeightUnit </em>declares).</li><li><em>Liskov Substitution Principle: </em>If <em>q(a)</em> is a provable property of the instance a of class <em>T</em>, then <em>q(b)</em> is provable for the instance <em>b</em> of class <em>S</em>, where <em>S </em>is a subtype of <em>T</em>. Basically, instances of <em>S </em>should be able to replace instances of <em>T </em>with no problems. Example: the class <em>Potato</em> is the parent class of <em>SweetPotato</em>. For variable <em>sackOfPotatos</em> (let’s say it is an <em>Array&lt;Potato&gt;</em>) each instance inside it, regardless if it is a class or a subclass, it should always return a valid value for <em>getWeight</em>.</li><li><em>Interface Segregation Principle: </em>A given interface should never be forced to implement an interface it doesn’t use. Classes should not be forced to depend on methods they do not need. In short, <em>Potato</em> should not implement <em>SweetnessInterface</em>, it is <em>SweetPotato</em> that should.</li><li><em>Dependency Inversion Principle: </em>Entities should depend on abstractions, not on specific implementations. Higher level modules should not depend on lower level modules. In essence, when directly referencing to an object (including lower level modules, like a controller referencing a database) do not reference a direct implementation (a class), instead, reference an abstraction (an interface, a protocol).</li></ul><p><strong>Naming Conventions</strong></p><p>It is understated how important proper naming is. We will divide this chapter into three parts, but many points are relevant to naming conventions as a whole. As an example, variables, classes and methods should be named with their intent.</p><p><em>Variables</em></p><p>Avoid naming anything with a single character (<em>Potato p</em>) at all costs. It is unreadable, unsearchable and gives no added value to the code. The rare occasion when this sort of naming is acceptable is in a for loop (<em>int i</em>). The big “no no”s are using a lower case <em>L </em>and an upper case <em>o </em>(they look way too similar to the decimals 0 and 1).</p><p>Avoid using names that could be misleading. As an example, <em>pf </em>may have seemed like a useful abbreviation to you before, but out of context (<em>PotatoFactory pf</em>) it could mean anything.</p><p>Do not use a variable like <em>potatoList </em>unless the variable is in fact an actual List. Use a variable like <em>potatoes </em>instead. The word List represents a data structure to programmers, so don’t confuse them.</p><p>Never spell a variable wrong just to fix a duplicate variable issue. This will lead to a situation where fixing the spelling mistake will lead to compiling errors. Instead, put more effort into finding the true distinction between the two variables. Adding noise words like <em>Info</em> or <em>Data</em> hinder more than help. Adding <em>the</em> or <em>a</em> as prefixes to a variable are in nearly all cases noise words, avoid using them.</p><p>Make sure your variables are pronounceable, it improves readability and as humans it helps us to remember what it is used for. Also, when naming a new variable, try to make it as searchable as possible. Searching for a variable called “<em>a”</em> could be troublesome.</p><p>Back in the day it was good practice to state the variable type in the variable name itself (<em>String potatoString</em>), nowadays with environments that show us the type at any location and type checking, there is no need for this in most languages anymore, so steer away from this practice if possible, because otherwise this can happen during a rewrite: <em>Potato potatoString</em>. That’s misleading.</p><p><em>Methods</em></p><p>Methods should be named as verbs or verb phrases. Getters should always start with <em>get</em> (or <em>is</em> for booleans) and setters should always start with <em>set</em>.</p><p>As an example of consistency, let us focus on getters. In some cases <em>fetch</em> or <em>retrieve</em> is used instead of <em>get</em>, which is acceptable, but make sure the same word is used consistently, avoid mixing different words with the same meaning.</p><p>Do not be afraid of making the name of a method verbose — if it has to be. Sometimes, there is no other way of naming a method to an adequate level of detail. Avoid abbreviations, use full words wherever possible. A method name shouldn’t be unreadable just so the name is shorter.</p><p><em>Classes</em></p><p>A class name should be a noun, never a verb. It should avoid using noise words (<em>Manager</em>, <em>Data</em>, <em>Info</em>, <em>Processor</em>, etc.).</p><p>Use computer science specific names. The chances are that the people who will read your code will be programmers. Feel free to use words specific to computer science, like coding patterns (<em>PotatoFactory</em>) or classes ending in <em>Queue</em> if they are in fact queues, etc.</p><p>A class prefix is an abbreviation used in front of a class with the main responsibility of avoiding name duplicates (let’s say you work at Super Potato Enterprise, the prefix to all classes might be <em>SPE</em>). If you are not using the prefix for this reason, you are most likely using it wrong. In general, using class prefixes is a bad idea (slower searching, less readable names, possibility of inconsistency…), depending on the language. Java has packages to keep the class names from being global, C++ uses namespaces. But some languages do not have this, making all class names in a project global, including classes from frameworks and libraries (one example language being Objective-C). So if you are using prefixes, make sure you’re using them right.</p><p>As you can see, even with summarizing, there’s a lot to cover here, so I will spread the issue of clean code into three parts. The next two will follow soon. Thanks for reading, here’s a potato.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*B28SmRpqECzRPeAVfZ_opg.jpeg" /></figure><p>If you wish to continue reading on the subject of clean coding, check out part #2:</p><p><a href="https://medium.com/@declanmcp/clean-code-part-2-ba021561daad">Clean Code - Part #2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f20880f427b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Objective-C - Part #2]]></title>
            <link>https://medium.com/@declanmcp/efficient-objective-c-part-2-b73be35dccd3?source=rss-ac75c6dc3afe------2</link>
            <guid isPermaLink="false">https://medium.com/p/b73be35dccd3</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[objective-c]]></category>
            <category><![CDATA[naming]]></category>
            <category><![CDATA[scopes]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Declan Stewart McPartlin]]></dc:creator>
            <pubDate>Tue, 11 Oct 2016 17:54:35 GMT</pubDate>
            <atom:updated>2016-10-21T15:35:27.386Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a continuation of part #1, so let’s get to it!</p><h4>Importing classes</h4><p>A general rule with importing headers of classes is to do it as little as possible. The more headers imported means longer compile times at best, so remove unused imports whenever possible.</p><p>When a class header is imported in another given class header and that given class header is imported to another class, all its own imported classes are imported to that other class too. A lot of the time this is unnecessary.</p><p>But worse situations can happen, an example being an infinite inclusion of two classes including each other with <em>#include</em>. At compile time they include each other into an endless loop. Using <em>#import</em> stops the endless loop, but one of the classes incorrectly imports the other class, so the program will not run in most situations. Luckily, there is a way of only declaring a class exists, not importing or including it:</p><pre>//instead of importing like this<br>#import DSMPotato</pre><pre>//declare the class like this<br>@class DSMPotato</pre><p>Keep in mind that the class may be declared in the header, but imported in the implementation file if its interface information is needed. In essence, use <em>@class</em> whenever possible, only use <em>#import</em> in headers when there is absolutely no other choice (like including frameworks or protocols — which is why protocols must be in their own file).</p><h4>Global Variables</h4><p>Try to steer clear of using global variables, that’s rule one. But there will be situations where using them makes sense, like naming NSNotifications and other edge cases. There are a few ways of implementing this in Objective-C, and one I see too much is by using the preprocessor, like this:</p><pre>#define COMMON_STRING @&quot;common string&quot; </pre><p>If this is added to the header of a class, it is then included to every class that imports this class, this is bad. This code doesn’t use the compiler, the preprocessor simply swaps each definition with its value. In our example, COMMON_STRING is swapped to “common string” in all the classes it was imported. Not only can this cause unexpected issues by swapping definitions that weren’t intended to be swapped, it doesn’t imply any type, so it can create type issues at compile time, or even at runtime. A much better choice is to utilize the compiler by using constant variables, like so:</p><pre>//Naming for local constants<br>static NSString *const kConstantString = @&quot;common string&quot;;<br>static const CGFloat kConstantFloat = 0.2;</pre><p>Use this declaration and naming conventions for constants only used locally in an implementation file. Make sure you use <em>static</em> so that the compiler keeps the constant local. As for <em>const</em>, it makes sure the compiler throws an error if the constant value changes.</p><p>Using both <em>static</em> and <em>const</em> actually means that the compiler does not create local constants but replaces occurrences, similar to the preprocessor. Keep in mind though that the main difference is that the type information of the constant is declared.</p><p>Sometimes we need our constants global though, an example previously mentioned being <em>NSNotification</em> names. In this case, we have to declare the global constants like so:</p><pre>//Naming for global constants</pre><pre>//In the DSMPotato.h file<br>extern NSString *const DSMPotatoConstantString;<br>extern const CGFloat DSMPotatoConstantFloat;</pre><pre>//In the DSMPotato.m file<br>NSString *const DSMPotatoConstantString = @&quot;common string&quot;;<br>const CGFloat DSMPotatoConstantFloat = 0.2f;</pre><p>The difference between the two examples is one is an object reference whilst the other is a value reference, leading to different declarations.</p><p>Be careful how you name your constant, since it will be visible in the project’s global scope. The naming convention is to prefix the constant with the full name of the class, followed by the constant description. Based on the example, wherever DSMPotato.h will be imported, both constants will be visible too.</p><h4>Weak References</h4><p>Since OS X 10.8, the option to have a garbage collector on OS X has been deprecated, and it never existed on iOS. This means we have to take care of memory management. Since ARC was released, this means one of our last main concerns is being careful of retain cycles (along with corner cases, including <em>performSelector</em> and <em>blocks</em>).</p><p>A retain cycle is when at least two objects have a strong reference of the other object (or three objects, pointing to the next object, forming a cycle, and so on). This becomes a leak when neither of them are referenced by any other object than each other at runtime. Neither object is of use to the process anymore, yet they are kept alive because of their reference count.</p><p>As discussed in our last <em>Efficient Objective-C</em> article, we have two ways of having a weak reference with another object (not raising the reference count of an object even though we have a direct reference to it). These being <em>weak</em> and <em>__unsafe_unretained</em>.</p><p>Both properties have similar functions (they do not raise the reference count of the object), but the main difference is what happens when the referenced object’s reference count falls to zero.</p><p>The property <em>__unsafe_unretained</em> basically does nothing. Next time when the object is accessed, a dangling pointer is used, which can lead to unexpected behaviour, including a crash.</p><p>As for the <em>weak</em> property, once the referenced object is deallocated, the object reference now points to nil instead. This means that if the object is deallocated too quickly, the application not crash, which is favourable from a user point of view, but makes it harder to debug what is happening. The last thing we want is our users experiencing crashes, which is why I recommend using <em>weak</em> instead of <em>__unsafe_unretained</em> whenever possible.</p><p>The main situations when we should be using weak references are:</p><ul><li>When referencing a delegate or a parent object. The delegate design pattern utilizes a non owning relationship.</li><li>Inside blocks. Whenever referencing self inside of blocks, make sure the reference is <em>weak</em>.</li><li>Referenced IBOutlet objects should always be <em>weak</em>.</li><li>Using CF objects (although we use <em>CFRetain</em>() and <em>CFRelease</em>() instead of <em>strong</em>/<em>weak</em> properties).</li></ul><h4>Grand Central Dispatch vs NSObject’s performSelector</h4><p>I could write a whole article just about the<em> Grand Central Dispatch</em>. Instead, we will touch base with some less known situations when <em>GCD</em> is our best option.</p><p>Before <em>GCD</em> was added to iOS with iOS 4, <em>performSelector</em> was the function used for a whole array of different situations: calling functions that only appeared at runtime, calling functions after a certain amount of time, performing selectors on the main thread, along with other situations. Sadly <em>performSelector</em> (which is a method inherited by <em>NSObject</em>) has many drawbacks, including: input arguments (two maximum) must be objects, limited ability of returning values, possible runtime errors if the selector doesn’t exist and also memory management (ARC cannot know the type, which can cause leaks).</p><p>Luckily, <em>GCD</em> can be used instead of <em>performSelector</em> now in many cases, with <em>GCD</em> having many low level optimizations. Let’s start a comparison of both solutions with delayed methods:</p><pre>//The performSelector solution<br>[self performSelector:@selector(skinPotato:) withObject:potato afterDelay:5.0];</pre><pre>//The GCD solution<br>dispatch_time_t dispatchTime = dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC);<br>dispatch_after(dispatchTime, dispatch_get_main_queue(), ^{<br>    [self skinPotato:potato];<br>});</pre><p>All the issues faced by using <em>performSelector</em> are solved by using <em>GCD</em> instead. The next situation where we should really be using <em>GCD</em> is:</p><pre>//The performSelector solution<br>[self performSelectorOnMainThread:@selector(skinPotato:) withObject:potato waitUntilDone:NO];</pre><pre>//The GCD solution<br> dispatch_async(dispatch_get_main_queue(), ^{<br>     [self skinPotato:potato];<br> });</pre><p>No leaks happen with <em>GCD</em>, no runtime errors because of unknown selectors, no issues with input and output values.</p><h4>Thread safety</h4><p>Now let’s focus on multithreading. Sometimes when using multithreading, we need to make sure a value is not being accessed at the same time by two threads.</p><p>One option is using @<em>synchronized</em>. This is usually a good option, as long as we do not overuse it, since all @<em>synchronized</em> blocks are executed serially. Sadly, @<em>synchronized</em> gets overused a lot.</p><p>Another option is directly using the <em>lock</em> object. The issue with this option though, is that deadlocks tend to happen fast.</p><p>But there’s another option, you guessed it, <em>GCD</em>. By far the fastest and safest option is using <em>GCD’s</em> <em>barrier</em> <em>blocks</em>. Instead of using a serial queue of operations like @<em>synchronized</em>, <em>GCD</em> uses a concurrent queue, and when asked to, performs <em>barrier blocks</em>. A <em>barrier block</em> is executed serially, other blocks have to wait. Here is a visual example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*f2oxEmhzEijgwhvIwbEO0w.jpeg" /><figcaption>Normal and barrier blocks being executed on a concurrent queue.</figcaption></figure><p>And here is an example of how to use barrier blocks in Objective-C code:</p><pre>_potatoQueue = dispatch_queue_create(&quot;com.declanmcpartlin.potatoqueue&quot;, DISPATCH_QUEUE_CONCURRENT);</pre><pre>- (id)getPotato {<br>    __block DSMPotato* localPotato;<br>    dispatch_sync(_potatoQueue, ^{<br>        localPotato = _potato;<br>    });<br>    return localPotato;<br>}</pre><pre>- (void)setPotato: (DSMPotato*)potato {<br>    dispatch_barrier_async(_potatoQueue, ^{<br>        _potato = potato;<br>    });<br>}</pre><p>As you can see in the example above, regular <em>blocks</em> are being used for simple <em>read</em> operations, but when it comes to operations like <em>write</em>, we make sure no other threads can access the value by setting the <em>block</em> as a <em>barrier block</em>. This makes use of concurrent queues whenever possible, but still keeping the solution thread safe.</p><p>So that’s enough for now, thanks for reading, here’s a potato.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*pWFO8jiTEOiLWlqNWwAauw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b73be35dccd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Objective-C - Part #1]]></title>
            <link>https://medium.com/@declanmcp/efficient-objective-c-part-1-562b4b860413?source=rss-ac75c6dc3afe------2</link>
            <guid isPermaLink="false">https://medium.com/p/562b4b860413</guid>
            <category><![CDATA[objective-c]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[naming]]></category>
            <dc:creator><![CDATA[Declan Stewart McPartlin]]></dc:creator>
            <pubDate>Wed, 05 Oct 2016 16:52:41 GMT</pubDate>
            <atom:updated>2016-10-05T16:52:41.994Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is for programmers that are familiar with Objective-C, but are still learning about the inner workings of the language.</p><p>Nowadays, when new iOS applications are being designed, Swift is the obvious choice in most cases. Swift is becoming only more powerful with every update, and largely promotes functional and value oriented programming, which usually ends in cleaner code compared to endless child classes and huge god classes (because programmers can be lazy).</p><p>But many projects were built before the creation of Swift and it would take a lot of effort and time to rewrite them into Swift. There are also some cases where it makes more sense to choose Objective-C over Swift, like projects that also use a lot of C++.</p><p>Even Objective-C has come a long way over the last decade, from the addition of GCD and blocks too. But for a beginner, Objective-C is a tough language to start with, even for seasoned programmers, it is a language that takes a long time to master.</p><p>Here I will list five tips and patterns I feel every professional programmer should know and use.</p><h4>Class Naming Conventions</h4><p>Unlike languages like Java that use namespaces, in Objective-C, class names are global, so we must be careful when it comes to naming our classes. If we name two classes the same (including classes coming from libraries and frameworks), chances are the application won’t link due to duplicate symbols. It gets even worse if libraries are loaded at runtime and has class names that clash with others.</p><p>To lower the chances of a potential class name clash, it is highly recommended you add a prefix to all your project class names. If you are using the cocoa framework, Apple has reserved the right to all two letter prefixes, so make sure your prefix is at least three letters. The same goes for global variables and methods (notice I have used DSM throughout my examples, if you work for <em>Universal Potato Tech</em>, UPT would be the logical choice).</p><p>When it comes to subclassing, make sure you stick to Objective-C naming conventions, including right-to-left readability. If you extend a UIView, add an explanation text about the specialization of the extended UIView class. Make sure your new class ends with View also. An example could be DSMPotatoView.</p><h4>Method Naming Conventions</h4><p>When naming methods there are a few things we have to be careful of. It is good practice to differentiate private methods from public ones. There are many ways in doing this, one is to add the <em>p_</em> (p for private) prefix (we go into more detail as to where to declare these private methods in the private methods section). This helps with debugging, visual readability and issues that can arise when changing the visibility of methods in a public API. Apple uses just an underscore, but for us to use the same could mean accidentally overriding methods in child classes that we didn’t know even existed, which can lead to bugs that are very hard to find, so don’t do it!</p><p>Do not be afraid of writing long method names as long as they are still concise and to the point. Objective-C has been said to be very verbose, but well chosen names for variables, methods and class names removes the need for comments, so do not shorten names just because they are ‘long’.</p><h4>Protocols</h4><p>Use protocols whenever a specific object is not needed, instead just a set of methods they must respond to. Try to steer clear from directly referencing other objects inside an object, especially when it is a non owning relationship. Types can be reduced to meerly an id that implements a protocol, as an example:</p><pre>id&lt;DSMSomeProtocol&gt; someObjectThatImplementsSomeProtocol;</pre><p>This helps to keep objects as decoupled as possible, keeping the project flexible and will eventually save you time when those inevitable changes come. This flexibility becomes even more pronounced when working on libraries and frameworks.</p><h4>Private methods and properties</h4><p>Declaring private methods and properties is simple in Objective-C when the class in question is not inherited by any child classes. But once you have child classes that must override private inherited methods, it gets a bit more complicated compared to other languages.</p><p>In Java for example, we can use the keyword <em>protected </em>to keep the variable visible only to child classes. In Objective-C though, it is common practice to create another header file that ends with _subclass.h and keep all ‘protected’ methods and properties there. This header must then only be imported by the base class and its child classes. Here is an example of a list of classes with such a subclass header used:</p><pre>DSMBaseObject.h<br>DSMBaseObject_subclass.h<br>DSMBaseObject.m<br>DSMChildObject.h<br>DSMChildObject.m</pre><p>In this project, only DSMBaseObject.m and DSMChildObject.m (along with any other classes that inherit from DSMObject) also import DSMBaseObject_subclass. Otherwise only DSMBaseObject.h is imported.</p><h4>Class Properties</h4><p>Instead of directly accessing attribute values of a class, Objective-C utilizes a feature called properties (the reason being compile time offsets, but we won’t get into that here). Here is a simple example of a class with two properties:</p><pre>@interface DSMShape : NSObject<br>@property NSString *area;<br>@property NSString *perimeter;<br>@end</pre><p>Not only does the compiler create getters and setters for you with properties, it also automatically transforms the dot syntax to calls to the accessors. That means these two calls are equal:</p><pre>square.side = 10; // this is transformed to:<br>[square setSide:10];</pre><p>But what if we don’t want our property to have a setter? What if it is not thread safe? What if we don’t want to keep a strong reference? Luckily, properties have a set of attributes that cover this:</p><ul><li><strong>nonatomic: </strong>Locks property values whilst being used. It is strongly recommended you use the <em>nonatomic </em>attribute at all times in iOS because of performance issues. Atomic by default.</li><li><strong>readwrite / readonly: </strong>Defines if a setter is generated as well or not. Readwrite by default.</li><li><strong>assign: </strong>For scalar types (CGFloat) an assign operation is executed.</li><li><strong>strong: </strong>Retains the set object value (the reference counter for the object goes up one).</li><li><strong>weak: </strong>It will not retain the set object value (and will also not release the old value). This is used in a non owning relationship.</li><li><strong>unsafe_unretained: </strong>Similar to weak, but the target is not nilled out when destroyed.</li><li><strong>copy: </strong>Similar to strong, but instead of retaining the object, it is copied.</li></ul><p>That’s enough for now, thanks for reading, here’s a potato!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*j888Bt4HA9W0AqisOF8CMA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=562b4b860413" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>