A Journey 2 Eternity

Good Code

Posted on: November 26, 2007

01. Never allocate memory like this way

void MyFunc(CString strText)
{
	int size = strText.GetLength();
	// Bad practice
	//TCHAR* pszNewText = new TCHAR[size];

	// Good practice
	TCHAR* pszNewText = new TCHAR[size+1];
}

02. Avoid Using the same parameter as Input and Output parameter

Bad code:

BOOL GetMergedCellRect(CRect& rect)
{
	rect.top++;
	rect.bottom–;
	Return TRUE;
}

Good Code:

BOOL GetMergedCellRect(CRect rect, /*OUT*/CRect& mergedRect)
{
	mergedRect = rect;
	mergedRect.top++;
	mergedRect.bottom–;
}

If we have method such as InflateRect, DeflateRect, whose names are obviously and clearly stating us to do some operation on the passed rectangle then we can use the same parameter as input and output.

03. It would be a good idea to typedef the parent class as Super inside the child class. This technique is used in the Symbian OS.

class wxEdit : public wxWindow
{
	typedef wxWindow Super;

public:
	void OnPaint() {
		Super::OnPaint();
	}
}

04. Sometimes we did ugly hacking for some situation, but the following style is never acceptable. Never allow Base Class to know his child classes.

For example, we should never declare a child class a friend of of our base class unless absolutely necessary.

class CHotListCtrlCellBase : public CObject
{
	friend class CHotListCtrlURLCell;
	friend class CHotListCtrlCellCombo;
	friend class CHotListCtrlCellCheck;

	…
};

05. Most of us are confused or make mistake while using memset() function.

	TCHAR* pBuff = new TCHAR[256];
	memset( pBuff, 0, 256); // WRONG!
	memset( pBuff, 0, 256*sizeof(TCHAR)); // Ok
Advertisements
Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Pages

Categories

November 2007
M T W T F S S
    Dec »
 1234
567891011
12131415161718
19202122232425
2627282930  

Blog Stats

  • 26,968 hits
%d bloggers like this: