Keeping your settlement tightly organized is definitely key for maintaining any sort of control over your settlers.
Try to place your crops, and the beds needed for farmers close, and be sure to assign each settler to a bed. Same for merchants, scrappers and guards. Build any shops and gathering spots centrally located relative to your workstations. I've found that so long as a settler has an assigned bed and job, and access to shopping and relaxation, they rarely stray far.
As already noted, walls aren't really much good for overall defense, as enemies will spawn inside your boundaries, but they can be useful for channeling attackers into killing grounds, and also for dividing up work/living areas.
With Sanctuary, I built a single floor 10 bed barracks for scrappers and farmers to one side of the workshop house, and on the other side a 2 story building with a large lounge/bar on the first floor, and beds for the merchants and companions on the second floor. HMGs on the rooftop of both buildings, one per corner.
Crops and scrapper benches are built directly behind their barracks(36 points of food and 4 benches), merchants line the sidewalk in front of the workshop, with a few more turrets covering the doorways.
I only have 2 full time guards assigned, they man a pair of elevated posts facing the bridge, supported by 6 HMGs, with a small barracks nearby; this lets them slaughter random beasties chasing Provisioners and traveling merchants on the road from Red Rocket.
Using this basic setup seems to work well for keeping settlers somewhat confined, they'll typically be at work, at play or in bed; note that I also use clothing and renamed weapons to ensure at a glance folks are where they should be.