Some of the Xojo forum members have created a Clash of Clans team called … Xojo, and if you are an Active player, then feel free to join!
Here is a layout of one of the good defense plans in Clash of Clans.

There are four sets of 5 items surrounding the castle. At least 3 of the 5 items are for defense. This layout has the cannons closest to the centre so that most cannons will fire to help defend the area under attack. Double walls are located in between each of the four armoured areas which helps divide the armies into two groups when attacking (divide and conquor!).
Non-defense items (mines, etc.) are placed on the outside of the walls to slow down the attacking units and help give enough time for the arrows and cannons to fire on attackers.
If you have seen other good town layouts, feel free to put a screen grab here!
Go Xojo Clan!!!
Basically it seems to be a good idea to build walls around everything separately, so that the enemy will have to break through a lot of walls before it can even reach your defences, which gives them time to do as much damage as possible before they’re taken down.
This setup has been working pretty well for me:

There have been some new items released since I last upgraded the layout properly, and they recently added more walls which i’ve placed at the bottom until i’ve found out what to do with them, i have also probably not been upgrading my walls enough, most of my gold has gone to upgrading defences, resource generators and vaults.
Overall though, it has pretty good coverage, enemies can’t ‘spawn’ into the white outlined area, so it will also take them longer to walk to my walls.
This website helped me pick a good defence layout:
http://www.clashofclans-tools.com/Layouts/Top
As well as a nice ‘farming’ layout since I kept getting all my gold stolen before, making it harder to upgrade.
Go get 'em Xojo Clan!
This layout worked really well for me in my war layout. Usually only get 1 star against me, and very rarely 3 stars. Works especially very well against dragon attacks.
You’ll notice I’m not worried about protecting resources in my war layout…

The two big-barrel bombs right next too each other, also takes out hords of hogs very efficiently.
I would add the following to your code Jean-paul:
if z.isbroken then
try
call app.AskAccordWifeForHaveMoneyForBuyingNewItems() // warn function return always false !!
catch
call app.ApplyFarmingStrategyToByNewItems()
end try
end if