-
Notifications
You must be signed in to change notification settings - Fork 14
/
params.json
1 lines (1 loc) · 10.5 KB
/
params.json
1
{"name":"Octarine","tagline":"Java 8 functional magic","body":"octarine\r\n========\r\n\r\n[![Build Status](https://travis-ci.org/poetix/octarine.svg?branch=master)](https://travis-ci.org/poetix/octarine)\r\n\r\n### Manifesto\r\n\r\nOctarine is a Java 8 library for working with data at the edges of your system: *records* that are loaded from CSV files, deserialised from JSON messages sent over HTTP, or retrieved from databases.\r\n\r\nTraditionally, records in Java have been represented by *Beans*: classes which carry a collection of mutable properties, where each property has a *getter* method to read it, and a *setter* method to write it. Bean objects have no \"behaviour\", in the sense in which objects in Object-Oriented Programming are said to bundle data and behaviour together. They are *degenerate* objects.\r\n\r\nCode that works with Beans is often ugly and repetitive, littered with null-checks (because a property that hasn't been set with a setter can always be null), and hampered by the simultaneous verbosity and inflexibility of the Bean protocol. Unit tests for such code are haunted by a sense of their own pointlessness. Anyone who's spent significant time writing \"Enterprise\" Java in which the Bean pattern predominates will at some point have asked themselves: \"why am I wasting my time with this *crap*?\"\r\n\r\nThere is a better way. Actually there are several better ways; Octarine provides an implementation of one of them.\r\n\r\nOctarine favours:\r\n\r\n * **Concision** - end-user code is concise, readable and free of boilerplate.\r\n * **Tolerance** - code that works with records should be forgiving in what it accepts, using schemas and pattern-matching to select and process records that satisfy its requirements.\r\n * **Immutability** - records are immutable by default.\r\n * **Composability** - keys can be composed to form paths into nested records.\r\n * **Transparency** - no \"magic\" required - especially tricks with reflection and dynamic proxies.\r\n\r\n### Basic concepts\r\n\r\nAn Octarine ```Record``` is a collection of typed key-value pairs, where the ```Key```s are special objects that carry information about the types of the values. A ```Record``` can contain values for any keys whatsoever, but the types of the values must match the types of the keys.\r\n\r\n```java\r\nKey<String> name = Key.named(\"name\");\r\nKey<Integer> age = Key.named(\"age\");\r\n\r\nRecord person = Record.of(name.of(\"Dominic\"), age.of(39));\r\n\r\nString personName = name.extract(person);\r\nInteger personAge = age.extract(person);\r\n```\r\n\r\nHere we have defined two keys, ```name``` and ```age```, created a ```Record``` with values defined for both keys, and extracted both values from the record in a type-safe way.\r\n\r\n#### Absent values\r\n\r\nBecause a ```Record``` can contain values for any ```Key``` or none, the safe way to read values is via the ```Key::get``` method, which returns an ```Optional``` value:\r\n\r\n```java\r\nOptional<String> personName = name.get(person);\r\nint personAge = age.get(person).orElse(0);\r\n```\r\n\r\nYou can use the ```Key::test``` method to find out whether a ```Record``` contains a particular ```Key```:\r\n\r\n```java\r\nif (name.test(person)) {\r\n System.out.println(name.extract(person));\r\n}\r\n```\r\n\r\nA ```Key<T>``` is both a ```Predicate<Record>``` which tests for the presence of that key in a ```Record```, and a ```Function<Record, Optional<T>>```, which tries to retrieve the corresponding value from the ```Record``` and returns ```Optional.empty()``` if it isn't there. ```Key::extract``` returns the value directly (or throws an exception, if it is absent).\r\n\r\nThis trio of methods - ```test```, ```extract```, ```apply``` - defines an ```Extractor```, a useful general concept.\r\n\r\n#### Extractors and pattern-matching\r\n\r\nAn ```Extractor<S, T>``` may be seen as a *partial function* from ```S``` to ```T```: it can only \"extract\" a value of type ```T``` from a value of type ```S``` if such a value is present. Any ```Key<T>``` is an ```Extractor<Record, T>```.\r\n\r\nSuppose we have a ```Record``` which we know will contain *either* a person's name and date of birth, *or* their social security number. We can use the fact that ```Key```s are ```Extractor```s to test which is the case and respond accordingly:\r\n\r\n```java\r\npublic Optional<Person> getPerson(Record details) {\r\n if (name.test(details) && dob.test(details)) {\r\n return Optional.of(getPersonByNameAndAge(name.extract(record), dob.extract(record)));\r\n } else if (ssn.test(record)) {\r\n return Optional.of(getPersonBySocialSecurityNumber(ssn.extract(record)));\r\n } else {\r\n return Optional.empty();\r\n }\r\n}\r\n```\r\n\r\nThis is a common enough thing to want to do that Octarine supports using *pattern matching* to pick out records having particular keys and extract their values:\r\n\r\n```java\r\npublic Optional<Person> getPerson(Record details) {\r\n Matching<Record, Person> matching = Matching.build(m ->\r\n m.matching(name, dob, (n, d) -> getPersonByNameAndAge(n, d))\r\n .matching(ssn, s -> getPersonBySocialSecurityNumber(s))\r\n );\r\n return matching.apply(details);\r\n}\r\n```\r\n\r\n\r\nEach of the patterns described by a ```matching``` call is tried in turn, until one is found where all of the listed extractors match the record. The values targeted\r\n by those extractors are then handed off to the supplied function. (Octarine supports matching patterns of up to four extractors, with functions of up to four arguments).\r\n\r\n#### Immutability and updating\r\n\r\nOctarine's ```Record```s are immutable: there is no way to change the key/value pairs of a record once it has been created. However, it is possible to create a *copy* of a ```Record``` with one or more key/value pairs added or removed:\r\n\r\n```java\r\nRecord person = Record.of(name.of(\"Dominic\"));\r\nRecord personWithAge = person.with(age.of(39));\r\nRecord personWithoutAName = personWithAge.without(name);\r\n```\r\n\r\nAlternatively, ```Key```s themselves act as *lenses*, getting and setting values:\r\n\r\n```java\r\nRecord person = Record.of(name.of(\"Dominic\"));\r\nRecord personWithAge = age.set(person, Optional.of(39);\r\nRecord personWithoutAName = name.set(Optional.empty());\r\n```\r\n\r\nLenses have the interesting property that they *compose*, which we'll explore later.\r\n\r\n#### Mutability: oh, go on then\r\n\r\nIf you really want a mutable record, you can have one.\r\n\r\n```java\r\nMutableRecord mutable = Record.of(\r\n Person.name.of(\"Dominic\"),\r\n Person.age.of(39),\r\n Person.favouriteColour.of(Color.RED),\r\n Person.address.of(Address.addressLines.of(\"13 Rue Morgue\", \"PO3 1TP\"))\r\n).mutable();\r\n\r\nmutable.set(Person.age.of(40), Person.favouriteColour.of(Color.GRAY));\r\nmutable.unset(Person.address);\r\n\r\nRecord immutable = mutable.immutable();\r\n````\r\n\r\nNote however that a ```MutableRecord``` is a mutable copy of an immutable ```Record```, and cannot be used to mutate the ```Record``` it has cloned.\r\n\r\n```MutableRecords``` remember what they've changed: ```MutableRecord::added``` returns a record containing all added or modified key/value pairs, and ```MutableRecord::removed``` returns a set of all removed keys.\r\n\r\n### Quick start\r\n\r\nWe define keys, schemas, serialisers and deserialisers for two record types, `Person` and `Address`.\r\n\r\n```java\r\npublic static interface Address {\r\n static final KeySet mandatoryKeys = new KeySet();\r\n static final ListKey<String> addressLines = mandatoryKeys.addList(\"addressLines\");\r\n static final Key<String> postcode = mandatoryKeys.add(\"postcode\");\r\n\r\n Schema<Address> schema = mandatoryKeys::accept;\r\n\r\n JsonDeserialiser reader = i ->\r\n i.add(addressLines, fromString)\r\n .add(postcode, fromString);\r\n\r\n JsonSerialiser writer = p ->\r\n p.add(addressLines, asString)\r\n .add(postcode, asString);\r\n}\r\n```\r\n\r\n```java\r\npublic static interface Person {\r\n static final KeySet mandatoryKeys = new KeySet();\r\n static final Key<String> name = mandatoryKeys.add(\"name\");\r\n static final Key<Integer> age = mandatoryKeys.add(\"age\");\r\n static final RecordKey address = mandatoryKeys.addRecord(\"address\");\r\n\r\n Schema<Person> schema = (r, v) -> {\r\n mandatoryKeys.accept(r, v);\r\n age.from(r).ifPresent(a -> { if (a < 0) v.accept(\"Age must be 0 or greater\"); });\r\n address.from(r).ifPresent(a -> Address.schema.accept(a, v));\r\n };\r\n\r\n JsonDeserialiser reader = i ->\r\n i.add(name, fromString)\r\n .add(age, fromInteger)\r\n .add(address, Address.reader);\r\n\r\n JsonSerialiser writer = p ->\r\n p.add(name, asString)\r\n .add(age, asInteger)\r\n .add(address, Address.writer);\r\n}\r\n```\r\n\r\nWe can now read a `Person`'s details from Json, validate the record against the schema and make test assertions against it, created an updated copy with one value changed, and write the updated copy back out to Json.\r\n\r\n```java\r\n@Test public void\r\ndeserialise_validate_update_serialise() {\r\n Record record = Person.reader.readFromString(\r\n \"{\\\"name\\\": \\\"Arthur Putey\\\",\\n\" +\"\" +\r\n \" \\\"age\\\": 42,\\n\" +\r\n \" \\\"address\\\": {\\n\" +\r\n \" \\\"addressLines\\\": [\\\"59 Broad Street\\\", \\\"Cirencester\\\"],\\n\" +\r\n \" \\\"postcode\\\": \\\"RA8 81T\\\"\\n\" +\r\n \" }\\n\" +\r\n \"}\");\r\n\r\n assertThat(record, ARecord.validAgainst(Person.schema)\r\n .with(Person.name, \"Arthur Putey\")\r\n .with(Person.age, 42)\r\n // Chaining keys\r\n .with(Person.address.join(Address.addressLines).join(Path.toIndex(0)), \"59 Broad Street\")\r\n // Using a sub-matcher\r\n .with(Person.address, ARecord.validAgainst(Address.schema).with(Address.postcode, \"RA8 81T\")));\r\n\r\n Record changed = Person.age.update(\r\n record, age -> age.map(v -> v + 1));\r\n\r\n assertThat(Person.writer.toString(changed), equalTo(\r\n \"{\\\"name\\\":\\\"Arthur Putey\\\",\" +\"\" +\r\n \"\\\"age\\\":43,\" +\r\n \"\\\"address\\\":{\" +\r\n \"\\\"addressLines\\\":[\\\"59 Broad Street\\\",\\\"Cirencester\\\"],\" +\r\n \"\\\"postcode\\\":\\\"RA8 81T\\\"\" +\r\n \"}}\"));\r\n}\r\n```\r\n","google":"","note":"Don't delete this file! It's used internally to help with page regeneration."}