Object-Oriented Design – Wrapping Related Properties in Struct/Class

cdata structuresjavaobject-orientedswift-language

Writing a User object in Swift, though my question relates to any strongly typed language. A User can have a bunch of links (FacebookProfile, InstagramProfile, etc). A few questions around this.

  1. Is it good practice to wrap links in their own object?
    struct User {
       var firstName: string
       var lastName: string
       var email: string
       var links: Links
    }
    struct Links {
       var facebook: string
       var instagram: string
       var twitter: string 
    }

Or should they be loose? I know technically both ways are fine, but wondering if there is a recommended approach, in general–especially for readability.

struct User { 
   var firstName: string
   var lastName: string
   var email: string
   var facebookLink: string
   var twitterLink: string
   var instagramLink: string
}
  1. In a scenario like this, should links be a collection/list? I figured it should not be a list because there is a fixed number of link options available, and not a growing number. Is my thinking right?

  2. Is it good practice to place my networking methods inside the User object, like getUsers, getUser, updateUser?

I know these could be subjective, but I am trying to understand what the best practice around similar situations is. Would appreciate any pointers.

Best Answer

You will either need

  • zero of a thing,
  • one of a thing, or
  • an arbitrary number of the thing.

I'm shocked that your design predicts that the number of needed links will always be three and that you know what their names are forever.

What I'm preaching is called the zero one infinity rule. It might not be obvious at first but it's what tells me your design is not future tolerant.

I'd feel differently if there was something about these links that was special to them. Some special thing that I do different when accessing a facebook link that I don't do for a twitter link. That would make them different things. But that isn't indicated in this code.

That's why I'm not bothered by the email string. I know that is used in a different way then the links.

So until I see a reason to use these links differently I'm on the side of a link collection.