In the previous post, I explained that duplicating application elements is expensive and we should avoid it whenever possible.
Let me mention a few techniques that you could use.
Obviously, you can create metadata extensions, use Chain of Command for methods, subscribe to events and so on; I’m assuming that you all know that.
What developers sometimes forget is doing enough work on finding the right place for an extension. For example, they want to extend a private method (which isn’t allowed) and don’t notice that the method calls an extensible method or it itself gets called from an extensible method. Or they consider CoC only and disregard modeled events (such as OnUpdating), which are called at a different time than CoC. Don’t also forget to look for delegates, SysPlugin endpoints and so on.
It’s easy to focus on CoC and forget the basics of object-oriented programming. For instance, maybe you need inheritance and not an extension. Maybe you need a combination of both, e.g. you implement a child class and then create an extension of a factory method (such as construct()) to get your new class used instead of the standard one. Creativity may be need to design an extension.
Sometimes you need an object sharing some, but not all, behaviour with an existing one. Then composition may be a better alternative to duplication. For example, let’s say we need a custom data entity similar to a standard entity, but with slightly different behaviour required by a particular integration scenario. Instead of duplicating the entity, you may create a new entity with the standard entity as a data source and override methods of your entity, use different mandatory fields or so.
Sometimes no change is needed at all. For example, someone in the Community Forum wanted to duplicate an existing entity and remove some fields to exclude them from OData messages. But that doesn’t require a new entity; OData allows you to select the fields you want (e.g. $select=ID,Name). Make sure you explore your options before jumping into code.
There are surely situations when you can’t extend or reuse existing logic and you can solve the problem by duplicating an element (e.g. an internal method). If the duplication could be avoided by getting the existing element refactored, create an extensibility request and get it fixed. Devote some time to the description of your scenario and the design of the requested change. My experience is that extensibility requests are accepted promptly if you make the case clear. Unfortunately, it still takes a long time before the change gets delivered.
And if everything fails you you must duplicate an existing element, be aware of the risks (discussed in The cost of code duplication) and plan how to mitigate them.