Skip to content

Instantly share code, notes, and snippets.

@davelnewton
Last active September 27, 2015 23:07
Show Gist options
  • Save davelnewton/1345849 to your computer and use it in GitHub Desktop.
Save davelnewton/1345849 to your computer and use it in GitHub Desktop.
Constructor vs. factories to enhance clarity an readability
// Most everything left out for clarity.
public class RPCRespond<Result> {
public RPCRespond() {
this.code = 0;
this.success = true;
this.result = null;
}
public RPCRespond(Result result) {
this.code = 0;
this.success = true;
this.result = result;
}
public RPCRespond(int code, String failureReason) {
this.code = code;
this.success = false;
this.failureReason = failureReason;
}
public RPCRespond(int code, String failureReason, Object... args) {
this.code = code;
this.success = false;
this.failureReason = String.format(failureReason, args);
}
}
// Example response creations.
r1 = RPCRespond(); // This is a success.
r2 = RPCRespond(1, "Something blew up"); // This is a failure.
/*
In order to understand which is a success or failure,
you must know that if there are *any* arguments supplied
it's a failure.
The constructor (ctor) signatures themselves don't provide
any contextual information that a reader of the code can
use to reason about what's happening.
*/
// Most everything left out for clarity; assume the original constructors.
public class RPCRespond<Result> {
public static RPCRespond rpcSuccess() {
return new RPCRespond();
}
public static RPCRespond rpcFailure(int code, String reason) {
return new RPCRespond(code, reason);
}
// Plus factories for the other failure ctors.
}
// Now the success/failure is immediate obvious, without
// needing to know anything about the API. If you need
// to know what the arguments mean, *then* you look,
// but you understand right away if you're creating
// a success or failure.
r1 = RPCRespond.rpcSuccess();
r2 = RPCRespond.rpcFailure(1, "Something blew up");
// It's a very minor addition, and a small amount of
// additional work, but it makes *reading* the code
// that much easier. You could even make it fluid,
// and provide yet more meaning, but it may not be
// worth the effort.
r3 = RPCRespond.failure().code(1).reason("Something blew up");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment