Guava makes defensive programming more pleasant.

This commit is contained in:
Michael Bayne
2010-12-08 19:35:50 +00:00
parent b42ec35b09
commit 963a9a0fc1
6 changed files with 65 additions and 108 deletions
@@ -39,6 +39,8 @@ import net.sf.ehcache.distribution.RMICacheReplicatorFactory;
import net.sf.ehcache.event.CacheEventListener; import net.sf.ehcache.event.CacheEventListener;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy; import net.sf.ehcache.store.MemoryStoreEvictionPolicy;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.samskivert.depot.Log.log; import static com.samskivert.depot.Log.log;
/** /**
@@ -149,9 +151,8 @@ public class EHCacheAdapter
{ {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
Ehcache cache = _categories.get(category); Ehcache cache = _categories.get(category);
if (cache == null) { checkArgument(cache != null, "Unknown category: " + category);
throw new IllegalArgumentException("Unknown category: " + category);
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
EHCacheBin<T> bin = (EHCacheBin<T>) _bins.get(cacheId); EHCacheBin<T> bin = (EHCacheBin<T>) _bins.get(cacheId);
if (bin == null) { if (bin == null) {
@@ -305,9 +306,8 @@ public class EHCacheAdapter
{ {
public EHCacheKey (String id, Serializable key) public EHCacheKey (String id, Serializable key)
{ {
if (id == null || key == null) { checkNotNull(id);
throw new IllegalArgumentException("Can't handle null key or id"); checkNotNull(key);
}
_id = id; _id = id;
_key = key; _key = key;
} }
+13 -23
View File
@@ -37,6 +37,8 @@ import com.samskivert.depot.impl.DepotMarshaller;
import com.samskivert.depot.impl.DepotUtil; import com.samskivert.depot.impl.DepotUtil;
import com.samskivert.depot.impl.FragmentVisitor; import com.samskivert.depot.impl.FragmentVisitor;
import static com.google.common.base.Preconditions.checkArgument;
/** /**
* A special form of {@link WhereClause} that uniquely specifies a single database row and thus * A special form of {@link WhereClause} that uniquely specifies a single database row and thus
* also a single persistent object. It knows how to invalidate itself upon modification. This class * also a single persistent object. It knows how to invalidate itself upon modification. This class
@@ -181,12 +183,9 @@ public class Key<T extends PersistentRecord> extends WhereClause
// from ValidatingCacheInvalidator // from ValidatingCacheInvalidator
public void validateFlushType (Class<?> pClass) public void validateFlushType (Class<?> pClass)
{ {
if (!pClass.equals(_pClass)) { checkArgument(pClass.equals(_pClass),
throw new IllegalArgumentException( "Class mismatch between persistent record and cache invalidator " +
"Class mismatch between persistent record and cache invalidator " + "[record=%s, invtype=%s].", pClass.getSimpleName(), _pClass.getSimpleName());
"[record=" + pClass.getSimpleName() +
", invtype=" + _pClass.getSimpleName() + "].");
}
} }
// from CacheInvalidator // from CacheInvalidator
@@ -247,9 +246,8 @@ public class Key<T extends PersistentRecord> extends WhereClause
protected static Comparable<?>[] toCanonicalOrder ( protected static Comparable<?>[] toCanonicalOrder (
Class<? extends PersistentRecord> pClass, ColumnExp<?>[] fields, Comparable<?>[] values) Class<? extends PersistentRecord> pClass, ColumnExp<?>[] fields, Comparable<?>[] values)
{ {
if (fields.length != values.length) { checkArgument(fields.length == values.length,
throw new IllegalArgumentException("Field and Value arrays must be of equal length."); "Field and Value arrays must be of equal length.");
}
// look up the cached primary key fields for this object // look up the cached primary key fields for this object
ColumnExp<?>[] keyFields = DepotUtil.getKeyFields(pClass); ColumnExp<?>[] keyFields = DepotUtil.getKeyFields(pClass);
@@ -269,24 +267,16 @@ public class Key<T extends PersistentRecord> extends WhereClause
Comparable<?>[] cvalues = new Comparable<?>[values.length]; Comparable<?>[] cvalues = new Comparable<?>[values.length];
for (int ii = 0; ii < keyFields.length; ii++) { for (int ii = 0; ii < keyFields.length; ii++) {
Comparable<?> value = map.remove(keyFields[ii]); Comparable<?> value = map.remove(keyFields[ii]);
if (value == null) { // make sure we were provided with a value for this primary key field
// make sure we were provided with a value for this primary key field checkArgument(value != null, "Missing value for key field: " + keyFields[ii]);
throw new IllegalArgumentException( checkArgument(value instanceof Serializable,
"Missing value for key field: " + keyFields[ii]); "Non-serializable argument [key=%s, value=%s]", keyFields[ii], value);
}
if (!(value instanceof Serializable)) {
throw new IllegalArgumentException(
"Non-serializable argument [key=" + keyFields[ii] +
", value=" + value + "]");
}
cvalues[ii] = value; cvalues[ii] = value;
} }
// finally make sure we were not given any fields that are not primary key fields // finally make sure we were not given any fields that are not primary key fields
if (map.size() > 0) { checkArgument(map.isEmpty(), "Non-key columns given: " +
throw new IllegalArgumentException( StringUtil.join(map.keySet().toArray()));
"Non-key columns given: " + StringUtil.join(map.keySet().toArray(), ", "));
}
return cvalues; return cvalues;
} }
@@ -32,6 +32,9 @@ import com.samskivert.depot.expression.SQLExpression;
import com.samskivert.depot.impl.ColumnSet; import com.samskivert.depot.impl.ColumnSet;
import com.samskivert.depot.impl.FindAllQuery; import com.samskivert.depot.impl.FindAllQuery;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
/** /**
* The root of a fluent mechanism for constructing queries. Obtain an instance via {@link * The root of a fluent mechanism for constructing queries. Obtain an instance via {@link
* DepotRepository#from}. * DepotRepository#from}.
@@ -96,9 +99,7 @@ public class QueryBuilder<T extends PersistentRecord>
public QueryBuilder<T> where (Iterable<? extends SQLExpression> exprs) public QueryBuilder<T> where (Iterable<? extends SQLExpression> exprs)
{ {
Iterator<? extends SQLExpression> iter = exprs.iterator(); Iterator<? extends SQLExpression> iter = exprs.iterator();
if (!iter.hasNext()) { checkArgument(iter.hasNext(), "Must supply at least one expression.");
throw new IllegalArgumentException("Must supply at least one expression.");
}
SQLExpression first = iter.next(); SQLExpression first = iter.next();
return where(iter.hasNext() ? new Where(Ops.and(exprs)) : new Where(first)); return where(iter.hasNext() ? new Where(Ops.and(exprs)) : new Where(first));
} }
@@ -128,7 +129,7 @@ public class QueryBuilder<T extends PersistentRecord>
*/ */
public QueryBuilder<T> where (WhereClause where) public QueryBuilder<T> where (WhereClause where)
{ {
requireNull(_where, "Where clause is already configured."); checkState(_where == null, "Where clause is already configured.");
_where = where; _where = where;
return this; return this;
} }
@@ -177,7 +178,7 @@ public class QueryBuilder<T extends PersistentRecord>
*/ */
public QueryBuilder<T> groupBy (SQLExpression... exprs) public QueryBuilder<T> groupBy (SQLExpression... exprs)
{ {
requireNull(_groupBy, "GroupBy clause is already configured."); checkState(_groupBy == null, "GroupBy clause is already configured.");
_groupBy = new GroupBy(exprs); _groupBy = new GroupBy(exprs);
return this; return this;
} }
@@ -211,7 +212,7 @@ public class QueryBuilder<T extends PersistentRecord>
*/ */
public QueryBuilder<T> orderBy (OrderBy orderBy) public QueryBuilder<T> orderBy (OrderBy orderBy)
{ {
requireNull(_orderBy, "OrderBy clause is already configured."); checkState(_orderBy == null, "OrderBy clause is already configured.");
_orderBy = orderBy; _orderBy = orderBy;
return this; return this;
} }
@@ -221,7 +222,7 @@ public class QueryBuilder<T extends PersistentRecord>
*/ */
public QueryBuilder<T> limit (int count) public QueryBuilder<T> limit (int count)
{ {
requireNull(_limit, "Limit clause is already configured."); checkState(_limit == null, "Limit clause is already configured.");
_limit = new Limit(0, count); _limit = new Limit(0, count);
return this; return this;
} }
@@ -231,7 +232,7 @@ public class QueryBuilder<T extends PersistentRecord>
*/ */
public QueryBuilder<T> limit (int offset, int count) public QueryBuilder<T> limit (int offset, int count)
{ {
requireNull(_limit, "Limit clause is already configured."); checkState(_limit == null, "Limit clause is already configured.");
_limit = new Limit(offset, count); _limit = new Limit(offset, count);
return this; return this;
} }
@@ -258,7 +259,7 @@ public class QueryBuilder<T extends PersistentRecord>
*/ */
public QueryBuilder<T> override (FromOverride fromOverride) public QueryBuilder<T> override (FromOverride fromOverride)
{ {
requireNull(_fromOverride, "FromOverride clause is already configured."); checkState(_fromOverride == null, "FromOverride clause is already configured.");
_fromOverride = fromOverride; _fromOverride = fromOverride;
return this; return this;
} }
@@ -304,7 +305,7 @@ public class QueryBuilder<T extends PersistentRecord>
*/ */
public QueryBuilder<T> forUpdate () public QueryBuilder<T> forUpdate ()
{ {
requireNull(_forUpdate, "ForUpdate clause is already configured."); checkState(_forUpdate == null, "ForUpdate clause is already configured.");
_forUpdate = new ForUpdate(); _forUpdate = new ForUpdate();
return this; return this;
} }
@@ -450,30 +451,16 @@ public class QueryBuilder<T extends PersistentRecord>
} }
} }
protected void requireNotNull (Object value, String message)
{
if (value == null) {
throw new IllegalStateException(message);
}
}
protected void requireNull (Object value, String message)
{
if (value != null) {
throw new IllegalStateException(message);
}
}
protected void assertValidDelete () protected void assertValidDelete ()
{ {
requireNotNull(_where, "Where clause must be specified for delete."); checkState(_where != null, "Where clause must be specified for delete.");
requireNull(_joins, "Join clauses not supported by delete."); checkState(_joins == null, "Join clauses not supported by delete.");
requireNull(_orderBy, "OrderBy clause not applicable for delete."); checkState(_orderBy == null, "OrderBy clause not applicable for delete.");
requireNull(_groupBy, "GroupBy clause not applicable for delete."); checkState(_groupBy == null, "GroupBy clause not applicable for delete.");
requireNull(_limit, "Limit clause not supported by delete."); checkState(_limit == null, "Limit clause not supported by delete.");
requireNull(_fromOverride, "FromOverride clause not applicable for delete."); checkState(_fromOverride == null, "FromOverride clause not applicable for delete.");
requireNull(_fieldDefs, "FieldDefinition clauses not applicable for delete."); checkState(_fieldDefs == null, "FieldDefinition clauses not applicable for delete.");
requireNull(_forUpdate, "ForUpdate clause not supported by delete."); checkState(_forUpdate == null, "ForUpdate clause not supported by delete.");
} }
protected final PersistenceContext _ctx; protected final PersistenceContext _ctx;
@@ -32,6 +32,7 @@ import com.samskivert.depot.expression.ColumnExp;
import com.samskivert.depot.impl.FieldMarshaller; import com.samskivert.depot.impl.FieldMarshaller;
import com.samskivert.depot.impl.Modifier; import com.samskivert.depot.impl.Modifier;
import static com.google.common.base.Preconditions.checkArgument;
import static com.samskivert.depot.Log.log; import static com.samskivert.depot.Log.log;
/** /**
@@ -97,25 +98,20 @@ public abstract class SchemaMigration extends Modifier
@Override @Override
protected int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { protected int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException {
if (!liaison.tableContainsColumn(conn, _tableName, _oldColumnName)) { if (!liaison.tableContainsColumn(conn, _tableName, _oldColumnName)) {
if (liaison.tableContainsColumn(conn, _tableName, _newColumnName)) { // if the new column already exists, log a warning, otherwise freak out
// we'll accept this inconsistency checkArgument(liaison.tableContainsColumn(conn, _tableName, _newColumnName),
log.warning(_tableName + "." + _oldColumnName + " already renamed to " + _tableName + " does not contain '" + _oldColumnName + "'");
_newColumnName + "."); log.warning(_tableName + "." + _oldColumnName + " already renamed to " +
return 0; _newColumnName + ".");
} return 0;
// but this is not OK
throw new IllegalArgumentException(
_tableName + " does not contain '" + _oldColumnName + "'");
} }
// nor is this // nor is this
if (liaison.tableContainsColumn(conn, _tableName, _newColumnName)) { checkArgument(!liaison.tableContainsColumn(conn, _tableName, _newColumnName),
throw new IllegalArgumentException( _tableName + " already contains '" + _newColumnName + "'");
_tableName + " already contains '" + _newColumnName + "'");
}
log.info("Renaming '" + _oldColumnName + "' to '" + _newColumnName + "' in: " + log.info("Renaming '" + _oldColumnName + "' to '" + _newColumnName + "' in: " +
_tableName); _tableName);
return liaison.renameColumn( return liaison.renameColumn(
conn, _tableName, _oldColumnName, _newColumnName, _newColumnDef) ? 1 : 0; conn, _tableName, _oldColumnName, _newColumnName, _newColumnDef) ? 1 : 0;
} }
@@ -274,10 +270,8 @@ public abstract class SchemaMigration extends Modifier
Map<String, FieldMarshaller<?>> marshallers, String fieldName) Map<String, FieldMarshaller<?>> marshallers, String fieldName)
{ {
FieldMarshaller<?> marsh = marshallers.get(fieldName); FieldMarshaller<?> marsh = marshallers.get(fieldName);
if (marsh == null) { checkArgument(marsh != null,
throw new IllegalArgumentException( "'" + _tableName + "' does not contain field '" + fieldName + "'");
"'" + _tableName + "' does not contain field '" + fieldName + "'");
}
return marsh; return marsh;
} }
@@ -32,6 +32,8 @@ import com.samskivert.depot.PersistentRecord;
import com.samskivert.depot.expression.ColumnExp; import com.samskivert.depot.expression.ColumnExp;
import com.samskivert.depot.impl.FragmentVisitor; import com.samskivert.depot.impl.FragmentVisitor;
import static com.google.common.base.Preconditions.checkArgument;
/** /**
* Represents a complete select clause. * Represents a complete select clause.
*/ */
@@ -64,17 +66,12 @@ public class SelectClause
continue; continue;
} }
if (clause instanceof WhereClause) { if (clause instanceof WhereClause) {
if (_where != null) { checkArgument(_where == null, "Query can't contain multiple Where clauses.");
throw new IllegalArgumentException(
"Query can't contain multiple Where clauses.");
}
_where = (WhereClause) clause; _where = (WhereClause) clause;
} else if (clause instanceof FromOverride) { } else if (clause instanceof FromOverride) {
if (_fromOverride != null) { checkArgument(_fromOverride == null,
throw new IllegalArgumentException( "Query can't contain multiple FromOverride clauses.");
"Query can't contain multiple FromOverride clauses.");
}
_fromOverride = (FromOverride) clause; _fromOverride = (FromOverride) clause;
} else if (clause instanceof Join) { } else if (clause instanceof Join) {
@@ -84,31 +81,20 @@ public class SelectClause
_disMap.put(((FieldDefinition) clause).getField(), ((FieldDefinition) clause)); _disMap.put(((FieldDefinition) clause).getField(), ((FieldDefinition) clause));
} else if (clause instanceof OrderBy) { } else if (clause instanceof OrderBy) {
if (_orderBy != null) { checkArgument(_orderBy == null, "Query can't contain multiple OrderBy clauses.");
throw new IllegalArgumentException(
"Query can't contain multiple OrderBy clauses.");
}
_orderBy = (OrderBy) clause; _orderBy = (OrderBy) clause;
} else if (clause instanceof GroupBy) { } else if (clause instanceof GroupBy) {
if (_groupBy != null) { checkArgument(_groupBy == null, "Query can't contain multiple GroupBy clauses.");
throw new IllegalArgumentException(
"Query can't contain multiple GroupBy clauses.");
}
_groupBy = (GroupBy) clause; _groupBy = (GroupBy) clause;
} else if (clause instanceof Limit) { } else if (clause instanceof Limit) {
if (_limit != null) { checkArgument(_limit == null, "Query can't contain multiple Limit clauses.");
throw new IllegalArgumentException(
"Query can't contain multiple Limit clauses.");
}
_limit = (Limit) clause; _limit = (Limit) clause;
} else if (clause instanceof ForUpdate) { } else if (clause instanceof ForUpdate) {
if (_forUpdate != null) { checkArgument(_forUpdate == null,
throw new IllegalArgumentException( "Query can't contain multiple For Update clauses.");
"Query can't contain multiple For Update clauses.");
}
_forUpdate = (ForUpdate) clause; _forUpdate = (ForUpdate) clause;
} else { } else {
@@ -22,6 +22,8 @@ package com.samskivert.depot.clause;
import com.samskivert.depot.expression.SQLExpression; import com.samskivert.depot.expression.SQLExpression;
import static com.google.common.base.Preconditions.checkArgument;
/** /**
* Currently only exists as a type without any functionality of its own. * Currently only exists as a type without any functionality of its own.
*/ */
@@ -50,10 +52,8 @@ public abstract class WhereClause implements QueryClause
*/ */
protected void validateTypesMatch (Class<?> qClass, Class<?> kClass) protected void validateTypesMatch (Class<?> qClass, Class<?> kClass)
{ {
if (!qClass.equals(kClass)) { checkArgument(qClass.equals(kClass),
throw new IllegalArgumentException( "Class mismatch between persistent record and key in query " +
"Class mismatch between persistent record and key in query " + "[qtype=%s, ktype=%s].", qClass.getSimpleName(), kClass.getSimpleName());
"[qtype=" + qClass.getSimpleName() + ", ktype=" + kClass.getSimpleName() + "].");
}
} }
} }