I have a class named Product
, which takes a product model number and number of wheels for that product as part of its creation information, and then it instantiates the product by doing a computation on the number of wheels and on various base parameters
For example, Product(5, 22)
creates a model 5 product with 22 wheels on it, where that particular product's weight and dimensions are computed from the number of wheels and from the base specifications for that model number. Right now base specifications are part of the class itself and are hardcoded into the class, along with the computation formulas.
My Issue: in the (legacy) code I am working with, I cannot always use the model number directly. It may not be available. Instead, an unrelated product_id
is given, where the link between product_id
and model_number
is in the database.
I want to keep my class as simple as possible. As such I do not want to introduce another constructor that allows product_id
as an input parameter, in addition to the existing model_number
, as it will be duplication of code. Also, I am not too keen on putting database logic inside the class, but maybe I can, as thinking about it now, this may be a good candidate for a database-wrapper class, i.e. active record (where my base specifications can be moved off from the code and into the database).
Question: How do I create and return the object while following good object oriented principles when the model_number
I typically use for its creation is not available, but another parameter is available instead (product_id
in this case), which links 1:1 to model_number
?
Sample solutions that I don't quite like:
- Do not involve the database -- since I am working with just a few Products at this time, and Products do not change often, I can create a "conversion function" that serves as a map between
product_id
andmodel_number
and not touch the database. Similarly, create aConvert
object that has same functionality and use it before creating the object. Problem: duplicating DB functionality in the code. - Put DB functionality inside code and add alternate constructor. Problem: multiple entry-points of Product creation for the class create code duplication.
Update:
There basically are 3 aspects here:
- base data (whether hardcoded or part of the database)
- finding base data by various parameters be it model number or other identifying information
- doing computation using base data as per model number