Our natural reaction to someone attacking us - especially if without cause - is to strike back. We celebrate the guys in the movies who get even with their enemies and then take a little more.
David knew that this is not the way Godly people live. He could honestly say to God
"You have tested my heart;
You have examined me at night.
You have tried me and found nothing evil;
I have determined that my mouth will not sin."
Your first thought might be, "Well then you're just asking to get smacked around (literally and figuratively) if you don't fight back." But David knew that he could call on God and that God would answer him.
"I call on You, God, because You will answer me."
17 Do not repay anyone evil for evil. Try to do what is honorable in everyone's eyes. 18 If possible, on your part, live at peace with everyone. 19 Friends, do not avenge yourselves; instead, leave room for His wrath. For it is written: Vengeance belongs to Me; I will repay, says the Lord. 20 But If your enemy is hungry, feed him. If he is thirsty, give him something to drink. For in so doing you will be heaping fiery coals on his head. 21 Do not be conquered by evil, but conquer evil with good.
It seems like the key to this is to determine before something happens that "your mouth will not sin." Once you are in the midst of an attack it may be too difficult to make that conscious choice to not sin.
Instead choose David's words
"Protect me as the apple of Your eye;