[swift-users] Should I be using more catchless do blocks?
savichmichael at icloud.com
Mon Jun 19 13:47:12 CDT 2017
Yeah, it's all about balance to be sure. Though one benefit of do blocks is in functions that are tied to a sense of time. It seems to me that the in case of something like viewDidLoad separating code into too many functions can obscure the fact that the code is meant to be executed at that time. Closures can provide much of the same functionality but I'm pretty sure inline closures have to have names and sometimes risking a bad name is worse than no name at all.
Anyway, do you think that most Swift users are even aware that do can be used in this fashion?
Sent from my iPad
> On Jun 19, 2017, at 2:33 PM, Michael Ilseman <milseman at apple.com> wrote:
> Introducing scope to manage lifetimes of local variables is a useful and valuable practice. Note that it might also be an opportunity to refactor the code. Any do block you want to introduce could also be a local function definition that you call later. Alternatively, it could be generalized and extracted into a utility component. Long function bodies with many do blocks could be a code smell.
>> On Jun 18, 2017, at 7:07 PM, Michael Savich via swift-users <swift-users at swift.org> wrote:
>> So, something I did not know until recently is that do blocks in Swift are for more than just error handling, they can also be used to tighten scope.
>> I'm wondering, why not use a ton of do blocks? Like, if I have a ViewController lifecycle method like viewDidLoad, I could segment it into out a do block for creating subviews, a do block for loading data into them, and a do block for adding them to the view itself. This seems like it would enforce grouping code tightly together.
>> Yes I could adopt a functional style of programming, but that has its downsides too, namely reading any functional code involves trawling through a long sequence of function calls. What I'm saying is, do blocks seem like a way to get many of the benefits of functional programming while maintaining the readability of imperative code. (Sorry functional programmers, I promise I love Haskell too!)
>> So I guess what I'm saying is… somebody talk me down from this ledge. Is there a reason I shouldn't refactor my projects to be full of do blocks? And can this usage of do really be considered idiomatic Swift? Or will most people reading my code be left wondering where all the try and catch statements are?
>> Sent from my iPad
>> swift-users mailing list
>> swift-users at swift.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the swift-users