Concise code · using a macro in a return statement


So, I bet this will sound familiar: for filling a table view you need to return either

  • The number of items in the datasource to indicate the required number of rows, or
  • 1 — in case there are no items and we need to show a cell stating that there is no content.

Solution 1 · Verbose

if ([self.catalogue.products count]) {  
    return [self.catalogue.products count];
} else {
    return 1;

Creating an if-else statement creates a lot of wasted space around the actual "logic"…

"…Wait, I can do this with a ternary operator. Hmm but creating one inline statement with the ternary proves a bit long/unreadable for some people.."

Solution 2 · Using a ternary operator

Now at least we're down to half the number of lines:

NSInteger numberOfProducts = [self.catalogue.products count];  
return numberOfProducts ? numberOfProducts : 1;  

Although this is shorter, because of the code density it gets harder to read.

Solution 3 · MAX

Down to a single concise statement, about a quarter of the number of lines as compared with solution 1, and more readable:

return MAX(1, [self.catalogue.products count]);  
Share this post:

Versatile developer with a passion for clean code, a keen eye for design and a strong sense of usability. Enjoys mobile development, user-centered design, and getting things pixel perfect.