General theory of detection and optimality