[swift-evolution] [Proposal Draft] Flexible memberwise initialization

Matthew Johnson matthew at anandabits.com
Fri Jan 1 10:11:41 CST 2016


> On Jan 1, 2016, at 6:57 AM, Tino Heth <2th at gmx.de> wrote:
> 
>>> I deny that, and even if it is true, there is a price to pay — and that is more than the lines of code that are required…
>> 
>> Personally, I think it is a lot more readable to put members separate lines, but if you don’t like doing that:
> You are focusing on the least important thing here — I basically meant to say that the lower line count is no real benefit, but that there are advantages that aren't as easy to spot.

What are those advantages precisely?  

> 
>>>> 1. It interacts well with access control
>>> Better than Kotlin? Please prove this.
>> 
>> Please look at the examples I have in the Access Control section of the proposal.  I spent some time reading the Kotlin docs and it isn’t clear to me that Kotlin can do this.  But maybe it can.  I don’t know Kotlin well.  It sounds like you do, so if it can, please show how this is done in Kotlin.
> I actually don't know Kotlin that well — and that contributes to my evaluation of their solution: It is intuitive, and I did not have to read a huge article to understand it.
> What I can see in your example is that the proposed syntax allows me to trigger compiler errors that will never happen with Kotlin (and errors that cannot happen are the ones I like the most).

Can you point out what potential compiler errors you are concerned about?  Are you referring to the access control example where the compiler does not synthesize initialization of a private member in an internal memberwise initializer and thus requires manual initialization of the private member?

> 
>>>> 2. Partial memberwise initialization is possible
>>> The same with Kotlin — and imho at least as easy
>> 
>> That isn’t clear from the Kotlin docs.  It may well be that they are just missing examples.  Please post some samples showing how this is handled.
> see below; of course, the sample won't use memberwise initialization, but archive the same in a (imho) better way
> 
>>>> 3. It allows memberwise initializers to accept non-memberwise parameters to initialize private state
>>> I think this can be achieved with less effort using function-like class declaration (afair Joe already gave an example)
>> 
>> I don’t see either of the examples Joe posted doing this.  Here is an example showing what I mean:
>> 
>> struct S {
>>     let s: String
>>     private let i: Int
>> 
>>     // user declares:
>>     memberwise init(other: S, ...) {
>>         i = other.i
>>     }
>>     // compiler synthesizes (suppressing memberwise initialization for properties with lower visibility):
>>     init(other: S, s: String) {
>>         /* synthesized */ self.s = s
>> 
>>         // body of the user's initializer remains
>>         i = other.i
>>     }
>> }
> 
> 
> Instead of several examples, I'll use just a single one to illustrate a bunch of points — and I'm leaving out comments on purpose, because I hope to see others participating with their interpretation:
> 
> public class Customer(title: String, private var birthday: NSDate?, public address: String = "n/a"): Person {
> 
> 	protected let statusPoints = - birthday?.timeIntervalSinceNow() ?? 0.0
> 
> 	let constantWithHardToExpressValue: Int
> 
> 	lazy var age: Int = dateCalculationIsHard(birthday)
> 
> 	init {
> 		constantWithHardToExpressValue = Int(statusPoints) + 1
> 		super.init(title: title)
> 	}
> 	
> 	public init(titlePrefix: String, titleSuffixObject: Any) {
> 		init(title: titlePrefix + titleSuffixObject.description, birthday: NSDate())
> 	}
> }
> 
> So: Dear reader, please do my job and explain the "pseudo"-source above ;-) — or ask questions if you are just puzzled by it.

This must be what you are suggesting for Swift because the example uses NSDate?  Thank you for providing a concrete example to look at.

Is it correct that this class would have the following members in addition to the ones declared in the body?  You used access control modifiers in that parameter list.  Would you allow any annotations that are valid for properties that can be initialized (i.e. not lazy, but maybe an observable behavior if Property Behaviors are accepted)?

let title: String // internal
private var birthday: NSDate?
public let address: String = “n/a”

It actually looks like you pass `title` to super so maybe that isn’t expected to synthesize a member?  If that is the case how does the compiler determine which parameters should receive member synthesis?  If not, I assume super would not have a `title` member and is doing something else with that argument.  Is that what you intend?

Is it also correct that all of the following forms would be valid at call sites?

Customer(title: “a title”, birthday: nil)
Customer(title: “a title”, birthday: nil, address: “an address”)
Customer(titlePrefix: “a prefix”, titleSuffixObject: Foo())

If so, does the initializer used in the first two call examples (the designated / memberwise initializer?) receive the same access control as the type itself since it cannot be specified directly?

Is it also correct that the init block that calls super would be invoked regardless of which initializer form is used?  When would this block run?     Immediately after the memberwise initializer is called?  Is it the “body” of the memberwise initializer?  It would need to run prior to any use of self in the body of `public init(titlePrefix: String, titleSuffixObject: Any)` in order to follow Swift's rules of definitive initialization.  

Is the `public init(titlePrefix: String, titleSuffixObject: Any)` initializer actually a convenience initializer?  Is it required to call the designated / memberwise initializer before it does anything else?  What rules need to be followed to ensure definitive initialization happens?  Is this rule applicable to all additional initializers the author writes?  If it is a convenience initializer maybe it just follows the current rules for those in Swift?

Maybe the memberwise parameters plus the body is the single and only designated initializer for the type?  Is that what you’re suggesting?  What if the init body needs additional non-memberwise parameters?  Is it allowed to specify those?  If so how is that accomplished?  How is the parameter ordering in the final parameter list determined?  Would you use the `…` placeholder for the memberwise parameters like the current proposal does?

What happens if another initializer wants to initialize `constantWithHardToExpressValue` to a value different than that in the factored out init block?  

What if the type needs to support more than one designated initializer?  Is that possible?  Would all designated initializers be required to receive the same set of memberwise parameters?  If that isn’t what is required how would the author implement the necessary initializers?

There a lot of details to work through here.  If we are do that we would could analyze the differences of the two approaches.  I think that is a fair request.  There are definitely some significant differences between them.  I will hold off on commenting further until we nail down exactly what it is you would like to see and how it would work.


> 
>>>> 4. More than one memberwise initializer is possible
>>> Kotlin has no need for memberwise initializers at all, and I see this as a big advantage
>> 
>> Please explain how it is an advantage.  How does Kotlin handle a case where you have some private state that needs to be initialized internally to protect invariants, but also some members which users can initialize (such as appearance attributes on a UI widget)?
> For me, something that is not necessary is always an advantage — because you can simply remove it and have a result that is more elegant and compact.
> Why would you want to add a feature that is not needed? It's just more work for those who actually build it, and it's more work for those who have to learn how to use it.

I don’t understand how this is a response to my question.  It is very common for a UI widget to have both internal state that is necessary to its implementation but not visible to users, as well as appearance properties that are directly configurable by its users.  In any case, lets focus on the previous example you gave as I believe it will address the question.

> 
>>> 
>>>> 5. Memberwise initialization of properties with declaration modifiers, behaviors / delegates is possible
>>> https://kotlinlang.org/docs/reference/delegated-properties.html <https://kotlinlang.org/docs/reference/delegated-properties.html>
>>> (afaik this is not only possible, it's handled by the current compiler for a long time)
>> 
>> Yes, I know Kotlin has this feature.  It isn’t clear from the docs how initialization of such properties is handled (for example an Observable property).  Maybe you can provide some examples of how this works.
> No, I can't (well, I accidentally did it partly...) — but I don't see why I should prove the features of a system that actually exists (and where everyone can easily check the behavior):
> I think it's not that presumptuous to assume that the Kotlin-compiler has no flaws which are so fundamental.

You are suggesting a design we should use for a feature in Swift.  I don’t think it is unreasonable to ask how that design would address specific use cases in Swift.  It is not enough to point at another language with a similar feature.  It is also not enough to just assume the Kotlin model is acceptable without being able to answer how it works in specific use cases.

> 
>>> Afaics there not much room left for the promised additional flexibility… and the problem with default values for constants just doesn't exist in Kotlin at all.
>> 
>> This is currently a problem in Swift.  I am confident that it can be solved one way or another.  I don’t think a solution should be tied to the “type initializer parameter list” syntax.
> As I said before:
> There is no need to copy, but there is also no need to discard a working solution without further explanation.

I am taking a nontrivial amount of time to work through this with you and am keeping an open mind during that discussion, but it will require specific details to change my mind.  Lets focus on the example you gave and get the details of what you want to see worked out.  

> 
>> If you can clearly demonstrate how Kotlin is superior in a specific area I will give that great consideration.  I want this proposal to be the best it can be.  However, you’re going to need to do more than just link to the docs which I have already looked at.
> I see it from the other direction:
> You have a "theory" (the proposal) and claim it is sound; Kotlin, on the other hand, is real working code!

I am trying to solve a problem for Swift.  I am willing to continue working through the Kotlin approach with you so we can understand the details of how it would fit in with Swift.  That will allow a fair comparison of the differences between the approaches.

> 
>> The good news is that as far as I can tell the things you like about what Kotlin is doing are not mutually exclusive with this proposal at all.  Think of it this way - this proposal provides a flexible and orthogonal foundation for memberwise initialization.  If desired, a future enhancement could easily be developed to provide additional syntactic sugar on top of it.  The example Joe posted shows how that might work.  
>> 
>> If this proposal is accepted and you want to pursue a proposal for that additional layer of syntactic sugar to get closer to Kotlin syntax I encourage you to do that.  The new syntax should be evaluated independently as its own proposal.  I would be happy to help show how your desired syntax could be transformed into existing syntax (including the memberwise initialization syntax if this proposal is accepted).
> I guess you really want to see your proposals accepted — and I understand that, as I'm quite sure that you put a huge amount of work into them.

I want to see the problems solved in the best way possible.  That is why I am investing time in the proposals and also why I am investing time in exploring the alternative you believe is better.  If there is a better approach or a way to improve my proposal I would prefer to identify that now rather than have it accepted as-is.

> But a "let's just take my solution and maybe integrate yours laterl"-attitude imho is not the right way:
> If it is used to silence opposers without actually supporting them later, it is wily; and if it is a honest offer, we'll end up with a language that is extrem complicated because it tries to please everyone (and orthogonality would suffer as well).

I was trying to show that the two features are not strictly mutually exclusive as one can be expressed in terms of the other.  If you don’t like that approach and think it makes the language too complex I understand that position.  I am definitely not trying to just silence you.  

Let’s work together to understand in detail the differences in these approaches and their respective advantages and disadvantages.  The first step in doing that is getting the design of what you would like to see nailed down further.

Matthew
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160101/d83dcd35/attachment.html>


More information about the swift-evolution mailing list