简体   繁体   中英

One to one relationships in UML diagrams

I am new to UML diagrams and reading a book about it. There it has a class diagram like the following:

在此处输入图片说明

And it says that,

The implication of a one to one association is that whenever you create an 
instance of one of the classes, you must simultaneously create an instance 
of the other, and when you delete one you must delete the other.

My question is, do we really have to do this? Can't we give "null" as a value to one of these? For example, i am thinking of the java code of this diagram like the following, and when i want to create a Company item, i can give null as the parameter. Am i wrong? Or is this a bad or wrong piece of code?

public class Company{
       . . .
    private BoardOfDirectors director;
    public Company(BoardOfDirectors director){
          this.director=director;

    }
       . . .
}

public class BoardOfDirectors{
       . . .
   private Company company;
   public BoardOfDirectors(Company company){
          this.company=company;

   }
       . . .
}

Thank you.

This all depends on the business rules in place behind the UML. Instead of NULL you may want to create the object that explains that there is no board of directors at this time. This would be wise if at a later time the company object decides that it wants to create a board of directors. Then you can store these inside an array of one another. In this way you are storing objects inside another object.

I have created programs where we store objects inside objects inside objects and so on. This allows for persistent code to be used and can serialize the state. Then you can have the arrays iterate through and maintain the cardinality of the UML diagram.

Really you must take in the business rule for the project, apply the cardinality and modeling behind the entities, and try to mimic this reality. From what I was taught in school our job is to mimic reality and treat this as real life so that our code makes more sense. It will be easier to understand and maintain in the long run. Though I do break this rule from time to time for the sake of speed, but that is how bad code starts to form.

Check out http://uml.org if you have not already.

Cheers!

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