|
| 1 | +--- |
| 2 | +title: Connection |
| 3 | +parent: Examples |
| 4 | +nav_order: 6 |
| 5 | +permalink: /examples/connection/ |
| 6 | +description: A typestate protocol with a value-dependent conditional transition. |
| 7 | +--- |
| 8 | + |
| 9 | +# Connection |
| 10 | + |
| 11 | +This example models a small object protocol where the target state of `connect` depends on a boolean parameter. Because the transition is value-dependent, this protocol does not encode to a DFA based only on the current state and method call. |
| 12 | + |
| 13 | +```java |
| 14 | +import liquidjava.specification.*; |
| 15 | + |
| 16 | +@StateSet({"disconnected", "guest", "authenticated"}) |
| 17 | +public class Connection { |
| 18 | + @StateRefinement(to="disconnected()") |
| 19 | + public Connection() {} |
| 20 | + |
| 21 | + @StateRefinement(from="disconnected()", to="hasToken ? authenticated() : guest()") |
| 22 | + public void connect(boolean hasToken) {} |
| 23 | + |
| 24 | + @StateRefinement(from="guest() && hasToken", to="authenticated()") |
| 25 | + public void authenticate(boolean hasToken) {} |
| 26 | + |
| 27 | + @StateRefinement(from="authenticated()") |
| 28 | + public void sendData() {} |
| 29 | + |
| 30 | + @StateRefinement(from="guest() || authenticated()", to="disconnected()") |
| 31 | + public void disconnect() {} |
| 32 | +} |
| 33 | +``` |
| 34 | + |
| 35 | +```java |
| 36 | +Connection conn = new Connection(); |
| 37 | +conn.connect(true); |
| 38 | +conn.sendData(); |
| 39 | +conn.disconnect(); |
| 40 | +``` |
| 41 | + |
| 42 | +```java |
| 43 | +Connection conn = new Connection(); |
| 44 | +conn.connect(false); |
| 45 | +conn.sendData(); // State Refinement Error |
| 46 | +``` |
| 47 | + |
| 48 | +LiquidJava enforces the intended protocol: |
| 49 | + |
| 50 | +- The `connect` method can be called from `disconnected()`, and the target state depends on the value of `hasToken` |
| 51 | +- The `authenticate` method can only be called from `guest()`, and only transitions to `authenticated()` if `hasToken` is true |
| 52 | +- The `sendData` method can only be called from `authenticated()` |
| 53 | +- The `disconnect` method can be called from either `guest()` or `authenticated()`, and always transitions back to `disconnected()` |
0 commit comments