How to Design a generic business entity and still be OO?

前端 未结 7 902
抹茶落季
抹茶落季 2021-02-01 20:57

I am working on a packaged product that is supposed to cater to multiple clients with varying requirements (to a certain degree) and as such should be built in a manner to be f

相关标签:
7条回答
  • 2021-02-01 21:27

    This is one of our biggest challenges, as we have multiple clients that all use the same code base, but have widely varying needs. Let me share our evolution story with you:

    Our company started out with a single client, and as we began to get other clients, you'd start seeing things like this in the code:

    if(clientName == "ABC") {
        // do it the way ABC client likes
    } else {
        // do it the way most clients like.
    }
    

    Eventually we got wise to the fact that this makes really ugly and unmanageable code. If another client wanted theirs to behave like ABC's in one place and CBA's in another place, we were stuck. So instead, we turned to a .properties file with a bunch of configuration points.

    if((bool)configProps.get("LastNameFirst")) {
        // output the last name first
    } else {
        // output the first name first
    }
    

    This was an improvement, but still very clunky. "Magic strings" abounded. There was no real organization or documentation around the various properties. Many of the properties depended on other properties and wouldn't do anything (or would even break something!) if not used in the right combinations. Much (possibly even most) of our time in some iterations was spent fixing bugs that arose because we had "fixed" something for one client that broke another client's configuration. When we got a new client, we would just start with the properties file of another client that had the configuration "most like" the one this client wanted, and then try to tweak things until they looked right.

    We tried using various techniques to get these configuration points to be less clunky, but only made moderate progress:

    if(userDisplayConfigBean.showLastNameFirst())) {
        // output the last name first
    } else {
        // output the first name first
    }
    

    There were a few projects to get these configurations under control. One involved writing an XML-based view engine so that we could better customize the displays for each client.

    <client name="ABC">
        <field name="last_name" />
        <field name="first_name" />
    </client>
    

    Another project involved writing a configuration management system to consolidate our configuration code, enforce that each configuration point was well documented, allow super users to change the configuration values at run-time, and allow the code to validate each change to avoid getting an invalid combination of configuration values.

    These various changes definitely made life a lot easier with each new client, but most of them failed to address the root of our problems. The change that really benefited us most was when we stopped looking at our product as a series of fixes to make something work for one more client, and we started looking at our product as a "product." When a client asked for a new feature, we started to carefully consider questions like:

    • How many other clients would be able to use this feature, either now or in the future?
    • Can it be implemented in a way that doesn't make our code less manageable?
    • Could we implement a different feature that what they are asking for, which would still meet their needs while being more suited to reuse by other clients?

    When implementing a feature, we would take the long view. Rather than creating a new database field that would only be used by one client, we might create a whole new table which could allow any client to define any number of custom fields. It would take more work up-front, but we could allow each client to customize their own product with a great degree of flexibility, without requiring a programmer to change any code.

    That said, sometimes there are certain customizations that you can't really accomplish without investing an enormous effort in complex Rules engines and so forth. When you just need to make it work one way for one client and another way for another client, I've found that your best bet is to program to interfaces and leverage dependency injection. If you follow "SOLID" principles to make sure your code is written modularly with good "separation of concerns," etc., it isn't nearly as painful to change the implementation of a particular part of your code for a particular client:

    public FirstLastNameGenerator : INameDisplayGenerator
    {
        IPersonRepository _personRepository;
        public FirstLastNameGenerator(IPersonRepository personRepository)
        {
            _personRepository = personRepository;
        }
        public string GenerateDisplayNameForPerson(int personId)
        {
            Person person = _personRepository.GetById(personId);
            return person.FirstName + " " + person.LastName;
        }
    }
    
    public AbcModule : NinjectModule
    {
         public override void Load()
         {
             Rebind<INameDisplayGenerator>().To<FirstLastNameGenerator>();
         }
    }
    

    This approach is enhanced by the other techniques I mentioned earlier. For example, I didn't write an AbcNameGenerator because maybe other clients will want similar behavior in their programs. But using this approach you can fairly easily define modules that override default settings for specific clients, in a way that is very flexible and extensible.

    Because systems like this are inherently fragile, it is also important to focus heavily on automated testing: Unit tests for individual classes, integration tests to make sure (for example) that your injection bindings are all working correctly, and system tests to make sure everything works together without regressing.

    PS: I use "we" throughout this story, even though I wasn't actually working at the company for much of its history.

    PPS: Pardon the mixture of C# and Java.

    0 讨论(0)
  • 2021-02-01 21:27

    I know your question is general, not tied to a technology, but since you mention you actually work with .NET, I suggest you look at a new and very important technology piece that is part of .NET 4: the 'dynamic' type.

    There is also a good article on CodeProject here: DynamicObjects – Duck-Typing in .NET.

    It's probably worth to look at, because, if I have to implement the dynamic system you describe, I would certainly try to implement my entities based on the DynamicObject class and add custom properties and methods using the TryGetxxx methods. It also depends whether you are focused on compile time or runtime. Here is an interesting link here on SO: Dynamically adding members to a dynamic object on this subject.

    0 讨论(0)
  • 2021-02-01 21:39

    A way of approaching this is to use a meta-layer, or reflection, or both. In addition you will need to provide a customisation application which will allow modification, by the users, of your business logic layer. Such a meta-layer does not really fit in your layered architecture - it is more like a layer orthoganal to your existing architecture, though the running application will probably need to refer to it, at least on initialisation. This type of facility is probably one of the fastest ways of screwing up the production application known to man, so you must:

    1. Ensure that the access to this editor is limited to people with a high level of rights on the system (eg administrator).
    2. Provide a sandbox area for the customer modifications to be tested before any changes they are testing are put on the production system.
    3. An "OOPS" facility whereby they can revert their production system to either your provided initial default, or to the last revision before the change.
    4. Your meta-layer must be very tightly specified so that the range of activities is closely defined - George Orwell's "What is not specifically allowed, is forbidden."

    Your meta-layer will have objects in it such as Business Object, Method, Property and events such as Add Business Object, Call Method etc.

    There is a wealth of information about meta-programming available on the web, but I would start with Pattern Languages of Program Design Vol 2 or any of the WWW resources related to, or emanating from Kent or Coplien.

    0 讨论(0)
  • 2021-02-01 21:40

    We develop an SDK that does something like this. We chose COM for our core because we were far more comfortable with it than with low-level .NET, but no doubt you could do it all natively in .NET.

    The basic architecture is something like this: Types are described in a COM type library. All types derive from a root type called Object. A COM DLL implements this root Object type and provides generic access to derived types' properties via IDispatch. This DLL is wrapped in a .NET PIA assembly because we anticipate that most developers will prefer to work in .NET. The Object type has a factory method to create objects of any type in the model.

    Our product is at version 1 and we haven't implemented methods yet - in this version business logic must be coded into the client application. But our general vision is that methods will be written by the developer in his language of choice, compiled to .NET assemblies or COM DLLs (and maybe Java too) and exposed via IDispatch. Then the same IDispatch implementation in our root Object type can call them.

    If you anticipate that most of the custom business logic will be validation (such as checking for duplicate chassis numbers) then you could implement some general events on your root Object type (assuming you did it something like the way we do.) Our Object type fires an event whenever a property is updated, and I suppose this could be augmented by a validation method that gets called automatically if one is defined.

    It takes a lot of work to create a generic system like this, but the payoff is that application development on top of the SDK is very quick.

    You say that your customers should be able to add custom properties and implement business logic themselves "without programming". If your system also implements data storage based on the types (ours does) then the customer could add properties without programming, by editing the model (we provide a GUI model editor.) You could even provide a generic user application that dynamically presents the appropriate data-entry controls depending on the types, so your customers could capture custom data without additional programming. (We provide a generic client application but it's more a developer tool than a viable end-user application.) I don't see how you could allow your customers to implement custom logic without programming... unless you want to provide some kind of drag-n-drop GUI workflow builder... surely a huge task.

    We don't envisage business users doing any of this stuff. In our development model all customisation is done by a developer, but not necessarily an expensive one - part of our vision is to allow less experienced developers produce robust business applications.

    0 讨论(0)
  • 2021-02-01 21:45

    Design a core model that acts as its own independent project

    Here's a list of some possible basic requirements...

    The core design would contain:

    • classes that work (and possibly be extended) in all of the subprojects.
    • more complex tools like database interactions (unless those are project specific)
    • a general configuration structure that should be considered standard across all projects

    Then, all of the subsequent projects that are customized per client are considered extensions of this core project.

    What you're describing is the basic purpose of any Framework. Namely, create a core set of functionality that can be set apart from the whole so you don't have to duplicate that development effort in every project you create. Ie, drop in a framework and half your work is done already.


    You might say, "what about the SCM (Software Configuration Management)?"

    How do you track revision history of all of the subprojects without including the core into the subproject repository?

    Fortunately, this is an old problem. Many software projects, especially those in the the linux/open source world, make extensive use of external libraries and plugins.

    In fact git has a command that's specifically used to import one project repository into another as a sub-repository (preserving all of the sub-repository's revision history etc). In fact, you can't modify the contents of the sub-repository because the project won't track it's history at all.

    The command I'm talking about is called 'git submodule'.

    You may ask, "what if I develop a really cool feature in one client's project that I'd like to use in all of my client's projects?".

    Just add that feature to the core and run a 'git submodule sync' on all the other projects. The way git submodule works is, it points to a specific commit within the sub-repository's history tree. So, when that tree is changed upstream, you need to pull those changes back downstream to the projects where they're used.

    The structure to implement such a thing would work like this. Lets say that you software is written specifically to manage a car dealership (inventory, sales, employees, customers, orders, etc...). You create a core module that covers all of these features because they are expected to be used in the software for all of your clients.

    But, you have recently gained a new client who wants to be more tech savvy by adding online sales to their dealership. Of course, their website is designed by a separate team of web developers/designers and webmaster but they want a web API (Ie, service layer) to tap into the current infrastructure for their website.

    What you'd do is create a project for the client, we'll call it WebDealersRUs and link the core submodule into the repository.


    The hidden benefit of this is, once you start to look as a codebase as pluggable parts, you can start to design them from the start as modular pieces that are capable of being dropped in to a project with very little effort.

    Consider the example above. Lets say that your client base is starting to see the merits of adding a web-front to increase sales. Just pull the web API out of the WebDealersRUs into its own repository and link it back in as a submodule. Then propagate to all of your clients that want it.

    What you get is a major payoff with minimal effort.


    Of course there will always be parts of every project that are client specific (branding, ect). That's why every client should have a separate repository containing their unique version of the software. But that doesn't mean that you can't pull parts out and generalize them to be reused in subsequent projects.

    While I approach this issue from the macro level, it can be applied to smaller/more specific parts of the codebase. The key here is code that you wish to re-use needs to be genericized.

    OOP comes into play here because: where the functionality is implemented in the core but extended in client's code you'll use a base class and inherit from it; where the functionality is expected to return a similar type of result but the implementations of that functionality may be wildly different across classes (Ie, there's no direct inheritance hierarchy) it's best to use an interface to enforce that relationship.

    0 讨论(0)
  • 2021-02-01 21:49

    Two approaches is what I feel:

    1) If different clients fall on to same domain (as Manufacturing/Finance) then it's better to design objects in such a way that BaseObject should have attributes which are very common and other's which could vary in between clients as key-value pairs. On top of it, try to implement rule engine like IBM ILog(http://www-01.ibm.com/software/integration/business-rule-management/rulesnet-family/about/).

    2) Predictive Model Markup Language(http://en.wikipedia.org/wiki/PMML)

    0 讨论(0)
提交回复
热议问题