KVC and KVO in Practice

After going through the chapters 8 and 9, I’m curious what experienced Cocoa developers (i.e., the moderators, or anyone else) think about using KVC/KVO for production code. In my book I highlighted the relevant portion offering advice when to decide between KVO and, for instance, delegate methods. Relying on string values to make bindings makes me cringe, and while it’s possible to just compile the app and look for runtime errors… that seems crazy. I’m not sure I see KVC/KVO as being very beneficial when it comes to writing quality software. Is it good practice to use for anything other than small little tools that you write in a short time while all the context is in your head? (Or does it become more agreeable with experience?)

I’ve got to say, I love the book so far! You all have done a fantastic job, and I feel like every single page offers a huge amount of value.

This is a great question. Especially in the context of Swift, where everything is so carefully type-checked, KVC/KVO/bindings can feel utterly reckless. As things in Cocoa stand now, there is a trade-off to be made. KVC/KVO/bindings allow you to skip writing a great deal of tedious code, but you also have to be that much more careful in writing and testing your app.

My personal approach is to use KVC/KVO/bindings in very well-defined, constrained parts of my app. I don’t like to have key paths reaching deep into the object graph. I keep them limited to one or two keys deep. One example would be a sheet (limited number of controls and things to be bound). Another would be binding the contents of a view controller to the model(s) that it represent(s).

Undo is another interesting area. KVO fits so nicely with the typical needs of implementing undo that it’s practically begging for you to use it. It makes it much easier to implement. But, again, there’s that risk. You have to update the key strings if you refactor something.

I think KVC/KVO/bindings are too powerful a feature to cast aside, but you do need to exercise care in how you use them. Start small (sheets, simple windows, simple view controllers). This will make it easier to debug when problems arise (and more realistic to test!) – and help you avoid having this tangled mess that you don’t know how to fix so you end up ripping everything out (not that I have ever done that).

Hope this helps and very happy to hear you’re enjoying the book!