Nice design for almost similar objects

I have two websites that have an almost identical database schema. the only difference is that some tables on one website have 1 or 2 additional fields, which others and vice versa.

I wanted to use the same database access level classes that would work with both websites.

What could be a good design pattern that can be used to handle this small difference.

for example, I have a createAccount(Account account) method in my DAO class, but the implementation will be slightly different between site A and website B.

+1
source share
2 answers

If the implementation of the objects would also be almost the same, I would suggest using an abstract base class. Extend the class by inheritance and make sure that your functions that do not know the extended field require a base class, not a derived class.

 class MercedesBenzC300 : Car { int brake(); void TurnOnRadio(); } class MercedesBenzC300Business : MercedesBenzC300 { int EnableCruiseControl(); } 

Thus, in this example, we have two cars that are almost exactly the same, however, this is a business publication, so it has cruise control. All functions that do not interact with cruisecontrol can also see this as a regular car. Only those who need to use cruise control should now get a derived class.

+1
source

Too few details to say something specific, but I will try. It depends on the complexity of the situation, but you may be happy with a simple parameterization that turns on / off the functions:

 class AccountRepository: def constructor(have_feature_a, have_feature_b, etc): # ... def create_account(account): if have_feature_a: # do something special # do common operations if have_feature_b: # do another special thing 

This works great if you have few such functions and they have very small things (represented in a few lines of code). If some of these functions are heavy, they can be encapsulated in a separate class using a well-known interface. This is called a strategy. This strategy is AccountRepository introduced by AccountRepository as a dependency. This is known as DI or dependency:

 class AccountRepository: def constructor(have_feature_a, feature_b_worker, etc): # ... def create_account(account): if have_feature_a: # do something special # do common operations if feature_b_worker != null: # line bellow runs heavy code encapsulated in strategy feature_b_worker.do_work(account) 

Now you can even have several FeatureB implementations and use any of them for different cases. For instance. one for tests and one for production.

0
source

Source: https://habr.com/ru/post/1494115/


All Articles