简体   繁体   中英

Better approach for implementing 2 similar classes

I am importing and exporting from the XPDL standard using C#.

I have written a hierarchy for classes using XPDL 2.1 and have debugged serialization with XmlSerializer . I need to implement XPDL 2.2 .

The structure of the classes has changed. There are additional parameters as well. There was list of Artifacts which was child of the root class, but the newer version lost DataObject from all of Artifacts. The DataObjects moved from an additional List into WorkflowProcess .

I need to support XPDL 2.1 and XPDL 2.2 . What is the best way to implement both of them?

I can see 3 ways:

  1. Copy and paste existing hierarchy with needed fixes (it is awful!)
  2. Create a base class and create two child classes. One for 2.1 and another for 2.2 (but will not it be too complex to maintain?)
  3. Implement conditional serialization using an enum variable. The class will contain the super-set of 2.1 and 2.2 (This option seems overly complex)

Please let me know if there is a better approach.

Create two additional seperate projects in your solution. The first should contain classes to be parsed from XPDL 2.1.

The second one is for 2.2, it should include all cs files from first's project folder as links. Instead of managing them manually add these lines to your second project file:

<Compile Include="..\ParserXPDL21\Classes\**\*.cs">
  <Link>Classes\file.cs</Link>
</Compile>

Remember to reload the second project each time you add or remove files from the first, otherwise Visual Studio will not compile it until you do.

For the second project declare a conditional constant in the project properties: XDPL22

Now you can modify the first project files like this to maintain two versions in the same file:

#if !XDPL22
namespace ParserXPDL21
#else
namespace ParserXPDL22
#endif
{
    [Serializable]
    public class Root
    {
#if !XDPL22
        public Artifact[] Artifacts { get; set; }
#endif
        public int NormalProperty1 { get; set; }
        public int NormalProperty2 { get; set; }
        public int NormalProperty3 { get; set; }

    }
}

After that you can reference these two projects from your main project and use the classes for the two different versions.

I know it doesn's seem to be a very elegant way but it helps when you have to make a lot of duplicated code.

You still need a way to check what version of XPDL you are going to read. May be you can just look at the file extension but if it's the same than you can just try to read 2.2 and if it throws an exception or the data is not correct think this is 2.1, or you can read XML manually with XmlReader and check before deserializing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM