title: Java: Enforcing doubly linked objects
body: <p>I am designing a game engine in Java.</p>
  
  <p>At the core of this engine exist the two classes Asset and Attribute, where an Asset has a list of Attributes. Most Attributes need no link back up to their Attribute, meaning that Attributes can and often do appear in the lists of more than one Asset. However, there is an extention of Attribute called UniqueAttribute, which is an implementation for those that are specific to their Asset, and utilise a link back.</p>
  
  <ol>
  <li><p>Ideally, my Asset's addAttribute method would look something like this if I cut out the other code:</p>
  
  <pre><code>public void addAttribute(Attribute attribute){
    if(attribute instanceof UniqueAttribute)
      ((UniqueAttribute)attribute).setAsset(this);
    attributeList.add(attribute);
  }
  </code></pre>
  
  <p>Unfortunately, since they live in different packages, UniqueAttribute.setAsset() must be public. This leaves the method open to outside users of the engine to mess with, and while I could just handwave it off by saying using this method directly is a bug - it seems rather sloppy.</p></li>
  <li><p>The second option is to provide the UniqueAttribute with the Asset on construction, meaning that the code at the point of creation would look something like this:</p>
  
  <pre><code>asset.addAttribute(new UniqueAttribute(asset));
  </code></pre>
  
  <p>While I can add a check-and-throwable or assert to confirm the correct asset is passed in, I am basically relying on the user to connect the two, which I also would prefer not to do.</p></li>
  <li><p>The third option is to bite the bullet and put 50 java files all into the same package so that I can just use the standard visiblity.</p></li>
  </ol>
  
  <p>Is there some kind of pattern or something that will help link these two together without exposing the wires, or forcing me to put everything into one massive package?</p>
  
  <p><em>Irrelevant rant: I have always disliked that the concept of subpackages in java has not really been expanded in any meaningful way. A subpackage, as far as java is concerned is simply a different package, and there have been many occasions I could do with more visibility modifiers directly related to this.</em></p>