The passage of the law is necessary to set up the initial threat. The judicial leeway in punishing is due to the need to balance the harm to the criminal vs. the benefit to society from further evidence of the credibility of the threat. Different cases call for difference sentences.
Again, a judge might decide that 7 years in prison is the best punishment in one particular case, because another extra year will harm the perpetrator more than society would benefit from greater deterrence; and at the same time, merely 6 years in prison shows mercy to the criminal, but the failure to deter sufficiently outweighs that.
Judges then are optimizers who must strive to create the greatest good for the greatest number within the confines of their profession.