package scratchlib.objects;

/**
 * Represents either an object or its reference, if not yet resolved.
 */
public class ScratchOptionalField
{
    private int referenceID = -1;
    private ScratchObject value;

    /**
     * Constructor for when the reference is not yet resolved.
     * 
     * @param referenceID The unresolved reference ID.
     */
    public ScratchOptionalField(int referenceID)
    {
        this.referenceID = referenceID;
    }

    /**
     * Constructor for when there already is a value.
     * 
     * @param value The field value.
     */
    public ScratchOptionalField(ScratchObject value)
    {
        this.value = value;
    }

    /**
     * @return The object this field refers to, if it exists.
     * @throws IllegalStateException If not yet resolved.
     */
    public ScratchObject get()
    {
        if (value == null) {
            throw new IllegalStateException("reference field unresolved");
        }
        return value;
    }

    /**
     * @return Whether this field is resolved, i.e. has a value.
     */
    public boolean isResolved()
    {
        return value != null;
    }

    /**
     * @return This field's reference ID, if available.
     */
    public int getReferenceID()
    {
        return referenceID;
    }

    /**
     * If this field has an associated reference ID, looks up the object it
     * points to from the given table and stores it as this field's value.
     * 
     * @param ref The reference lookup table.
     */
    public void resolve(ScratchReferenceTable ref)
    {
        if (referenceID < 0) {
            return;
        }
        this.value = ref.lookup(referenceID);
    }
}

@@ -348,64 +348,246 @@
    *
-/%0A    public ScratchOptionalField(int referenceID)%0A    %7B
+ @throws IllegalArgumentException If referenceID &lt; 1.%0A     */%0A    public ScratchOptionalField(int referenceID)%0A    %7B%0A        if (referenceID %3C 1) %7B%0A            throw new IllegalArgumentException(%22referenceID may not be %3C 1%22);%0A        %7D
 %0A   
@@ -729,32 +729,90 @@
 he field value.%0A
+     * @throws IllegalArgumentException If value is null.%0A
      */%0A    publ
@@ -854,32 +854,144 @@
 ct value)%0A    %7B%0A
+        if (value == null) %7B%0A            throw new IllegalArgumentException(%22value may not be null%22);%0A        %7D%0A
         this.val
@@ -1934,9 +1934,9 @@
 D %3C 
-0
+1
 ) %7B%0A

Validate ScratchOptionalField parameters