2

I am busy developing code that processes a bunch of objects that represent monthly reports for regions (e.g. one instance per region per month). Let's call them RegionMonthlyReport objects. At the end of the month, a new set of RegionMonthlyReports need to be created for the next month that are populated with values from certain fields from the original RegionMonthlyReports.

In part of my code, these copies will be saved to the database, such that we have a time-phased full set of regions per month: say we had 10 regions, we'd have 10 records for a single month; after a full year of this, we'll have 10 regions x 12 months = 120 records.

My question is, where should I implement a method to make the 'copy' of the RegionMonthlyReport object, and what are the pros/cons of a preferred approach? Should it be

  • A method on the RegionMonthlyReport itself, like RegionMonthlyReport.CreateCopy(newMonth)
  • A static method in a utility class, like StaticUtilityClass.CreateRegionMonthlyReportCopy(sourceRegionMonthlyReport, newMonth)
  • Something else

Note that I'm not talking about any Copy method in a framework. This is a solution design question. FWIW I'm developing in .NET/C#

This question seems to be somewhat relevant - and indicates that the second option might be better - but I'm too much of a beginner to confidently generalise to my case.

sasfrog
  • 253
  • 1
  • 6

2 Answers2

5

The intuitive way to do it is to create a copy in the object itself. Here some arguments:

  • who knows better than the object what is to be copied ?
  • who has a better (controlled) access to the objects member than the object itself ?
  • mainstream oo languages allow to define copy constructors or assignment operators in the object itself.
  • the prototype pattern that is based on object cloning also relies on an object operation.

This approach is robust and proven, and implements separation of concerns.

If you have several independent objects that you need to copy (e.g. regional reports ?), you can nevertheless have a copy service that ensures that all relevant objects are copied at the same time. This service should nevertheless rely on the object copy method for its implementation.

Christophe
  • 74,672
  • 10
  • 115
  • 187
3

In addition to it being "intuitive" to copy in the object itself, (@Christophe answer) the GRASP "Information expert" principle supports that decision.

"Information expert will lead to placing the responsibility on the class with the most information required to fulfill it". In this case, the class itself.

user949300
  • 8,679
  • 2
  • 26
  • 35