Codes represent the collective wisdom of those now serving in a given industry and those who have gone before. While a code may have some rough edges here and there, and some of its rules are not "best practices" in every situation, we still have codes because—in the big picture—they work.
Code books exist to protect the public, as well as private end-users. In liability suits, the "should have known" principle applies. If you are responsible for the design, management, or installation of a project, you are liable for code-covered issues.
Some codes began life as recommended procedures or guidelines for members of a given trade or professional organization. As the procedures became generally accepted practices, they moved into a more formal, more binding form—codes.
Other codes began life as standards. An industry trade group published a set of standards to address the underlying technical issues of how a job should be done. Firms that adhered to the standards produced better work. Firms that did not adhere to the standards were able to charge lower prices, because they didn’t incur the cost of buying the standards or getting trained in application of those standards. Firms that adhered to the standards didn’t want to engage in "fly by night" pricing and the shoddy work required to profit from it. A combination of pride, competitiveness, and public responsibility moved these folks to lobby for their standards to become codes.
No matter how codes began, they require a minimum standard of performance from practitioners and others involved in a given industry. While they don’t always represent the most cost-effective or efficient way of doing a particular job, they do prevent the enormous costs of a job gone catastrophically wrong.
Many people wrongly assume code requirements are the "ideal" standards for performance—a target that is OK to miss. This is extremely common in manufacturing in relation to the National Electrical Code. If every factory in the USA conformed to the NEC’s Article 250—at a minimum—the annual savings would probably exceed what Americans collectively pay in personal income tax.
Code books are not design guides, nor do they purport to replace training or common sense. Understanding and applying some codes takes a hefty amount of training and experience, because some of the subjects the various codes address are not simple. That’s one more reason we have the codes.