87 lines
2.4 KiB
Java
Raw Normal View History

2016-08-29 07:27:53 -06:00
// validating/Queue.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// Demonstration of Design by Contract (DbC)
2016-08-29 07:27:53 -06:00
package validating;
2015-06-15 17:47:35 -07:00
import java.util.*;
public class Queue {
private Object[] data;
private int
in = 0, // Next available storage space
out = 0; // Next gettable object
// Has it wrapped around the circular queue?
private boolean wrapped = false;
public Queue(int size) {
data = new Object[size];
2016-01-25 18:05:55 -08:00
// Must be true after construction:
assert invariant();
2015-06-15 17:47:35 -07:00
}
public boolean empty() {
return !wrapped && in == out;
}
public boolean full() {
return wrapped && in == out;
}
public boolean isWrapped() { return wrapped; }
2015-06-15 17:47:35 -07:00
public void put(Object item) {
precondition(item != null, "put() null item");
precondition(!full(), "put() into full Queue");
assert invariant();
data[in++] = item;
if(in >= data.length) {
in = 0;
wrapped = true;
}
assert invariant();
}
public Object get() {
precondition(!empty(), "get() from empty Queue");
assert invariant();
Object returnVal = data[out];
data[out] = null;
out++;
if(out >= data.length) {
out = 0;
wrapped = false;
}
assert postcondition(
returnVal != null, "Null item in Queue");
assert invariant();
return returnVal;
}
// Design-by-contract support methods:
private static void
precondition(boolean cond, String msg) {
if(!cond) throw new QueueException(msg);
}
private static boolean
postcondition(boolean cond, String msg) {
if(!cond) throw new QueueException(msg);
return true;
}
private boolean invariant() {
// Guarantee that no null values are in the
// region of 'data' that holds objects:
for(int i = out; i != in; i = (i + 1) % data.length)
if(data[i] == null)
throw new QueueException("null in queue");
// Guarantee that only null values are outside the
// region of 'data' that holds objects:
if(full()) return true;
for(int i = in; i != out; i = (i + 1) % data.length)
if(data[i] != null)
throw new QueueException(
"non-null outside of queue range: " + dump());
return true;
}
public String dump() {
2015-06-15 17:47:35 -07:00
return "in = " + in +
", out = " + out +
", full() = " + full() +
", empty() = " + empty() +
", queue = " + Arrays.asList(data);
}
2016-08-23 16:48:02 -06:00
}