Weekend Reading for August 19, 2016

Weekend Reading for August 19, 2016, click here

Happy Friday fellow Clean Swifters. Who’s watching the Olympics? There’s something that professional software engineering has in common with professional sports: practice makes perfect.

How do you practice your craft?

Reading is a big part of how I stay up to date, and I use the weekends as catch up time. Here’s what I’ll be reading this weekend.

Get “Weekend Reading” delivered in your email, as well as every other cleanswifter.com post, and receive a free screencast on iOS automated testing by signing up here. “Weekend Reading” is created through AWeber’s app, Curate, which I helped create and is entirely written in Swift.

Happy cleaning

Swift API Design Guidelines: Highlights

The Swift API Design Guidelines could be one of the most important things I’ve found towards writing cleaner Swift code. Have you seen them yet? I hadn’t actually looked at them until I watched the WWDC video, “Swift API Design Guidelines.”. When chatting with a coworker about which WWDC video to watch during some downtime, I’ll admit that this video didn’t really catch my eye. As someone who doesn’t really write much “framework” type code for other people to consume besides those I directly work with, I didn’t immediately relate to the description for the video:

Swift 3 introduces new API Design Guidelines specifically crafted to the unique character of Swift for clear, concise code. This talk will explore the philosophy behind the Swift API Design Guidelines and their application throughout the Swift Standard Library and the Cocoa and Cocoa Touch APIs. See how this API transformation will affect your Swift code and learn how to ensure a smooth transition to Swift 3. Learn how Swift 3 imports Objective-C APIs and how to expose rich Swift interfaces for existing Objective-C libraries.

Well having watched the video, and then read through the actual design guidelines on Swift.org, I’m bought in, and recommend you take a look as well.

The Swift API Design Guidelines is like an instruction manual for how to craft the “words” in your code: how you name variables, parameters, method names. It tells you how to interweave the words in your code with the surrounding documentation. By becoming familiar with the Swift API Design Guidelines, you’ll both write code that is consistent with the community, and the APIs that are being created within the frameworks right out of Apple and the Swift team. It’s a win/win proposition.

Here are the highlights of the Swift API Design Guidelines for me:

The “ed/ing” rule

The presenter in the WWDC video summed this rule up as the “ed/ing” rule (that makes it easy for me to remember). In the Swift.org documentation, it’s referred to as Name functions and methods according to their side-effects in the Strive for Fluent Usage section. The guideline suggests that often, “A mutating method will often have a nonmutating variant with similar semantics, but that returns a new value rather than updating an instance in-place.” According to the ed/ing rule, append ed or ing to the nonmutating version. For example:

Mutating

x.sort()
x.append(y)

Nonmutating

z = x.sorted()
z = x.appending(y)

Omit Needless Words

Boy, if there’s one bad habit that is leftover from Objective-C is really wordy method names, particularly be repeating words. For example, just look at the NSMutableArray Objective-C class documentation and take a peak at how many times the word “object” appears. Methods like this are all over the Objective-C Foundation API:

- (void)addObject:(ObjectType)anObject;
- (void)removeObject:(ObjectType)anObject;

Just look at how many times the word “object” appears in the class documentation for NSMutableArray. As a result, this verbosity made its way into the code that I wrote as well.

Well this is a no no in Swift. The Swift creators are striving for a balance of conciseness AND clarity.

Although Swift code can be compact, it is a non-goal to enable the smallest possible code with the fewest characters. Brevity in Swift code, where it occurs, is a side-effect of the strong type system…

The last part of this section is relevant. It’s the strong type system that allows for the NSMutableArray API to be redesigned as:

func add(_ anObject: AnyObject)
func remove(_ anObject: AnyObject)

Notice how the word “Object” was removed from the method name itself? That’s exactly what is meant as a “needless word” in the guideline “Omit Needless Words.” This is because consumers of this API can rely on the strong type system of Swift to only pass objects to the method that are of the defined type of the parameter. This is just one example where Swift API Design Guideliness lead us to more concise code through omitting needless words. Now that you’re aware of it, you’ll start to see this all over and should even apply it to your own API design.

Also, be sure to check out the sections in the Swift API Design Guidelines for Name variables, parameters, and associated types according to their roles and Compensate for weak type information. Detailed examples are not included here, but those guidelines provide good companion structure how to achieve clarity while also ommitting needless words. Remember, don’t strive for brevity over clarity. Just like the WWDC presenter mentioned, you don’t want to have to constantly be switching to the API docs because the API is so terse.

Grammatical English Phrases

Method and function names should read like grammatical English phrases. I really like this one, and I feel like this is one good habit I’ve carried from my dark days as a Java programmer. This is also covered in the String for Fluent Usage section of the Swift API Design Guidelines. A good sanity check for your method and parameter names is to read the line of code aloud and ask yourself, “Is this grammatically correct English? Is this how I would conversationally say it?” If yes, then you probably are on to a good API design. If not, you should probably reconsider it. Examples right from Swift.org of good API design that grammatically makes sense:

x.insert(y, at: z)          // “x, insert y at z”
x.subViews(havingColor: y)  // “x's subviews having color y”
x.capitalizingNouns()       // “x, capitalizing nouns”

Bad design that doesn’t read aloud well:

x.insert(y, position: z)
x.subViews(color: y)
x.nounCapitalize()

Other Random Cool Stuff

Documentation

In the handful of programming languages that I’ve professionally written, I’ve never come across such a succinct yet well defined set of guidelines for writing code documentation. It’s right at the top of the Fundamentals section of the Swift API Design Guidelines. There are short and sweet points to consider when writing documentation for your Swift code, and also how to make your comments compatible with how Xcode might represent them in generated documentation.

Conventions

The Conventions section is really cool too. There are a lot of one-off suggestions to help clarify everything from when to document Big-Oh efficiency, to how to capitalize your variable and method names.

Wrap Up

I can’t urge you strongly enough to check out the Swift API Design Guidelines on Swift.org. I can tell you that in my opinion it is one actionable thing that you can do to improve your Swift code, today. It’s simple, clear, and instructional manner makes it really easy to understand. Your code will be more consistent with itself, and code written elsewhere in the community. Who wouldn’t want that?

Happy cleaning.

Split Temporary Variable in Swift

In “Refactoring, Improving the Design of Existing Code” by Martin Fowler, he presents the Split Temporary Variable refactoring.

Here’s a video walkthrough of the Split Temporary Variable refactoring in Swift and when you might want to use it:

Video Transcript:

Hey what’s up everybody, it’s Andy from cleanswifter.com and I’m here to show you another refactoring from Martin Fowler’s book, “Refactoring, Improving the Design of Existing Code.” This week, in Swift 3, I’m going to show you how to do Martin Fowler’s refactoring “Split Temporary Variable.” This refactoring fixes a bad habit of mine that goes all the way back to my first couple classes in computer science. Specifically, this bad habit is when you create a temporary variable that you then reuse and reuse throughout a method for multiple purposes. This is bad because these variables are very poorly named and as a result, it’s really hard to figure out what they do. A general best practice is to only create a variable that will be used for a specific purpose. If you have to then create another temporary variable for a different purpose, do that rather than reuse the original. In order to do this, we’re basically going to look for cases where a temporary variable is used, and assigned to multiple times and then investigate whether that is a good candidate to be split into multiple temporary variables. Let’s take a look at some code.

Here’s a view controller in which there are a couple properties: two strings which represent first and last name, a name label, a welcome label, and a computed property which represents the person’s full name (which is their first name combined with their last name, separated by a space). Down here in viewDidLoad(), this is where things get a little ugly. First, there’s a variable named i. Who knows what i even means? And i gets assigned a string “My first name is” with the firstName value. i is assigned to nameLabels text. Later, i is also assigned a new value which is “Welcome” with the value of fullName. That new value is then assigned to the welcomeLabels text. I can see what’s going on here. It’s that two strings are being created and ultimately set on the labels, but I have no idea why this variable is named i, or why it’s being reused. The first way that you can get the compiler to be able to help you fix this, is simply change the definition of i from a var to a let. Let me show you that, in Swift, the compiler will alert you to any variables that are defined and only assigned to once. The compiler is telling us here that i was never mutated so consider changing it to a let which actually makes it a constant. I could do this. In this case where the compiler is detecting that it is only assigned to once, I can automatically use the IDE to fix it. But let’s go back to the original code. The compiler is not going to identify that as something to be changed because it’s assigned to twice despite this very poorly named variable i. So what I’m going to do here is change this to let and what that’s going to do is enable the compiler to show me all other places that i is assigned to. Those assignments are what I’m going to target for splitting out into their own thing. I’ve already made the decision that i is being inappropriately reused in was that don’t make sense. Once this is switched to a let I see the compiler gives me an error with a suggested fix. Xcode tells me to consider changing the definition of i from let to var to make it mutable. Yes. That would make this compile, that’s not what I want to do because that’s the opposite way of this refactoring. Instead, what I should do here, is actually create a new variable, and for now we’ll just call it n, and now there are two temp variables here. I need to actually use n in the new place where it should be read. Already this is an improvement because I’m using two temp variables and there’s no chance of collision between the two, and it’s a step towards making this even better. The final step in this refactoring is to actually come up with good names for the temporary variables. Let’s call these firstNameString and for the other one we’ll call it welcomeMessageString. Now be sure to take the new variable names and use them in the right place. Now you see the result of the refactoring. You can see where we started with one single temporary variable that was being reused and very poorly named such that the code was not very readable where now I have two temporary variables, both well named, and used in this resulting way.

There you have it, that’s the Split Temporary Variable refactoring from Martin Fowler’s book, “Refactoring, Improving the Design of Existing Code.” You can buy the book in the Amazon Affiliate link in the description for this video. I hope to see you next time for another refactoring, and in the meantime,

Happy cleaning.

Weekend Reading for August 12, 2016

Weekend Reading for August 12, 2016, click here

Happy Friday fellow Clean Swifters. I’m heading up to the Poconos in Pennsylvania this weekend looking forward to some much needed downtime. That doesn’t mean I haven’t loaded up my Instapaper queue! Here’s what I’ll be reading.

Get “Weekend Reading” delivered in your email, as well as every other cleanswifter.com post, and receive a free screencast on iOS automated testing by signing up here. “Weekend Reading” is created through AWeber’s app, Curate, which I helped create and is entirely written in Swift.

Happy cleaning

Introduce Explaining Variable in Swift

In “Refactoring, Improving the Design of Existing Code” by Martin Fowler, he presents the Introduce Explaining Variable refactoring.

Here’s a video walkthrough of the Introduce Explaining Variable refactoring in Swift and when you might want to use it:

Video Transcript:

Hey, what’s up everybody, it’s Andy the clean swifter, and I’m back to show you another refactoring from Martin Fowler’s book, “Refactoring, Improving the Design of Existing Code.” This week, I’m going to show you in Swift I’m going to show you the refactoring “Introduce Explaining Variable.” This refactoring can be used as an alternative to Extract Method when you have a complex piece of code that you want to simplify. The way that you’re going to simplify it is to create a new temporary variable that is well named and can be used to break up some complicated logic. Imagine sometimes you’ll be creating a complicated if statement to represent some conditional code, where there’s a lot of different things you need to check. All of a sudden you end up with several different and clauses, a couple different ors, and some parens grouping them, and before you know it, you’ve created a piece of very hard to read code. That’s bad because it’s a way to introduce bugs. It’s easy to accidentally change the logic of that statement such that you create a bug. Temporary variables can be used to break it up. You’ll take a piece of that if statement, that conditional cause, extract it into a temporary variable that is well named, and then reference that temporary variable in the conditional clause to then help explain it to the reader. You might instead use extract method to put it into a brand new, well named, method that returns a boolean that also helps explain its purpose to the reader, but in the case that you don’t want to do that, sometimes it may not be worth a method of its own, you can use this to introduce a variable to help explain the complicated conditional code. Let’s take a look at Introduce Explaining Variable:

Here’s a view controller similar to last week, where in this view controller there are two strings that represent a first and last name, a label that will be set with the name, and then also a welcome label which will give a customized welcome message based on something about the name. Down here in viewDidLoad() we’re going to set the nameLabel to be the fullName but now here we’re going to do some conditional logic to set the welcomeLabel based on the person’s name. Right off the bat, I’m trying to read this code and I come across this if statement and I see there are at least four different things being checked in order to determine how the welcomeLabel will be set. This to me isn’t very readable. We can use this refactoring to help improve the readability of this code. In order to use the refactoring, Introduce Explaining Variable, what I’m going to do is that I first need to understand what the condition is checking, and then I’m going to find a way to break it apart. Looking at this, it’s checking if the firstName starts with “A” and the lastName starts with “A” and the firstName ends with “A” and the lastName ends with “A” the welcomeLabel is set with a message that indicates they have a lot of “A”s in their name because just like my name “Andy”, “A” is the best letter in the alphabet. What’s the explaining variable I’m going to introduce? Well I could create two variables to each represent whether each name starts and ends with “A”, or a variable to represent whether both names start with “A” and another to represent that both end with “A”. For instance, let firstNameStartsAndEndsWithA, and to set that, I’m going to take this code right here, cut it out, and paste it in there. So that boolean represents the fact that firstName may or may not start and end with the letter “A”. And now I’m going to do the same thing for lastName. Now update the original if statement to represent the original behavior, and you should have unit tests to actually verify this, but it’s not a requirement. Now reading through this updated code, it is easily read aloud. I can look at the if statement alone, skipping over the variable definition, and understand the logic the if statement is checking. Well named temporary variables go a long way to give you quick readability of a complicated if statement. Now I can read this and understand if the first name starts and ends with “A”, and the last name starts and ends with “A”, I give a specific welcome message that they have a lot of “A”s in their name, otherwise their name is boring. Fowler does describe you could take this even further, and instead extract both of these new temps into their own method which might be called “lots of As in name” and then call that method from the if statement. It’s just one alternative. In this case, I choose that using temporary variables is appropriate, and leave it at this.

There you have it, that’s the Introduce Explaining Variable refactoring and it’s a way that you’re going to reduce the complexity of code specifically often times in complicated conditional clauses by introducing temporary variables. I hope you liked this refactoring, Introduce Explaining Variable from Martin Fowler’s book, “Refactoring, Improving the Design of Existing Code.” You can buy the book through my Amazon Affiliate link in the description for this video. I’ll see you next time.

Happy cleaning.

Weekend Reading for August 5, 2016

Weekend Reading for August 5, 2016, click here

Happy Weekend fellow Clean Swifters. Aside from checking out this year’s incredible Perseid meteor shower , I found some good reading.

Get “Weekend Reading” delivered in your email, as well as every other cleanswifter.com post, and receive a free screencast on iOS automated testing by signing up here. “Weekend Reading” is created through AWeber’s app, Curate, which I helped create and is entirely written in Swift.

Happy cleaning

XCTest Target Membership Rule #1

I just had to learn a lesson the hard way, and wanted to pass on to you what I’m going to call the XCTest Target Membership Rule. It took some head banging of mine to discover this rule, and I don’t want you to go through the same pain.

The XCTest Target Membership Rule

The actual implementation files for your app should not be included with the Target Membership for your XCTest target.

xctest target membership

If you were to check the box next to TestStaticTests you would start to see this error in the Console when running your tests:

objc[14049]: Class ViewController is implemented in both <path cut>/TestStatic.app/TestStatic and <path cut>/TestStaticTests.xctest/TestStaticTests. One of the two will be used. Which one is undefined. 

The runtime for XCTest is telling you that it has found the same class defined in two places, the two targets for which you specified the file should be included. And furthermore, you’re also being told that the behavior with regard to which implementation is used will be “undefined.” The funny thing was, I actually found this error message to be misleading. I found that in practice, both copies of the implementation are actually used if you can believe that!

Here’s an in-depth question I posted on StackOverflow documenting the odd behavior I noticed, and included a sample project demonstrating it as well.

Background

These past few weeks I’ve been working on an older project, specifically AWeber Stats. If you notice, that app hasn’t been updated since April 2015, that’s a while. As a result a lot of the dependencies were out of date, so one thing the team set out to do was update the dependencies, and CocoaPods seemed like a good place to start. We were previously on version 0.34.1 and planned to update to 1.0.1 (which at the time of this writing is the latest version). We use Ruby Gems to manage the dependency versions for CocoaPods specifically. This allows us to have per-project control of which version of CocoaPods end up being used. This gives us the reassurance that we must explicitly designate the desire to update a given project’s CocoaPod’s version, and thus accordingly test and verify the update.

I move forward with the update, bumping the version of CocoaPods to 1.0.1 as defined in our Gemfile. CocoaPods 1.0 actually defines a new schema for Podfiles so I subsequently migrated the Podfile to the new format, and successfully ran pod install. Everything has gone smoothly up to this point. Then I opened my Xcode workspace and attempt to run our test suite.

100s of failures.

In addition to the failures, I saw many instances of that Console warning from earlier:

...One of the two will be used. Which one is undefined.

Now the thing is, remember, at this point I hadn’t yet discovered the XCTest Target Membership Rule. And as it turns out, nearly every implementation file in the project for the app target, also existed in membership for the test target. And in fact, as I dusted the cobwebs off of my mind, and thought back to the original work on the project, I specifically remember needing to designate those implementation files as having membership in the test target. Specifically, it was errors like this that would appear of the class under test was not part of the test target:

Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_MyArrayController", referenced from:
      objc-class-ref in MyArrayControllerTests.o

So where did the need to include that file with the test target go? Why was Xcode now telling me that I shouldn’t include these files with both targets?

Well I never got to the bottom of it. I have two guesses at this point: something either in Xcode, or in CocoaPods changed to modify the behavior how XCTest integrates with the classes under test.

Closing Thoughts

I’m still digging to get to the bottom of this. In the meantime, I will not forget the XCTest Target Membership Rule. A couple other lessons surfaced:

  1. Don’t wait to keep your project up to date – It’s easy to launch an app on the store, or hand it off to a client, and semi-forget about it. The app is live, attracting customers, and functioning well. Just remember, at some point it will either need to be updated or die. And the longer you wait, the harder it will be to bring it up to contemporary standards. It’s much easier to make more frequent small changes, than wait 15 months, return to an unfamiliar code base, and try to bring it up to speed.
  2. Know your tool chain – I’m still not fully aware of what changed between the last app update and today such that such a fundamental piece of project functionality changed. I’m taking this as a kick in the butt to get my head wrapped around third party dependencies being used. And if you can’t do that (for whatever reason – time, complexity, interest, etc.), don’t use them. There are plenty of ways to manually install third party code, or even write it from scratch. Of course other people have already invented the wheel, just don’t blindly use the tools without a foundational understanding of how to troubleshoot them when they go wrong.

Happy cleaning.

Replace Temp With Query In Swift

In “Refactoring, Improving the Design of Existing Code” by Martin Fowler, he presents the Replace Temp With Query refactoring.

Here’s a video walkthrough of the Replace Temp With Query refactoring in Swift and when you might want to use it:

Video Transcription

Hey, what’s up everybody, it’s Andy from cleanswifter.com, and I’m back this week to show you another refactoring from Martin Fowler’s book, “Refactoring, Improving the Design of Existing Code.” This week we’re going to take a look at the refactoring called, Replace Temp With Query. Replace Temp With Query is a refactoring that’s a lot like Extract Method, but there’s one difference, it’s a little more specific. With Replace Temp With Query, we’re going to specifically target temporary variables within our code, and extract them into reusable pieces of code. For example, often times within your code you may create a temporary variable that’s then assigned a value based the result of some computation and then reused elsewhere in your code, especially if that value is reused in several different places. The benefit of using Replace Temp With Query is that by replacing the temp with a query, which is then going to be reusable code, you provide a much bigger availability of where that code can be reused from. Additionally, by removing the code that assigns the value to the temp, it will also consolidate the code where the temporary variable is used. Often, temporary variables lead to methods that are longer than they should be. They decrease the readability of code because you then have temporary variables that you have to read and understand where and how that variable is computed.

Let’s take a look at this refactoring in Swift for how we’re going to replace a temp with a query. Here’s a view controller that has three properties on it, two strings which represent a first and last name, and a label that’s going to be set with a name. Here in viewDidLoad() were actually going to compute a full name which represents a first name, a space, and the last name, then store that in a temporary variable called fullName and then set it as the text on the label. The first thing that should jump out at you here is the use of var to define fullName. General Swift best practice is that if a variable is created and only ever assigned to once, it should be defined as let and in fact the compiler actually tells us that here. “Variable was never mutated, please change it to a let.” And the IDE will even help you do that. This plays right into the refactoring, Replace Temp With Query, because by changing this to a let we have the confidence that this variable is never changed anywhere else after it is first assigned. This means fullName always represents this computed value. That sets us up well to do the refactoring. In Martin Fowler’s book, he actually advocates that as part of the refactoring you create a new method to contain the computation for the result. Now I think something a little more Swift like is that we can use computed properties here to actually return this value. The goal of this refactoring is that I want to delete this line of code. To do that, I’m going to create a computed property, fullName. And that’s going to have a getter on it which simply returns this value. Now that I’ve moved where the computation happens, I can continue on my mission to delete the temporary variable’s creation, and then reuse the computed value from the property. You can see a line of code was deleted from viewDidLoad(), no need to look at a temporary variable, and additionally we now have this piece of reusable code where we can access a full name from anywhere else in our code. Now in the case that it’s not so straightforward to use a computed property, you can actually create a method that returns a String (in this case full name) but I think in this case this is a good solution.

There you have it. That’s Replace Temp With Query in Swift. Again, the benefits are that you now have a reusable piece of code which represents that computed value. And additionally, you can delete the temp from the method where it’s being called from, thus consolidating the method and improving the overall readability. I hope you liked this video on this refactoring, Replace Temp With Query from Martin Fowler’s book, “Refactoring, Improving the Design of Existing Code.” You can buy the book through my Amazon Affiliate link in the description for this video. See you next time, and happy cleaning.

Weekend Reading for July 29, 2016

Weekend Reading for July 29, 2016, click here

Happy Weekend fellow Clean Swifters. I was on vacation last week in Sea Isle City, New Jersey. You might know it as “the Jersey shore.” The downtime at the beach felt great and now I’m back at it this week, recharged and refreshed. Here’s what I’ll be catching up on this coming weekend.

Get “Weekend Reading” delivered in your email, as well as every other cleanswifter.com post, and receive a free screencast on iOS automated testing by signing up here. “Weekend Reading” is created through AWeber’s app, Curate, which I helped create and is entirely written in Swift.

Happy cleaning

Final By Default, Yes Please

Two worlds collided for me this week. There has been a ton of Internet chatter about Swift proposal SE-0117. Officially it’s titled “Allow distinguishing between public access and public overridability” but a lot of people are simply summing it up as changing classes and their members to be final by default. This is the opposite of Swift 1, 2, and 3, as well as Objective-C and Java. Just as I was trying to keep up with the Internet discussion about this proposal, I came across Charles Scalfani’s article on Medium “Goodbye, Object Oriented Programming.” I could relate to every single point he made in that article, the first of which is that the biggest advertised benefit of object oriented programming, inheritance, is also its biggest shortcoming. After having professionally written object orient code for over 10 years, I absolutely agree. The thing is, object oriented programming is part of me.

Why Is Inheritance Bad?

In object oriented programming, inheritance is one of the fundamental principles that define the programming model. With inheritance, you can define one object to “inherit” from another object. This means that the child object has all the behavior of the parent object, as well as any new behavior it defines. It can also override behavior from the parent class when needed or desired. In his article, Charles Scalfani both gives a great description as to what inheritance is, with simple code examples as well. Take a look if you’re unfamiliar with inheritance. He also gives a perspective on why inheritance bad that I totally relate to. In my own mind, the most dominant piece of resentment against inheritance is the tight coupling that is created between parent and child class. The thing is, it’s so easy to think about classes in terms of inheritance. It’s so easy to understand that a square is also a rectangle, or that a dog is an animal. My mind naturally thinks like this. And back to the foundations of my programming education with C++, I was taught to think in terms of object oriented principles, and this means to look out for relationships between “things” that can relate to each other with “is a” relationships.

Often it’s easy to initially construct a design that appears to creatively leverage inheritance to remove redundant code and take advantage of that “is a” relationship. The thing is, as you maintain your code, make enhancements in response to new end user features, perform refactorings to clean up other pieces of code, you’ll quickly find the need to change either the parent and/or child classes in the inheritance relationship. This is where you will run into trouble. It will not be clear how changes to the parent class may affect the child class. On the flip side, it will not be clear how changes to the child class may violate assumptions made in the parent class. And in some cases, desired changes simply won’t be possible as it would break the “is a” relationship that inheritance brings.

Why Will Final By Default Be Better?

Not only is it easy to simply think in terms of inheritance when mapping out objects in your object oriented system, but both the languages and frameworks we use make it so easy to continue applying this anti-pattern. (Yes, I just went there. Okay, well not necessarily an anti-pattern, but a sledgehammer for all nails, even tiny finishing nails. Get it? Just because you have a tool doesn’t mean it’s appropriate for all jobs.) I’m not going to accuse all code authors as having not thought through the ramifications of inheritance, but think about it for a minute from the perspective of any class you might write. Is thinking about use of a final keyword in the forefront of your mind to apply to the class or its members in order to prevent subclassing in times you don’t intend for it? I know in my experience, both in code I’ve written, as well as classes I’ve collaborated with others on, we almost never discuss whether it might be appropriate for others to subclass the given class, in order to correctly designate constructs as final. The conversation simply doesn’t happen, and thus the object is left open to be subclassed, either by us later on, or future team members, or in the case of open source code, or frameworks distributed to others, those consumers of the code.

The fact of the matter is, since this consideration hasn’t happened, there’s no guarantees that the class will work at all as a super class. What about as a super super class? Or a super super super class? Inappropriate subclassing could happen, totally be accident, and fast forward 1000 lines of code later, and you’re stuck with this incredibly tightly wound nest of coupled spaghetti code. Composition over inheritance is nothing new. By changing the fundamentals of Swift such that classes and their members will be final by default will go a long way to prevent accidental subclassing. This decision in the language will facilitate forethought at system design time to think and ponder the question, “Is there any reason for this class to be subclassed?” And only if the answer is yes, may you then use the proposed declaration modifier open indicating that the class or class member may be overriden.

To The Future, and Beyond

Honestly, it’s a struggle to continue to wrestle my mind away from object oriented programming techniques. Like I already wrote, these are fundamentals driven into my brain since adolescence. Not only that, but it’s also very naturally to look for patterns between “things” in the manner that inheritance conveys, and then program them that way. The thing is, as easy as this is to do, I’ve also seen how ugly it can get. And just like Charles Scalfani proposes, it’s a false premise to think that inheritance leads to maintainable code. What side of the fence are you on with this debate?

Happy cleaning.

As a bonus, if you’ve gotten this far, I’m reminded of a cheesy programmer joke:

What’s the object oriented way to get rich?

Inheritance