简体   繁体   中英

What is the right code generation for a composition

I was trying to look for the correct solution to generate classes code based on composition.

组成

From the representation above, and using 2 tools (MagicDraw and Enterprise Architect) I got 2 different code generation for the Person.h file:

MagicDraw :

class Person
{   
    int age;    
    string fname;   
    Head haveHead;  
    string lname;   
};

Enterprise Architect :

class Person
{

public:
    Person();
    virtual ~Person();
    Head *m_Head;

private:
    int age;
    string fname;
    string lname;

};

So in MagicDraw I have a class member of Head but in the Enterprise Architect code I have a pointer?

I know that Head is part of the Person object and its existence is managed by the Person object ... So I guess that the code generated by MagicDraw is more appropriate.

My question is the code generated by Enterprise correct too?

In case of both correct, which is the best among them?

I don't think one is better than the other. There is really no answer to such questions usually unless you compare two things, one of which is extremly inferior to the other, but there are a couple things to note here.

Enterprise Architect made m_head public (I don't want everyone to have access to my head!). Unless you want and need it to be public (there are better ways than making it public, though), it's undesirable. Additionaly, it's a pointer, so one head can be assigned to more than one person, but you may need it, as suggested in the comments by @coredump, to access a subclass of Head at runtime. Also this version enforces memory management on your own. You need to dynamically allocate during construction and then clean up after yourself. However, moving this version is cheaper if Head is not trivially movable and possible even if Head is not movable for some bizzare reason.

Magic Draw's version made everything private, so no access to someone's head. One head belongs to only one person. Memory is managed automatically. Moving is more expensive if Head is not trivially movable and not possible if Head is not movable.

You should choose whichever fits your needs the best.

Also in my opinion the version of MagicDraw is more correct, at least from a semantical point of view. The key point is that the relation 1 <-> 1 is more explicitly stated in this case, and it can't be abused . In the other case you can potentially relate more than one Head to a particular Person .

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