Patchy feedbacks for stabilization and optimal control: general theory and robustness properties