I don't have much information to share regarding exactly how they work, but I would build as many Defense Units as you can afford!
I tend to make sure I've got enough resources to keep troops coming out of my Barracks and Factories at all times, but when I'm feeling especially wealthy I like to make sure I've got defenses under construction as well.
Defenses are essentially just another kind of troop. You can learn more about their strengths and weaknesses in the Stat Array displayed to the right of the Defense type.
You'll want to have plenty of them, in a mixed variety if possible. By the time you know that you're going to be attacked, you won't be able to build them fast enough!
Good luck out there.