David was desperate when he fled from Saul. So desperate that he not only persuaded the priest to give him the holy shew bread, but he lied to the priest twice, saying that he was there because the King had sent him on some urgent business, so urgent that he had no time to pack food or weapons. He then retrieved Goliath's sword from the priest. When he got to Gath, he was afraid of the king there so he faked being crazy, scratching at the gates and drooling spit down his beard. Both of these deceptions in short order kept him free and alive in the short term, and eventually he became King, God's man on the throne.
Jesus endorsed and defended David's use of the shew bread when he was defending his own disciples for eating grain plucked on the Sabbath day. Jesus points out that the Sabbath was made to serve man's good, not man to be a slave to the Sabbath. Same with the shew bread, yes it was holy, but holy bread doesn't help the starving child of God if he looks at it, only if he eats it. The lies David told the priest aren't mentioned by Jesus. It seems God understands when his people are under threat and hard pressed to survive, that they may make mistakes and even sins that are forgiven later, but God looks at the heart and the intent and the greater good that comes from his people who serve him. Was David perfect in these matters? No. He lied or at very least deceived people. But these things were small in God's overall plan to make him King, and David was forgiven his sins because he was a man after Gods own heart.
You might do all the right things, legalistically, but your heart may be far from God and your self righteousness may make you into a Pharisee who heartlessly criticizes God's servants. Legalism keeps you from experiencing the grace of being forgiven. God knows we are weak and imperfect and cave under pressure, but if our heart is full of faith and love for him, he forgives, restores, purifies and exalts us.