That’s one school of thought. Law as a tool to punish those who have committed a prohibited act, mostly reactive.
Others consider law a way of encoding the group’s existing rules and norms.
In that view, making something illegal or mandatory is not a prerequisite for punishment: it’s the actual main point.
The threat of punishment is meant for those not deterred from an act by the simple fact it is illegal (and the threat only works if enforced).
Others put it the other way around, and see law as social engineering, a way to shape the group, either through the encoding itself of the desired behaviours in law, or through deterrence. Or both. If what one is after is either power or legitimacy, they need compliance more than punishment (can’t rule once you’ve chopped everyone’s heads off, or once the mob has put yours on a spike).
It’s also sometimes used as coordination (which side of the road we drive on).
And there’s also law as dispute resolution (if your neighbour’s hen lays an egg in your garden, who does it belong to? Yes, it’s ridiculous. Yes, some places have one or more laws for that). Which, incidentally, both requires and provides legitimacy. Funny, that.
And probably many other kinds / points of view, with many different purposes, intents, and mechanisms.
Anyway, all that to say law is vast, fascinating, and utterly tedious. And apologies for the tangent.