Skip to content

Instantly share code, notes, and snippets.

View xrrocha's full-sized avatar

Ricardo Rocha xrrocha

View GitHub Profile
val bank1 = Bank()
val memimg1 = MemImg(bank1, eventSourcing)
memimg1.execute(CreateAccount("janet", "Janet Doe"))
assertEquals(Amount.ZERO, bank1.accounts["janet"]!!.balance)
memimg1.execute(Deposit("janet", Amount(100)))
assertEquals(Amount(100), bank1.accounts["janet"]!!.balance)
memimg1.execute(Withdrawal("janet", Amount(10)))
/* 1) Domain entities: Bank and Account */
typealias Amount = BigDecimal
data class Bank(val accounts: MutableMap<String, Account> = HashMap())
data class Account(val id: String, val name: String) {
var balance: Amount by TxDelegate(initialValue = Amount.ZERO) {
// triggers rollback on validation failure
it >= Amount.ZERO
}
interface Command { fun applyTo(system: Any) }
interface Query { fun extractFrom(system: Any): Any?}
interface EventSourcing {
fun append(event: Any)
fun <E> replay(eventConsumer: (E) -> Unit)
}
interface TxManager {
// Skeletal Kotlin TL;DR for the truly impatient:
class MemoryImageProcessor(private val system: Any,
private val eventSourcing: EventSourcing) {
init {
synchronized(this) {
eventSourcing.replay<Command> { command -> command.applyTo(system) }
}
}
fun execute(command: Command): Unit = synchronized(this) {
do {
// ... shuffling stuff...
// Ensure shuffling took place!
} while (range.all {
result[it] == text[it] })
@xrrocha
xrrocha / README-28
Created December 16, 2020 17:26
code block for README-28
package wscrambler
object WordScrambler {
private val WORD_REGEX =
"""\p{IsLatin}(\p{IsLatin})\1*(?!\1)\p{IsLatin}\p{IsLatin}+""".toRegex()
@JvmStatic // JVM static method
// CLI FQN: wscrambler.Scrambler
fun main(args: Array<String>) {
@xrrocha
xrrocha / README-27
Created December 16, 2020 17:26
code block for README-27
// Nullable constructor arg w/default
class Numberer(pattern: String? = null) {
companion object {
// Public constant
const val DEF_PATTERN = "000,000"
}
// Private field w/fallback value (?:)
@xrrocha
xrrocha / README-26
Created December 16, 2020 17:26
code block for README-26
package wscrambler
object WordScrambler {
// Regex compiled only once:
// at object initialization.
// Inaccessible to others,
// even in the same package.
private val WORD_REGEX =
"""\p{IsLatin}(\p{IsLatin})\1*(?!\1)\p{IsLatin}\p{IsLatin}+"""
@xrrocha
xrrocha / README-25
Created December 16, 2020 17:26
code block for README-25
wscrambler.scrambleWords("Hey there!")
@xrrocha
xrrocha / README-24
Created December 16, 2020 17:26
code block for README-24
// Scramble from files/stdin to stdout
fun main(args: Array<String>) {
// Collect readers from args/stdin
val readers =
if (args.isNotEmpty())
args.map { File(it).reader() }
else
// in: quoted because reserved