The best way to get your security deposit back is to entrust it to a good landlord in the first place. In most states, landlords are required to keep that money separate from other accounts so they can return the deposit to their tenants when they move out. That's why it's called a "security deposit" and not "fuel for your landlord's gambling spree."
Unfortunately, some landlords and even some professional management companies will try to unfairly hold on to security deposits -- because who wouldn't want to keep extra money? The key is not renting from these people in the first place. When you're considering renting a place, research the landlord as thoroughly as you research the neighborhood. Hit up the Better Business Bureau to see if there are complaints against the property management company. Check out Yelp.com, ApartmentRatings.com or local real estate sites to read reviews of the building. Heck, just run the landlord or property management company's name through a search engine to see if there's a pattern of complaints. It's a lot easier to get your security deposit back if you don't rent from someone who never intended to return it in the first place.