Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. Design and Architecture
  4. OO design: Copying data from class A to B

OO design: Copying data from class A to B

Scheduled Pinned Locked Moved Design and Architecture
questiondesignooparchitecturelounge
13 Posts 7 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N Offline
    N Offline
    Nilzor
    wrote on last edited by
    #1

    This is a general and basic question about object oriented design. I've been programming for many years, but just recently I've started realizing many of my old ways of doing stuff is flawed or just plain wrong in terms of good OO design. Simple case: You have class A and class B which have some overlapping properties. You want a method that copies or converts the common properties from class A to class B. Where does the method go? 1) Class A as a B GetAsB() ? 2) Class B as a constructor B(A input)? 3) Class B as a method void FillWithDataFrom(A input)? 4) Class C as a static method B ConvertAtoB(A source)? Thinking of SOLID principles and testability I have a hunch that 4) is the best answer, but I'd like to hear some rationale. Maybe there isn't a definite answer?

    V L I P G 5 Replies Last reply
    0
    • N Nilzor

      This is a general and basic question about object oriented design. I've been programming for many years, but just recently I've started realizing many of my old ways of doing stuff is flawed or just plain wrong in terms of good OO design. Simple case: You have class A and class B which have some overlapping properties. You want a method that copies or converts the common properties from class A to class B. Where does the method go? 1) Class A as a B GetAsB() ? 2) Class B as a constructor B(A input)? 3) Class B as a method void FillWithDataFrom(A input)? 4) Class C as a static method B ConvertAtoB(A source)? Thinking of SOLID principles and testability I have a hunch that 4) is the best answer, but I'd like to hear some rationale. Maybe there isn't a definite answer?

      V Offline
      V Offline
      venomation
      wrote on last edited by
      #2

      I would personally use a static method called "Clone",temp = YourClass.Clone(); Hope it helped... :laugh:

      N 1 Reply Last reply
      0
      • V venomation

        I would personally use a static method called "Clone",temp = YourClass.Clone(); Hope it helped... :laugh:

        N Offline
        N Offline
        Nilzor
        wrote on last edited by
        #3

        Well it's not really a clone. They have SOME overlapping properties, but they are different classes. A concrete example similar to what triggered my question: I have a MVC-project where the model class is class A and the ViewModel is class B:

        class Model
        {
        string Name;
        string Timestamp; // Format: MMDDYYY
        string Token;
        }

        class ViewModel
        {
        string Name;
        DateTime Timestamp;
        }

        I am not interested in showing the Token, and the Timestamp has to be converted to a DateTime class, which then is presented better by the .NET framwork's DateTime.ToString(). Where do I do the conversion? Now if I put the code in either Model or ViewModel, I will introduce a dependecy between the Model and the ViewModel. If my Model-class changes, the ViewModel must change. So my question is really if that is always a bad thing (option 1,2 or 3 from the original post). Don't they have an intrinsic dependency anyway?

        K 1 Reply Last reply
        0
        • N Nilzor

          This is a general and basic question about object oriented design. I've been programming for many years, but just recently I've started realizing many of my old ways of doing stuff is flawed or just plain wrong in terms of good OO design. Simple case: You have class A and class B which have some overlapping properties. You want a method that copies or converts the common properties from class A to class B. Where does the method go? 1) Class A as a B GetAsB() ? 2) Class B as a constructor B(A input)? 3) Class B as a method void FillWithDataFrom(A input)? 4) Class C as a static method B ConvertAtoB(A source)? Thinking of SOLID principles and testability I have a hunch that 4) is the best answer, but I'd like to hear some rationale. Maybe there isn't a definite answer?

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #4

          Nilzor wrote:

          You have class A and class B which have some overlapping properties.

          That's one way to describe it. What happens when I say that the overlapping properties are class BaseAB, and that both class A and Class B inherit that? ..or call the shared properties Class SharedStuff and nest it as a property in both Class A and Class B.

          Nilzor wrote:

          Maybe there isn't a definite answer?

          There's never a definite answer :)

          I are Troll :suss:

          N 1 Reply Last reply
          0
          • N Nilzor

            This is a general and basic question about object oriented design. I've been programming for many years, but just recently I've started realizing many of my old ways of doing stuff is flawed or just plain wrong in terms of good OO design. Simple case: You have class A and class B which have some overlapping properties. You want a method that copies or converts the common properties from class A to class B. Where does the method go? 1) Class A as a B GetAsB() ? 2) Class B as a constructor B(A input)? 3) Class B as a method void FillWithDataFrom(A input)? 4) Class C as a static method B ConvertAtoB(A source)? Thinking of SOLID principles and testability I have a hunch that 4) is the best answer, but I'd like to hear some rationale. Maybe there isn't a definite answer?

            I Offline
            I Offline
            Ian Shlasko
            wrote on last edited by
            #5

            I usually opt for something similar to #4, but put the static method inside B so it can work like a factory constructor... B newObject = B.FromA(original); But since you mentioned in your other reply that these are two different layers, well... Depends on: 1) How much interaction you're allowing between your layers 2) Which layer is dependent, if any (If A depends on B, then A can have code that converts to/from B) I work mostly in WPF, which is best done with MVVM... I tend to put translation-type logic in the ViewModel, since that's dependent on the data model (But the data model knows nothing about the viewmodel).

            Proud to have finally moved to the A-Ark. Which one are you in?
            Author of the Guardians Saga (Sci-Fi/Fantasy novels)

            1 Reply Last reply
            0
            • L Lost User

              Nilzor wrote:

              You have class A and class B which have some overlapping properties.

              That's one way to describe it. What happens when I say that the overlapping properties are class BaseAB, and that both class A and Class B inherit that? ..or call the shared properties Class SharedStuff and nest it as a property in both Class A and Class B.

              Nilzor wrote:

              Maybe there isn't a definite answer?

              There's never a definite answer :)

              I are Troll :suss:

              N Offline
              N Offline
              Nilzor
              wrote on last edited by
              #6

              Inheritance wasn't even in my mind. Although it wouldn't be the best choice in the specific case i mentioned in my second post, it definitely shows there are many ways to solve this - it depends on the case. Thanks for your and Shlasko's input!

              1 Reply Last reply
              0
              • N Nilzor

                This is a general and basic question about object oriented design. I've been programming for many years, but just recently I've started realizing many of my old ways of doing stuff is flawed or just plain wrong in terms of good OO design. Simple case: You have class A and class B which have some overlapping properties. You want a method that copies or converts the common properties from class A to class B. Where does the method go? 1) Class A as a B GetAsB() ? 2) Class B as a constructor B(A input)? 3) Class B as a method void FillWithDataFrom(A input)? 4) Class C as a static method B ConvertAtoB(A source)? Thinking of SOLID principles and testability I have a hunch that 4) is the best answer, but I'd like to hear some rationale. Maybe there isn't a definite answer?

                P Offline
                P Offline
                Pete OHanlon
                wrote on last edited by
                #7

                Option 5. Create an interface that encapsulates the properties, and have both classes implement the interface. Use that as the basis of filling the properties.

                I'm not a stalker, I just know things. Oh by the way, you're out of milk.

                Forgive your enemies - it messes with their heads

                My blog | My articles | MoXAML PowerToys | Onyx

                1 Reply Last reply
                0
                • N Nilzor

                  Well it's not really a clone. They have SOME overlapping properties, but they are different classes. A concrete example similar to what triggered my question: I have a MVC-project where the model class is class A and the ViewModel is class B:

                  class Model
                  {
                  string Name;
                  string Timestamp; // Format: MMDDYYY
                  string Token;
                  }

                  class ViewModel
                  {
                  string Name;
                  DateTime Timestamp;
                  }

                  I am not interested in showing the Token, and the Timestamp has to be converted to a DateTime class, which then is presented better by the .NET framwork's DateTime.ToString(). Where do I do the conversion? Now if I put the code in either Model or ViewModel, I will introduce a dependecy between the Model and the ViewModel. If my Model-class changes, the ViewModel must change. So my question is really if that is always a bad thing (option 1,2 or 3 from the original post). Don't they have an intrinsic dependency anyway?

                  K Offline
                  K Offline
                  Keld Olykke
                  wrote on last edited by
                  #8

                  In your concrete example, I would let the ViewModel have a reference to the Model. In this way, you hint that the ViewModel is in sync with the Model and you don't have to duplicate data. If you consider DateTime strictly as a presentation data type, the data model should NOT know about it. Hence, you need to put DataTime operations outside the data model e.g. in ViewModel or a data type converter. To illustrate this cut, imagine that you MUST put your model code into 1 library and MUST put view model code into another library. Furthermore, the view model MUST know the data model, but the data model SHOULD NOT know the view model. This is the classic MVC pattern: http://en.wikipedia.org/wiki/Model%E2%80%93View%E2%80%93Controller[^] With all that background info, either or both of the following conversion services would work: Model model = new Model(); model.Timestamp = "0227011"; DateTime timestamp = model.Timestamp; // model implementation converts it and DateTime is a model data type ViewModel viewModel = ViewModel(model); DateTime timestamp = viewModel.Timestamp; // presentation implementation converts it and DateTime is a presentation type Hope it makes some sense!

                  N 1 Reply Last reply
                  0
                  • K Keld Olykke

                    In your concrete example, I would let the ViewModel have a reference to the Model. In this way, you hint that the ViewModel is in sync with the Model and you don't have to duplicate data. If you consider DateTime strictly as a presentation data type, the data model should NOT know about it. Hence, you need to put DataTime operations outside the data model e.g. in ViewModel or a data type converter. To illustrate this cut, imagine that you MUST put your model code into 1 library and MUST put view model code into another library. Furthermore, the view model MUST know the data model, but the data model SHOULD NOT know the view model. This is the classic MVC pattern: http://en.wikipedia.org/wiki/Model%E2%80%93View%E2%80%93Controller[^] With all that background info, either or both of the following conversion services would work: Model model = new Model(); model.Timestamp = "0227011"; DateTime timestamp = model.Timestamp; // model implementation converts it and DateTime is a model data type ViewModel viewModel = ViewModel(model); DateTime timestamp = viewModel.Timestamp; // presentation implementation converts it and DateTime is a presentation type Hope it makes some sense!

                    N Offline
                    N Offline
                    Nilzor
                    wrote on last edited by
                    #9

                    Thank you, this makes sense yes. Usually one don't have to worry about dependencies going downward in the project hierarchy, I guess. It's all this new IoC-trend that just got me rethinking a lot of the old paradigms. Another thing - slightly related: What do you (or anyone else who care to answer) think about referencing the Name property from the Model in the ViewModel directly, instead of copying it? Would this breach some kind of archictecture/dependency principle? So...: class ViewModel { public Model ModelInstance public DateTime Timestamp; } This way the View accesses the Name property directly on the model through the ViewModel. If ASP.NET: <¤= ViewModelInstance.ModelInstance.Name %> I read an article by Rockford Lhotka[^], creator of the CSLA framework, that encourages such an architecture. I'm not convinced everybody agrees, but I kind of like it. It minimizes property duplication. See in particular the chapter "ViewModel as Action Repository".

                    K 1 Reply Last reply
                    0
                    • N Nilzor

                      Thank you, this makes sense yes. Usually one don't have to worry about dependencies going downward in the project hierarchy, I guess. It's all this new IoC-trend that just got me rethinking a lot of the old paradigms. Another thing - slightly related: What do you (or anyone else who care to answer) think about referencing the Name property from the Model in the ViewModel directly, instead of copying it? Would this breach some kind of archictecture/dependency principle? So...: class ViewModel { public Model ModelInstance public DateTime Timestamp; } This way the View accesses the Name property directly on the model through the ViewModel. If ASP.NET: <¤= ViewModelInstance.ModelInstance.Name %> I read an article by Rockford Lhotka[^], creator of the CSLA framework, that encourages such an architecture. I'm not convinced everybody agrees, but I kind of like it. It minimizes property duplication. See in particular the chapter "ViewModel as Action Repository".

                      K Offline
                      K Offline
                      Keld Olykke
                      wrote on last edited by
                      #10

                      Your most welcome. Yes, I am all for the approach with a Model reference in the ViewModel. Thx for the link. I like the discussion. The MVVM architecture is however not my best friend (though very popular these days). I prefer MVC with the a twist, where the C stands for Command (think a simple Controller that performs a specific Algorithm). The Command Pattern is classic, but I have not seen much recent discussion about it, but here is a link with a little discussion: http://c2.com/cgi/wiki?CommandObject[^] Since a Command can be both a Controller and Algorithm, you have a single class with the full responsibility (and all the code) of getting a specific task done. When you got a bug, you know where to look. You automatically re-use code, since you just run the existing commands or combine them into composite commands e.g. sequences or parallels. When you think about it, most tasks can be specified as a command or composite commands: request, sleep, set, create, delete, save, undo, shutdown, etc. Execution of commands is a topic on its own, just like execution of CPU/VM instructions, fibers, threads, jobs, etc. In the MVC, I let M be the model, let the V be the View that listen on the model and let the C be the commands that changes the model. Both the model and view may issue commands. If you don't like the Observer pattern, the view can be modified by commands that are called from model commands. Just like Rockfor Lhotka suggests in "ViewModel as Action Repository", I create MVC layers when its makes sense e.g. when in need of faster response and I create a MVC subsystem when it makes sense in terms of a "black box" e.g. an application, a view or a dialog. I hope above triggered some thoughts.

                      1 Reply Last reply
                      0
                      • N Nilzor

                        This is a general and basic question about object oriented design. I've been programming for many years, but just recently I've started realizing many of my old ways of doing stuff is flawed or just plain wrong in terms of good OO design. Simple case: You have class A and class B which have some overlapping properties. You want a method that copies or converts the common properties from class A to class B. Where does the method go? 1) Class A as a B GetAsB() ? 2) Class B as a constructor B(A input)? 3) Class B as a method void FillWithDataFrom(A input)? 4) Class C as a static method B ConvertAtoB(A source)? Thinking of SOLID principles and testability I have a hunch that 4) is the best answer, but I'd like to hear some rationale. Maybe there isn't a definite answer?

                        G Offline
                        G Offline
                        GParkings
                        wrote on last edited by
                        #11

                        just to clarify what you are asking, Class A has properties X and Y Class B has properties Y and Z given an instance of class A such that X = i and Y = j an instance of class B such that Y = k and Z = l you would like to achieve a modification to the state of class A such that X = i and Y = k is that correct? 1. would not achieve this, it could only result in an instance of class A where Y = k and X = default(x) 2. likewise this would not be able to set the X property 3. This could achieve the result you are after, it would copy values for common properties from the argument instance to the instance of the class on which the method is hosted 4. as with 1 and 2 this would not be able to populate the X property so, if the initial assumptions of your question are correct, i would go with option 3 ;p either that or I've misunderstood completely and have resorted to flinging answers at a non-existent hypothetical question, sadly that wouldn't be the least productive thing I've done today....

                        N 1 Reply Last reply
                        0
                        • G GParkings

                          just to clarify what you are asking, Class A has properties X and Y Class B has properties Y and Z given an instance of class A such that X = i and Y = j an instance of class B such that Y = k and Z = l you would like to achieve a modification to the state of class A such that X = i and Y = k is that correct? 1. would not achieve this, it could only result in an instance of class A where Y = k and X = default(x) 2. likewise this would not be able to set the X property 3. This could achieve the result you are after, it would copy values for common properties from the argument instance to the instance of the class on which the method is hosted 4. as with 1 and 2 this would not be able to populate the X property so, if the initial assumptions of your question are correct, i would go with option 3 ;p either that or I've misunderstood completely and have resorted to flinging answers at a non-existent hypothetical question, sadly that wouldn't be the least productive thing I've done today....

                          N Offline
                          N Offline
                          Nilzor
                          wrote on last edited by
                          #12

                          either that or I've misunderstood completely and have resorted to flinging answers at a non-existent hypothetical question, sadly that wouldn't be the least productive thing I've done today....

                          At least this made me laugh - I'm sorry but your initial assumptions is wrong ;-) But who knows- maybe some guy in Taiwan or Botswana Google's the question you answered, and it will come to use after all! I do realize my question was a bit unclear. This is the initial state I was thinking of: an instance of class A such that X = i and Y = j There is no class B - I want to create a NEW class B, with the values of the common properties from A set, and the other default. So if class B has property Y and Z, whatever method we chose, the result should be a class B with Y = j and Z = (default)

                          G 1 Reply Last reply
                          0
                          • N Nilzor

                            either that or I've misunderstood completely and have resorted to flinging answers at a non-existent hypothetical question, sadly that wouldn't be the least productive thing I've done today....

                            At least this made me laugh - I'm sorry but your initial assumptions is wrong ;-) But who knows- maybe some guy in Taiwan or Botswana Google's the question you answered, and it will come to use after all! I do realize my question was a bit unclear. This is the initial state I was thinking of: an instance of class A such that X = i and Y = j There is no class B - I want to create a NEW class B, with the values of the common properties from A set, and the other default. So if class B has property Y and Z, whatever method we chose, the result should be a class B with Y = j and Z = (default)

                            G Offline
                            G Offline
                            GParkings
                            wrote on last edited by
                            #13

                            In that case i feel it depends on the nature of the class The constructor approach should be used if: - Class A is logically a component of class B (e.g. A = Engine, B = car), although in this case i would prefer an instance of class A within the state of class B rather than copies of its state values being placed into the state values of class B - The information in class A is (in part) mandatory for the creation of class B The instance method approach should be used if: - The logical functionality of the entity represented by class B is such that it would be expected to replace its state with that of class A (e.g. A = location, B = car, B.DriveTo(A) sets common 'lat/long' properties) The static method should be used in other cases Thats my view at least :D

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups