[swift-evolution] [Proposal] Factory Initializers
Benjamin Spratling
bspratling at mac.com
Thu Nov 17 17:52:31 CST 2016
Howdy,
Yes, I would like a feature like this. I’m working on a number of apps where I have a number of concrete types which conform to a protocol. Deserializing means picking one, and I’d love to be able to declare a protocol-scoped method which can pick between different subclasses. In some cases, I implement these as enums, but that unfortunately puts together a lot of code that I’d rather have apart.
My question is why bother writing “init” if I’ve already written “factory”? It isn’t really an initializing anything, it’s actually delegating. It really is just a static method, but a commonly-named and syntactically convenient way for someone to not know -or not need to know- that they are actually creating a subtype.
At that point, given that many of these are protocol-centric, what I want from a language standpoint is a way to define a protocol-scoped method. In contrast to a static method, which can only be called from a concrete type which conforms to the protocol, in initializing the correct sub-type, we do not yet know the correct sub-type.
For instance, consider a presentation app which contains an array of user “entries”, which can be text, images, whatever.
protocol PresentationEntry {
}
extension PresentationEntry
protocol func new(json:[String:Any])throws-> PresentationEntry {
//…
if whatever {
return TextEntry(…
else {
return ImageEntry(...
}
}
struct TextEntry : PresentationEntry {
}
struct ImageEntry : PresentationEntry {
}
class Presentation {
var entries:[PresentationEntry]
init(json:[String:Any])throws {
//…
self.entries = entriesJson.flatMap(){ (json)-> PresentationEntry? in
return try? PresentationEntry.new(json:json)
}
Right now, I think I’m stuck tacking the creation method on somewhere, like as an instance method on the Presentation type, as a global function, or creating a type to do nothing but be the factory.
At that point, the question revolves around extensibility. What if a sub-class adds another conforming type of concrete subclass? That’s what protocols and classes are for, after all! How do I modify the protocol’s protocol-scoped method to be overridden? Using custom factory types,
i.e.
protocol PresentationEntryFactory : class {
weak var presentationFactory: PresentationFactory? { get set }
func new(json:[String:Any], factory:PresentationEntryFactory)throws->PresentationEntry {
...
}
}
class GenericPresentationEntryFactory : PresentationEntryFactory {
func new(json:[String:Any])throws->PresentationEntry {
if whatever {
return TextEntry(json:…, factory:Self)
else {
return ImageEntry(json:…, factory:Self)
}
...
}
I don’t have that problem. I just create my own factory type, using exactly the same interface:
struct SongEntry : PresentationEntry {
...
}
class SongCapablePresentationEntryFactory : PresentationEntryFactory {
func new(json:[String:Any])throw->PresentationEntry {
if whatever {
return TextEntry(json:…, factory:self)
else if whenever {
return ImageEntry(json:…, factory:self)
else {
return SongEntry(json:…, factory:self)
}
}
And now Presentation just gets its “entryFactory” from its factory and creates the entries.
Or perhaps the PresentationFactory creates the entries before it even creates the presentation and there never was a init(json:… method on the Presentation in the first place. But I get that one goal is to avoid the need to create all these additional factory classes. A lot of developers would prefer to simply use an init( and never write them out.
So that’s a ‘general’ way to solve the problem now. I’m not 100% sure that we have to have extensibility of these factory or protocol-scoped methods to proceed, but it would be nice to see what could happen with extensiblility with some more minds checking on this list. Maybe a type “registration” method? We could create a “factory register” keyword which tells the compiler to place the given type in a special run-time accessible location including a reference to the concrete type and a validation function. Unfortunately, the validation function may need to be custom not only by protocol, but also by starting data. Consider a type which can be initialized from NSCoder, JSON, NSManagedObject and also from a CKRecord (I have that in several apps). How many factories do we have for a type? How do we distinguish them? Argument labels and types? How many validation methods need to be specified? Obviously, it would be nice to have the compiler check for our errors in that.
Not using a specific “factory” keyword method, but adding “protocol”-scoped stored properties allows me to specify a different factory closure:
extension PresentationEntry {
protocol var jsonEntryFactory:(json:[String:Any])throws->Self
Then my second app, which supports more Entry types, but embeds the original module, could simply
PresentationEntry.jsonEntryFactory = { (…)->PresentationEntry in
if whatever {
return TextEntry(json:…, factory:self)
else if whenever {
return ImageEntry(json:…, factory:self)
else {
return SongEntry(json:…, factory:self)
But it doesn’t answer the question of “when” do we set this value. Do I just do it “early”? and hope I don’t end up writing yet another inheriting module?
CoreImage really wants to work that way, with the init(name:… pattern. On the other hand, I can’t tell you whether the CoreImage team is happy with that API, but I can tell you I’m not. I want @availability attributes on concrete types, so I know the type doesn’t work before I build an entire app built on using the variable blur filter and then realize that I misread the docs. So, how would @availability play into factory type registrations?
But, I feel like this need kind of starts to spider out into a ton of considerations to really get us what we can use.
+1 for factory keyword
-1 for still needing to type “init”
+1 for protocol-scoped members without needing a conforming concrete type
-1 for consideration of extensibility of factories.
+1 for directly representing the as-designed initialization patterns of several popular modules
-1 for such long tendrils
-Ben Spratling
> On Nov 17, 2016, at 4:23 PM, Charles Srstka via swift-evolution <swift-evolution at swift.org> wrote:
>
> Is there any chance of reviving this? It seems to me that since this would require Swift initializers to be implemented internally in such a way that they can return a value (as Objective-C init methods do), it may affect ABI stability and thus may be germane to the current stage of Swift 4 development.
>
> Charles
>
>> On Dec 17, 2015, at 3:41 PM, Riley Testut via swift-evolution <swift-evolution at swift.org> wrote:
>>
>> Recently, I proposed the idea of adding the ability to implement the "class cluster" pattern from Cocoa (Touch) in Swift. However, as we discussed it and came up with different approaches, it evolved into a functionality that I believe is far more beneficial to Swift, and subsequently should be the focus of its own proposal. So here is the improved (pre-)proposal:
>>
>> # Factory Initializers
>>
>> The "factory" pattern is common in many languages, including Objective-C. Essentially, instead of initializing a type directly, a method is called that returns an instance of the appropriate type determined by the input parameters. Functionally this works well, but ultimately it forces the client of the API to remember to call the factory method instead, rather than the type's initializer. This might seem like a minor gripe, but given that we want Swift to be as approachable as possible to new developers, I think we can do better in this regard.
>>
>> Rather than have a separate factory method, I propose we build the factory pattern right into Swift, by way of specialized “factory initializers”. The exact syntax was proposed by Philippe Hausler from the previous thread, and I think it is an excellent solution:
>>
>> class AbstractBase {
>> public factory init(type: InformationToSwitchOn) {
>> return ConcreteImplementation(type)
>> }
>> }
>>
>> class ConcreteImplementation : AbstractBase {
>>
>> }
>>
>> Why exactly would this be useful in practice? In my own development, I’ve come across a few places where this would especially be relevant:
>>
>> ## Class Cluster/Abstract Classes
>> This was the reasoning behind the original proposal, and I still think it would be a very valid use case. The public superclass would declare all the public methods, and could delegate off the specific implementations to the private subclasses. Alternatively, this method could be used as an easy way to handle backwards-compatibility: rather than litter the code with branches depending on the OS version, simply return the OS-appropriate subclass from the factory initializer. Very useful.
>>
>> ## Protocol Initializers
>> Proposed by Brent Royal-Gordon, we could use factory initializers with protocol extensions to return the appropriate instance conforming to a protocol for the given needs. Similar to the class cluster/abstract class method, but can work with structs too. This would be closer to the factory method pattern, since you don’t need to know exactly what type is returned, just the protocol it conforms to.
>>
>> ## Initializing Storyboard-backed View Controller
>> This is more specific to Apple Frameworks, but having factory initializers could definitely help here. Currently, view controllers associated with a storyboard must be initialized from the client through a factory method on the storyboard instance (storyboard. instantiateViewControllerWithIdentifier()). This works when the entire flow of the app is storyboard based, but when a single storyboard is used to configure a one-off view controller, having to initialize through the storyboard is essentially use of private implementation details; it shouldn’t matter whether the VC was designed in code or storyboards, ultimately a single initializer should “do the right thing” (just as it does when using XIBs directly). A factory initializer for a View Controller subclass could handle the loading of the storyboard and returning the appropriate view controller.
>>
>> Here are some comments from the previous thread that I believe are still relevant:
>>
>>
>>> On Dec 9, 2015, at 1:06 PM, Philippe Hausler <phausler at apple.com> wrote:
>>>
>>> I can definitely attest that in implementing Foundation we could have much more idiomatic swift and much more similar behavior to the way Foundation on Darwin actually works if we had factory initializers.
>>
>>
>>> On Dec 7, 2015, at 5:24 PM, Brent Royal-Gordon <brent at architechies.com> wrote:
>>>
>>> A `protocol init` in a protocol extension creates an initializer which is *not* applied to types conforming to the protocol. Instead, it is actually an initializer on the protocol itself. `self` is the protocol metatype, not an instance of anything. The provided implementation should `return` an instance conforming to (and implicitly casted to) the protocol. Just like any other initializer, a `protocol init` can be failable or throwing.
>>>
>>> Unlike other initializers, Swift usually won’t be able to tell at compile time which concrete type will be returned by a protocol init(), reducing opportunities to statically bind methods and perform other optimization tricks. Frankly, though, that’s just the cost of doing business. If you want to select a type dynamically, you’re going to lose the ability to aggressively optimize calls to the resulting instance.
>>>
>>
>>
>> I’d love to hear everyone’s thoughts on this!
>>
>> Best,
>> Riley Testut
>> _______________________________________________
>> swift-evolution mailing list
>> swift-evolution at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
More information about the swift-evolution
mailing list