Archive for the ‘Coding Tips’ Category

Coding Tip: Replace Complicated Conditions With Boolean Variables

Saturday, October 3rd, 2009

Consider the following if statement:

if(dragOperation != NSDragOperationCopy && NSPointInRect(currentMouseLocation, self.bounds)){
    //do something
}

Even though you may have worked out what the condition represents, it probably took you a little longer than it should. It’s complicated, making it time consuming to read, and prone to bugs upon modification. Thankfully, there is an easy remedy:
(more…)

Coding Tip: Use The Ternary Conditional Operator

Wednesday, September 9th, 2009

The ternary conditional operator (?:) can be used as a short-hand version of an if statement. It is a feature of many languages.

For example, this code:

int height;
if(isTall)
    height = 50;
else
    height = 10;

can be better written as:

int height = isTall ? 50 : 10;

The ?: operator is good for replacing very simple if statements, but is bad for complicated if statements as it can harm readability.

Coding Tip: Don’t Mix Abstraction Levels

Sunday, July 5th, 2009

Can you tell what is wrong with the abstraction in this class interface?

@interface EmployeeList
-(void) addObject:(Employee*)anEmployee;
-(void) removeObject:(Employee*)anEmployee;
-(NSUInteger) numberOfEmployees;
@end

Here is the answer:
(more…)

Coding Tip: Have A Single Exit Point

Tuesday, June 30th, 2009

Having one exit point (return) from a function is a good thing. Here is an example of a single exit point:

int MyArray::indexOfElement(int elementToFind){
	int foundIndex = ELEMENT_NOT_FOUND;
 
	for(int i = 0; i < m_numberOfElements; ++i){
		if(this->elementAtIndex(i) == elementToFind){
			foundIndex = i;
			break;
		}
	}
 
	return foundIndex;
}

Having multiple exit points can be bad. Here is an example of multiple exit points:

int MyArray::indexOfElement(int elementToFind){
	for(int i = 0; i < m_numberOfElements; ++i){
		if(this->elementAtIndex(i) == elementToFind){
			return i;
		}
	}
 
	return ELEMENT_NOT_FOUND;
}

Why are multiple exit points bad? Because I say so. They are also bad for these two reasons:

(more…)