Avoiding nested blocks with asynchronous code in objective-c

a 夏天 提交于 2019-12-05 09:08:31
Fattie

I think you've discovered dispatch groups!

there are 1000s articles on them, no need to pointlessly paste something in here,

Wait until multiple networking requests have all executed - including their completion blocks

cheers!


On a simpler level, it's possible what you're looking for is just simply "breakaway code" which is a critical part of writing, simply, tidy code. Note that this is not always the solution, but often - also, I'm not 100% clear on what you're asking. But in break away code you go like this ...

{
do something;
if ( failure, and you don't want to do any more ) return;
do some other important thing;
if ( failure of that thing, and you don't want to do any more ) return;
do yet another routine here;
if ( some other failed conditions, and you don't want to do any more ) return;
}

Here's a typical example. Often you will see code something like this...

-(void)loadNameInToTheCell
  {
  if ( self.showname != nil && [self.showname notLike:@"blah"] && kount<3 )
        {
        // many many lines of code here
        // many many lines of code here
        // many many lines of code here
        }
  }

You with me? But it's much better to write it like this:

-(void)loadNameInToTheCell
  {
  if ( self.showname == nil ) return;
  if ( [self.showname notLike:@"blah"] return;
  if ( kount<3 ) return;

  // many many lines of code here
  // many many lines of code here
  // many many lines of code here
  }

makes sense?

Note that critically, in any real project it's about the documentation not the code, so you can properly discuss and comment on that ...

-(void)loadNameInToTheCell
  {
  if ( self.showname == nil ) return;
  // don't forget Steve's routine could return nil

  if ( [self.showname notLike:@"blah"] return;
  // should we worry about caps here?

  if ( kount<3 ) return;
  // client wants to change this to 4 in future - Steve
  // screw that ... Biff, 8/2014

  // many many lines of code here
  // many many lines of code here
  // many many lines of code here
  }

Makes sense right? I hope that helps with what you were asking. You have to think the "other way around" you know?

A possible rule of thumb is if you ever have a condition and then a "very long block of code" - it's sort of wrong. Turn it around the other way and have breakaway conditions. Only then, have "the actual relevant code". In a sense .. never put a long slab of important code inside an if block; you're sort of thinking the wrong way around if so.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!