OOP - Best way to populate Object - oop

I try to follow OOP and S.O.L.I.D for my code and came across a topic where I'm not sure what's the best way to align it with OOP.
When I have an Object with different properties, what's the ideal way to populate those properties?
Should the Object if possible populate them?
Should separate code assign the values to the properties?
I have the following example (Python), which I created based on how I think is the best way.
The Object has methods that will populate the properties so if you instantiate the Object, in this case an Account with and Id, it should automatically populate the properties since they can be retrieved with the ID using DB and API.
class Account:
def __init__(self, account_id):
self.id = account_id
self.name = None
self.page = Page(self.id)
def populate(self):
self.get_name()
def get_name(self):
''' Code to retrieve Account name from DB with account_id '''
self.name = <NAME>
class Page:
def __init__(self, account_id):
self.id = 0
self.name = None
self.user_count = 0
self.populate()
def populate():
self.get_id()
self.get_name()
self.get_user_count()
def get_id(self):
''' Code to retrieve Page Id from DB with account_id '''
self.id = <Page_ID>
def get_name(self):
''' Code to retrieve Account name from DB with account_id '''
self.name = <NAME>
def get_user_count(self):
''' Code to retrieve user_count from API with page_id '''
self.user_count = <user_count>
So instead of doing something like:
account = Account()
account.id = 1
account.name = function.to.get.account.name()
account.page = Page()
account.page.id = 1
I will have it managed by the class itself.
The problem I could see with this is the dependency on the DB and API classes/methods which go against S.O.L.I.D (D - Dependency Inversion Principle) as I understand.
For me it makes sense to have the class handle this, today I have some similar code that would describe the Object and then populate the Object properties in a separate Setup class, but I feel this is unnecessary.
The articles I found for OOP/S.O.L.I.D did not cover this and I didn't really find any explanation on how to handle this with OOP.
Thanks for your help!
Michael

Your design seems fairly ok. Try having a look # Builder Pattern and Composite pattern. And for your question on violation of D principle.
The problem I could see with this is the dependency on the DB and API classes/methods which go against S.O.L.I.D (D - Dependency Inversion Principle) as I understand.
The dependencies are already abstracted into separate components I guess. It is the responsibility of that component to give the data you needed per the contract. Your implementation should be independent of the what that component internally does. A DAO layer for accessing DB and Data APIs can help you achieve this.
The dependency then your system will have is the DAO component. That can be injected with different ways. There are frameworks available to help you here or you can control the creation of objects and injections when needed with some combinations of factory, builder and singleton patterns. If it is single DB instance or LogFile you may also consider using Singleton to get the component.
Hope it helps!

In looking at SOLID and OOP the key is to analyze what it is your doing and separate out the various elements to make sure that they do not end up mixed together. If they do the code tends to become brittle and difficult to change.
Looking at the Account class several questions need to be answered when considering the SOLID principles. The first is what is the responsibility of the Account class? The Single Responsibility Principle would say there should be one and only one reason for it to change. So does the Account class exist to retrieve the relevant information from the DB or does it exist for some other purpose? If for some other purpose then it has multiple responsibilities and the code should be refactored so that the class has a single responsibility.
With OOP typically when retrieving data from a DB a repository class is used to retrieve information from the DB for an object. So in this case the code that is used to retrieve information from the DB would be extracted out form the Account class and put in this repository class: AccountRepository.
Dependency Inversion means that the Account class should not depend explicitly on the AccountRepository class, instead the Account class should depend on the abstraction. The abstraction would be an interface or abstract class with no implementation. In this case we could use an interface called IAccountRepository. Now the Account class could use either an IoC container or a factory class to get the repository instance while only having knowledge of IAccountRepository

Related

What is the name of described pattern?

From high level perspective, the pattern makes possible to get polymorphic behavior without creating classes hierarchy.
It consists of 3 parts:
Data container classes, which have a certain field to be distinguished (e.g. User class with country field, or any class with tenant field in a multi-tenant saas project).
Context classes: these classes contain the data and logic which varies for different types of data containers (e.g. different logic for different tenants). There's a top-level Context class with all varying props set to default, and multiple derived classes which override defaults.
Data consumers/processors: these are business logic holders. They accept data container(s) and Context as parameters.
The 3rd-group citizen may have a method like:
Price getPrice(Price price, Context context) {
double VAT = context.getVAT()
return new Price(
transform(price.amount + price.amount * VAT, price.currency, context.currency),
context.currency
)
}
...
//and here's the call:
Context ctx = getContext(principal.getCountry())
Price priceInUserCurrency = priceCalculator(priceInUsd, ctx);
Here's a simplified UML diagram:
Basic usage: when we need to introduce a different specific behavior for small groups of objects of the same class,
we add a new method to Context with reasonable default value and implement the actual logic in concrete contexts. Then whereever we need to inject this piece of logic, we just call correspondent context method.
It looks like you are describing the Strategy Design Pattern.
What gives it away is that you can perform process() for both PersonProcessor and PaymentProcessor. Like this example below.
Each object knows how to handle their own case of the functionality.
To me the description of
makes possible to get polymorphic behavior without creating classes hierarchy
is more close to the concept of the State design pattern.
Because it allow an object to alter its behavior when its internal state changes. The object will appear to change its class. Further more also allows you to keep attributes of a former state even when the state changes afterwards.
About the inheritance part you can read more here.

IOC , Class Factory, Open/Closed

I have a question about IOC, factories, and the Open/Closed principle.
consider, if you will, the following factory
public function PODocument( _type as string) as IPODocument
dim d as new PODocument
if _type = "service" then
d.header = new ServicePOHeader()
d.details = new ServicePOLineItems()
else if _type = "merchandise" then
d.header = new MerchandisePOHeader()
d.details = new MerchandisePOLineItems()
end if
return d
end function
This is working for me and I can nicely have a webpage show information about heterogeneous collections.
My challenge is that today someone told me sometimes a certain customer will order a service and merchandise together. Come on, who among us could have seen that coming?
So I write a new set of providers that handle the added complexity, changed the factory to include a case for the new type, I'm back off and running.
However, I have violated the open/closed principle by changing the factory, which was released to production.
Is there a way to set this up so that I am not constantly changing the factory?
thanks in advance.
Yes. The simplest example for your case would be to define a factory class for each _type, and name them ServiceFactory, MerchandiseFactory, etc, or put a <PODocumentType("Service")> etc on them.
Then just find all factories (for example, using reflection), put them in a Dictionary(Of String, IPODocumentFactory) and select correct one based on key.
In a more complicated case, IPODocumentFactory interface may include CanCreate() method in addition to Create(). Then you can select a factory on the list based on its opinion about current situation.
Note that the discovery and list resolution support is often provided out of the box by DI frameworks such as Unity or Autofac.

Dependency injection of local variable returned from method

I'm (somewhat) new to DI and am trying to understand how/why it's used in the codebase I am maintaining. I have found a series of classes that map data from stored procedure calls to domain objects. For example:
Public Sub New(domainFactory As IDomainFactory)
_domainFactory = domainFactory
End Sub
Protected Overrides Function MapFromRow(row As DataRow) As ISomeDomainObject
Dim domainObject = _domainFactory.CreateSomeDomainObject()
' Populate the object
domainObject.ID = CType(row("id"), Integer)
domainObject.StartDate = CType(row("date"), Date)
domainObject.Active = CType(row("enabled"), Boolean)
Return domainObject
End Function
The IDomainFactory is injected with Spring.Net. It's implementation simply has a series of methods that return new instances of the various domain objects. eg:
Public Function CreateSomeDomainObject() As ISomeDomainObject
Return New SomeDomainObject()
End Function
All of the above code strikes me as worse than useless. It's hard to follow and does nothing of value. Additionally, as far as I can tell it's a misuse of DI as it's not really intended for local variables. Furthermore, we don't need more than one implementation of the domain objects, we don't do any unit testing and if we did we still wouldn't mock the domain objects. As you can see from the above code, any changes to the domain object would be the result of changes to the SP, which would mean the MapFromRow method would have to be edited anyway.
That said, should I rip this nonsense out or is it doing something amazingly awesome and I'm missing it?
The idea behind dependency injection is to make a class (or another piece of code) independent on a specific implementation of an interface. The class outlined above does not know which class implements IDomainFactory. A concrete implementation is injected through its constructor and later used by the method MapFromRow. The domain factory returns an implementation of ISomeDomainObject which is also unknown.
This allows you supplement another implementation of these interfaces without having to change the class shown above. This is very practical for unit tests. Let's assume that you have an interface IDatabase that defines a method GetCustomerByID. It is difficult to test code that uses this method, since it depends on specific customer records in the database. Now you can inject a dummy database class that returns customers generated by code that does not access a physical database. Such a dummy class is often called a mock object.
See Dependency injection on Wikipedia.

God object - decrease coupling to a 'master' object

I have an object called Parameters that gets tossed from method to method down and up the call tree, across package boundaries. It has about fifty state variables. Each method might use one or two variables to control its output.
I think this is a bad idea, beacuse I can't easily see what a method needs to function, or even what might happen if with a certain combination of parameters for module Y which is totally unrelated to my current module.
What are some good techniques for decreasing coupling to this god object, or ideally eliminating it ?
public void ExporterExcelParFonds(ParametresExecution parametres)
{
ApplicationExcel appExcel = null;
LogTool.Instance.ExceptionSoulevee = false;
bool inclureReferences = parametres.inclureReferences;
bool inclureBornes = parametres.inclureBornes;
DateTime dateDebut = parametres.date;
DateTime dateFin = parametres.dateFin;
try
{
LogTool.Instance.AfficherMessage(Variables.msg_GenerationRapportPortefeuilleReference);
bool fichiersPreparesAvecSucces = PreparerFichiers(parametres, Sections.exportExcelParFonds);
if (!fichiersPreparesAvecSucces)
{
parametres.afficherRapportApresGeneration = false;
LogTool.Instance.ExceptionSoulevee = true;
}
else
{
The caller would do :
PortefeuillesReference pr = new PortefeuillesReference();
pr.ExporterExcelParFonds(parametres);
First, at the risk of stating the obvious: pass the parameters which are used by the methods, rather than the god object.
This, however, might lead to some methods needing huge amounts of parameters because they call other methods, which call other methods in turn, etcetera. That was probably the inspiration for putting everything in a god object. I'll give a simplified example of such a method with too many parameters; you'll have to imagine that "too many" == 3 here :-)
public void PrintFilteredReport(
Data data, FilterCriteria criteria, ReportFormat format)
{
var filteredData = Filter(data, criteria);
PrintReport(filteredData, format);
}
So the question is, how can we reduce the amount of parameters without resorting to a god object? The answer is to get rid of procedural programming and make good use of object oriented design. Objects can use each other without needing to know the parameters that were used to initialize their collaborators:
// dataFilter service object only needs to know the criteria
var dataFilter = new DataFilter(criteria);
// report printer service object only needs to know the format
var reportPrinter = new ReportPrinter(format);
// filteredReportPrinter service object is initialized with a
// dataFilter and a reportPrinter service, but it doesn't need
// to know which parameters those are using to do their job
var filteredReportPrinter = new FilteredReportPrinter(dataFilter, reportPrinter);
Now the FilteredReportPrinter.Print method can be implemented with only one parameter:
public void Print(data)
{
var filteredData = this.dataFilter.Filter(data);
this.reportPrinter.Print(filteredData);
}
Incidentally, this sort of separation of concerns and dependency injection is good for more than just eliminating parameters. If you access collaborator objects through interfaces, then that makes your class
very flexible: you can set up FilteredReportPrinter with any filter/printer implementation you can imagine
very testable: you can pass in mock collaborators with canned responses and verify that they were used correctly in a unit test
If all your methods are using the same Parameters class then maybe it should be a member variable of a class with the relevant methods in it, then you can pass Parameters into the constructor of this class, assign it to a member variable and all your methods can use it with having to pass it as a parameter.
A good way to start refactoring this god class is by splitting it up into smaller pieces. Find groups of properties that are related and break them out into their own class.
You can then revisit the methods that depend on Parameters and see if you can replace it with one of the smaller classes you created.
Hard to give a good solution without some code samples and real world situations.
It sounds like you are not applying object-oriented (OO) principles in your design. Since you mention the word "object" I presume you are working within some sort of OO paradigm. I recommend you convert your "call tree" into objects that model the problem you are solving. A "god object" is definitely something to avoid. I think you may be missing something fundamental... If you post some code examples I may be able to answer in more detail.
Query each client for their required parameters and inject them?
Example: each "object" that requires "parameters" is a "Client". Each "Client" exposes an interface through which a "Configuration Agent" queries the Client for its required parameters. The Configuration Agent then "injects" the parameters (and only those required by a Client).
For the parameters that dictate behavior, one can instantiate an object that exhibits the configured behavior. Then client classes simply use the instantiated object - neither the client nor the service have to know what the value of the parameter is. For instance for a parameter that tells where to read data from, have the FlatFileReader, XMLFileReader and DatabaseReader all inherit the same base class (or implement the same interface). Instantiate one of them base on the value of the parameter, then clients of the reader class just ask for data to the instantiated reader object without knowing if the data come from a file or from the DB.
To start you can break your big ParametresExecution class into several classes, one per package, which only hold the parameters for the package.
Another direction could be to pass the ParametresExecution object at construction time. You won't have to pass it around at every function call.
(I am assuming this is within a Java or .NET environment) Convert the class into a singleton. Add a static method called "getInstance()" or something similar to call to get the name-value bundle (and stop "tramping" it around -- see Ch. 10 of "Code Complete" book).
Now the hard part. Presumably, this is within a web app or some other non batch/single-thread environment. So, to get access to the right instance when the object is not really a true singleton, you have to hide selection logic inside of the static accessor.
In java, you can set up a "thread local" reference, and initialize it when each request or sub-task starts. Then, code the accessor in terms of that thread-local. I don't know if something analogous exists in .NET, but you can always fake it with a Dictionary (Hash, Map) which uses the current thread instance as the key.
It's a start... (there's always decomposition of the blob itself, but I built a framework that has a very similar semi-global value-store within it)

OOP - Where to put the calls to the Data Access Layer?

I am implementing a Data Access Layer (DAL), which is basically a set of classes with (VB.NET) Shared functions to actually execute the database (CRUD) calls. I am trying to figure out the best place to place the calls to the DAL within the class hierarchy. Let me give an example.
Suppose I have a class Customer, with only standard ID, Name, Address1, etc. properties and maybe an overridden ToString function or so. I also have a DAL class with Shared methods, such as:
(pseudocode)
Namespace Dal
Public Class Customer
Public Shared Function Read(id As Integer) As Customer
Public Shared Function ReadList() As List(Of Customer)
Public Shared Sub Create(c As Customer)
'etc.
Now, I could call the Dal from the presentation layer like so:
Me.DataGridView1.Datasource = Dal.Customer.ReadList
However, is it not a good practice to have the presentation layer aware of the Dal at all? Should I instead put methods in the Customer object and call the Dal, like this?
Public Function ReadList() As List(Of Customer)
Return Dal.Customer.ReadList()
End Sub
Public Sub Create()
Dal.Customer.Create(Me)
End Sub
Would this be "cleaner" OOP? Or is it acceptable practice to let the presentation call the Dal, passing the business objects like my previous example:
Me.DataGridView1.Datasource = Dal.Customer.ReadList
Dim c As New Customer
c.Name = "Alpha Corporation"
c.Address1 = "123 Main Street"
Dal.Customer.Create(c)
Thanks for your feedback.
The less your application knows about your DAL the better. There are several ways to do this and I think you are on the right track. I think you might want to look into the factory pattern for this implementation as you will be able to hide the DAL implementation behind the factory and return entities and collections of entities from the factory.
I agree that data calls do not belong in a UI layer. Those are for presentation only.
I think they properly belong in a service layer. The service implementation uses model objects and the persistence layer to accomplish its goals. Whether that's an XML-based web service or local interface, the service is the object that maps to use cases and knows about units of work.
Either put the database calls into a separate persistence layer or embed them in the model objects for extra object-oriented purity.
The reason why'd you want to pull the CRUD operations into a separate layer is in case you ever want to change database systems. Well, that's why I did it. I wouldn't recommend doing this just to be good OOD. But here ya go...
Several sets of classes/interfaces
BusinessObject - Represents business type entities such as a Customer, has DataManager as a property.
DataManager - Maybe you can come up with a better name, but this thing provides Load() and Save() functions for the BusinessObjects
SearchList - Returns lists of things, your SQL queries go here. Also this should probably behave like a RecordSet with Next(), Eof(), and CurrentRecord type members
Constructor/Factory - See FactoryPattern. You've de-coupled your database operations from your business objects this thing re-couples them in a necessary way. Assigns an appropriate datamanager implementation to BusinessObject
Come up with whatever actual names you want, but let's talk about Customer again. Suppose you have an Oracle database. You might end up with these classes:
boCustomer that inherits from BusinessObject
oracleDMCustomer that inherits or implements DataManager
searchlistCustomer that inherits from searchlist that has exposed either through abstract methods or as an interface something like:
SearchAll() - which should return all customer
SearchByZip(String zip) which should return all customers with the given zipcode
oracleSearchlistCustomer - implements searchlistCustomer, would actually implement the SearchAll() and SearchByZip()
boFactory - static class that has a method that looks something like CreateObject(Type type)
searchlistFactory - static class that has a method that looks something like CreateSearchList(Type type);
I'll let you fill in some of the blanks, but I think the important stuff is there. Others may have different ideas that require less abstraction. I'd mock up several strategies before going with one.