How can David write of his righteousness?

O my soul, you have said to the LORD, "You are my Lord, My goodness is nothing apart from You."
Psalm 16:2

Christians often question how David could speak of his righteousness (e.g., Psalm 7:8).  David is thought to be self-righteous and not understanding either his own sinfulness or the universal sinfulness of all mankind. Three lessons:

First, In some cases, David was pleading “not guilty” to a particular charge that had been made against him.  If I am in court, charged with a crime I did not commit, I will plead “not guilty.  That plea is not a declaration of sinlessness—it’s just “not guilty” of a particular charge.

Second, there are plenty of other Psalms in which David is clear about owning his own sin and guilt before God.  Psalm 51 is a classic example.  So is Psalm 16:2 in which David declares that [His] goodness is nothing apart from [the Lord]”

Third, scripture does teach that those who are saved, born again, “in Christ” are securely wrapped in Christ’s flawless righteousness, and therefore secure.  In Psalm 16:5 David declares that God “is the portion of [David’s] inheritance,” and that God “maintained his lot.”  This is another way of saying that David was not trusting in anything in himself, but solely on the Lord and His righteousness.