title: Java: How to marry JPA and high-level business rules? (Bounded contexts)
body: <h2>Question context</h2>
  
  <p>So I organized my application into bounded contexts (Eric Evans' "domain-driven design"). One of the bounded contexts is the "gameplay context." It, for instance, contains an interface <code>Gamer</code></p>
  
  <pre><code>public interface Gamer {
      void setFriends(Set&lt;Gamer&gt; friends);
      Set&lt;Gamer&gt; getFriends();
      ....
  }
  </code></pre>
  
  <p>There is also an implementation that is able to persist a <code>Gamer</code>'s state to a database.</p>
  
  <pre><code>@Entity
  public class JpaGamer implements Gamer {
      private String someData;
      private String someSensitiveData;
  
      public setFriends (Set&lt;Gamer&gt; friends) {
          ...
      }
  
      ...
  }
  </code></pre>
  
  <p>Far, far away, inside another bounded context called "accounts context," I have classes and interfaces that deal with the users of my application. For instance, there is an interface called <code>Account</code>. </p>
  
  <pre><code>public interface Account{
      boolean isSignedUp();
      ....
  }
  </code></pre>
  
  <p>So a user / <code>Account</code> can be signed up or not. For any <code>Account</code>, there exists a corresponding <code>Gamer</code>.</p>
  
  <h2>Challenge</h2>
  
  <p>I have a business rule: <strong><em>Never</strong> persist <strong>sensitive</strong> data anyhow related to a <strong>non-signed-up</strong> <code>Account</code>.</em>  </p>
  
  <p>For example, this means that some non-signed-up <code>Account</code>'s  <code>JpaGamer</code> instance cannot write data to the <code>someSensitiveData</code> field. You could informally say that this <code>JpaGamer</code> is a "<em>non-signed-up <code>JpaGamer</code></em>".</p>
  
  <p>I don't want to hardcode any accounts-related logic into anything gameplay-related (and the same the other way around).  </p>
  
  <p>How can I implement such business rules in Java without tainting either bounded context with concepts from the other bounded context?</p>
  
  <p>To fulfill the business rule, I have the idea that whenever there is a "non-signed-up <code>JpaGamer</code>", I wrap that <code>JpaGamer</code> inside a <code>SparsePersistingGamer</code>. The <code>SparsePersistingJpaGamer</code> would simply not forward to the underlying <code>JpaGamer</code> any method that could potentially tamper with <code>someSensitiveData</code>.<br>
  But now I have a problem with the <code>someGamer.getFriends()</code> method. For the <code>SparsePersistingGamer</code>, it would lazily load all that gamer's friends from JPA, returning a set of plain <code>JpaGamer</code>s that are not aware of the (and any other) business rule, therefore persisting <code>someSensitiveData</code> for potentially "non-signed-up <code>JpaGamer</code>s".</p>
  
  <p>Which strategies do you apply to tackle similar and related situations?</p>