My little trick to avoid duplicate code for inherited initializers
Duplicate code is annoying
From time to time, I got into a situation that I need to override initializers, inherited from a superclass, for my own class. For instance:
In this particular case, you would need to initialize the value of myProperty
in init(nibName:bundle:)
and required init?(coder:)
. However, there are a few drawbacks.
You would have to change all of the initializers when you change lately the logic of the initialization. Inconsistent changes, such as typo, may cause unexpected behaviors or results. Moreover, it may be error-prone when the code is part of a project you collaborate with others. People may not notice that there is more than one initializer. This is especially true when they are spread all around the file instead of gathering at the same spot.
Okay. Then what’s next?
Here is my trick:
The key points of the trick are:
- Make the inherited initializers be
convenience
ones. - Use
enum
with associated values as a way to direct to the corresponding initializer of the superclass. - Make your own private initializer (in this case,
private init(_:)
) and put the initialization logic of your class in it, along with the invocation of the corresponding initializer of the superclass.
Some of you may notice that to do the trick, you need more lines of code. It really depends on the context you’re in. However, if avoiding duplicate makes a great sense for the constructors of your class, then the additional lines of code could be a worthy investment.
Happy coding, and cheers!