Is it good or not to have temporary fields to save costly work between modules
-
22-06-2021 - |
题
I have:
- Raw Object: contains raw data before importing to the system
- Module #1: Validator which will validate Raw Objects
- Module #2: Updater which will use validated raw data (invalid data were removed) to generate Real Objects
Module #1 has to determine whether ItemCode (just an example, the actual number of keys are dozens) exists in the database or not. Module #2 has to get the Item object by querying ItemCode in the database.
A developer wants to add an alien property .TempItem to the raw object so that the Module #1 will assign the Item object to .TempItem property (because it is super easy to do that) and Module #2 just needs to use .TempItem without querying the database second time.
My technical expert advises that it is not good.
I want to follow programming principles and best practices but have no idea how.
Any help is appreciated.
解决方案
What you have with Module #1 and #2 is a pipeline process. The output of #1 passes into #2. Any information that #2 needs which #1 has already ascertained can (arguably should) be cached.
I would create an additional object to pass this state information through the pipeline (@astander suggests a dictionary, but in many cases a hard-coded object that stores precisely the data you need will be simple to write and much more usable/maintainable)
Using a "tempitem" is essentially the same mechanism, but a poor implementation of it - the idea is the same though (don't read the same information from the database multiple times)
By passing a state object through your pipeline you keep the pipeline processors loosely coupled (#2 doesn't need to know about #1, it simply acts on the state information that is passed in), which makes it easier to add new pipeline stages or refactor your modules in future. By passing the data within a separate class, it also makes it really easy to add new state data to be passed through the system.
其他提示
I dont think you need to add the temp item to the raw object.
You could use caching, and store the object in a dictionary/list and pass that along to Module2 to be used for lookup.
In Module2 then you can check if the object is in the cached dictionary/list (the dictionary should be easier as you can lookup the value based on the key) and if it is not present, then only load it from the database.