Ben
Ben

Reputation: 21625

How to set up classes to model one-to-many relationship with at least one object in the range set

Suppose you want to model the following situation using OOP. You want to have a User class, an Album class, and a Photo class, such that

A User has 0 or more Albums
An Album has 1 or more Photos

Because I'm requiring an Album to have at least one Photo, I thought I should put a List<Photo> photos argument in the constructor of my Album class. However, this would assume that a list of Photo objects are created before the parent Album class is created. So, I cannot include a Album parentAlbum argument in the constructor of my Photo class like I was planning.

What is the best way for me to design so that each photo can reference it's parent album, but an album cannot be created without any photos?

Upvotes: 0

Views: 59

Answers (1)

musical_coder
musical_coder

Reputation: 3896

Strictly speaking, I actually think you shouldn't reference the parent Album from a Photo instance, because: a) a photo doesn't need an album to exist, and b) you're limiting the re-usibility of Photo in the future. If you can come with a way to remove that reference, I'd do it. You could instead find the parent Album by searching through each Album you have, or better yet, create a dictionary of photos to albums.

That being said, I've definitely done similar things myself, because it makes coding a whole lot easier :) This doesn't set the parent Album in Photo's constructor, but it's probably the next best thing:

class Album {

    public Album (List<Photo> photos)
    {
        if (photos.Count < 1)
        {
            throw new Exception("Album must have at least one photo.");
        }

        foreach (Photo thisPhoto in photos)
        {
            thisPhoto.setAlbum(this);
        }
    }

}

Upvotes: 1

Related Questions