For a general class of risk models, the dividends-penalty identity is derived by probabilistic reasoning. This identity is the key for understanding and determining the optimal dividend barrier, which maximizes the difference between the expected present value of all dividends until ruin and the expected discounted value of a penalty at ruin (which is typically a function of the deficit at ruin). As an illustration, the optimal barrier is calculated in two classical models, for different penalty functions and a variety of parameter values.