How to change membership in groups based on attributes of users in AD automatically

If your company has a complicated structure, you may need to filter members of your security or distribution groups automatically based on changes to some attribute of users in Active Directory – let's say Department.