Skip to content

Instantly share code, notes, and snippets.

@galdosd
Last active August 29, 2015 14:01
Show Gist options
  • Save galdosd/92f327152811b86e932b to your computer and use it in GitHub Desktop.
Save galdosd/92f327152811b86e932b to your computer and use it in GitHub Desktop.
// property slots.... get the extensibility of getters/setters along with the conciseness of the common case where they trivially wrap a field
class Slot<X> {
private X x;
public Slot(){this.x=null;}
private Slot(X x) { this.x=x; }
static <X> Slot<X> slot(X x){ return new Slot<>(x); }
static <X> Slot<X> slot(){ return new Slot<X>(null); }
public X get() { return x; }
public void set(X x) { this.x=x; }
}
class Bob {
// easy to declare without monkey code
public final Slot<Long> timestamp = slot(69L);
public final Slot<Thread> myFavoriteThread = slot();
// but easy to extend
public final Slot<String> nickname = new Slot<String>() {
private String _nickname = "Anonymous coward";
@Override public String get() { return "Mr. " + _nickname; }
@Override public void set(String s) { _nickname = s; }
};
// the only catch?
// it won't interoperate with anything else, now that the unfortunate getter/setter name convention is so ingrained :(
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment