Are code generators bad?

后端 未结 26 1987
耶瑟儿~
耶瑟儿~ 2021-02-07 07:44

I use MyGeneration along with nHibernate to create the basic POCO objects and XML mapping files. I have heard some people say they think code generators are not a good idea. Wha

26条回答
  •  青春惊慌失措
    2021-02-07 08:36

    Code generators are great, bad code is bad.

    Most of the other responses on this page are along the lines of "No, because often the generated code is not very good."

    This is a poor answer because:

    1) Generators are tool like anything else - if you misuse them, dont blame the tool.

    2) Developers tend to pride themselves on their ability to write great code one time, but you dont use code generators for one off projects.

    We use a Code Generation system for persistence in all our Java projects and have thousands of generated classes in production.

    As a manager I love them because:

    1) Reliability: There are no significant remaining bugs in that code. It has been so exhaustively tested and refined over the years than when debugging I never worry about the persistence layer.

    2) Standardisation: Every developers code is identical in this respect so there is much less for a guy to learn when picking up a new project from a coworker.

    3) Evolution: If we find a better way to do things we can update the templates and update 1000's of classes quickly and consistently.

    4) Revolution: If we switch to a different persistence system in the future then the fact that every single persistent class has an exactly identical API makes my job far easier.

    5) Productivity: It is just a few clicks to build a persistent object system from metadata - this saves thousands of boring developer hours.

    Code generation is like using a compiler - on an individual case basis you might be able to write better optimised assembly language, but over large numbers of projects you would rather have the compiler do it for you right?

    We employ a simple trick to ensure that classes can always be regenerated without losing customisations: every generated class is abstract. Then the developer extends it with a concrete class, adds the custom business logic and overrides any base class methods he wants to differ from the standard. If there is a change in metadata he can regenerate the abstract class at any time, and if the new model breaks his concrete class the compiler will let him know.

提交回复
热议问题