Coding Tips

From PsiWiki

Below are a collection of coding tips written by the Psi team.

This page serves several purposes:

  • It allows us to keep track of what each other know about coding.
  • It provides a guide for anyone wishing to patch Psi; patches following these tips are much more likely to be accepted unmodified than those which don't.
  • It's hopefully not a bad place for people to look for tips about structuring their own code.

Note that not all of Psi's code adheres to these tips! Patches which improve the situation will be looked upon fondly ;)

Contents

Interesting books

Below are some books which are worth reading for immediate reward, containing many coding tips. Some of the coding tips below come from these books.

  • "The Pragmatic Programmer: From Journeyman to Master" by Andrew Hunt and David Thomas. Read this book. It's a well-written book that's far more accessible than most programming books and is worth reading. Possibly several times.
  • "User Interface Design for Programmers" by Joel Spolsky. A light book with some useful tips and philosophies about UI design, with a lot of examples from the real world.
  • "Effective C++" / "More Effective C++" by Scott Meyers. This series of books contains many do's and dont's of C++. For people who have familiarity with C++.


Coding Tips

Use QPointers

If storing pointers as members, do so in a QPointer. For example:

   class Foo 
   {
       Foo(Bar* bar) : bar_(bar) {
       }
       void doSomethingOnBar() {
           bar_->doSomething();
       }
       QPointer<Bar> bar_;
   };

But don't do this when you connect to the destroyed signal and need the pointer in the connected slot.

Use initialiser lists

If you find yourself putting someMember = NULL; in your constructors, put them in the initialiser list instead. So, use

   MyClass::MyClass() : myptr_(NULL) 
   {
   }

instead of

   MyClass::MyClass() 
   {
       myptr_ = NULL;
   }

Always use braces

Always use braces with an if (or a while, or a for or a ...) statement, even if it's a one-liner; there's no convincing reason not to and it can splat bugs months before anyone dreams of writing the code that causes them. So, use

   if (condition) {
       doSomething();
   }

instead of

   if (condition)
       doSomething();

If something can't happen, make sure it doesn't

Use Q_ASSERT when you are sure that a certain condition is met. This will immediately show errors when for some reason, the assumption turned out wrong. For example:

   int x = computeSomePositiveResult();
   Q_ASSERT(x > 0); // X will always be positive
   ...

or

   void foo(Bar* bar) {
       Q_ASSERT(bar); // Bar will never be null when passed to this function
   }


Always add Q_OBJECT

All QObject derived classes should have a Q_OBJECT in the class definition.