Skip to content

Instantly share code, notes, and snippets.

@GabrielBrasileiro
Last active October 18, 2023 23:58
Show Gist options
  • Save GabrielBrasileiro/c68fed78e2307aa52aa2e59c7866ee7a to your computer and use it in GitHub Desktop.
Save GabrielBrasileiro/c68fed78e2307aa52aa2e59c7866ee7a to your computer and use it in GitHub Desktop.
Functional Replacement Pattern
// Interface de controle
interface ClientFlow {
fun executeFlow()
}
class ClientFlowTransform(
private val executionFlow: ExecutionFlow,
private val emitterFlow: EmitterFlow
) : ClientFlow {
override fun executeFlow() {
executionFlow.contextFlow { data: Any ->
// Edições, criações, atualizações, etc.
emitterFlow.emitFlow(anotherObject)
}
}
}
interface ClientFlow {
override fun createState()
}
class ClientFlowTransform(
private val executionFlow: ExecutionFlow,
private val emitterFlow: EmitterFlow
) : ClientFlow {
override fun createState() {
executionFlow.onScope { newContext: NewContext ->
emitterFlow.emitFlow(newContext.param.uppercase())
}
}
}
// Interface funcional
fun interface ContextScope {
fun onContext(contextData: Any)
}
// Interface de isolamento
interface ExecutionFlow {
fun contextFlow(scope: ContextScope)
}
// Interface de recepção
interface EmitterFlow {
fun emitFlow(data: Any)
}
interface EmitterFlow {
fun emitFlow(data: String)
}
class EmitterFlowReceiverFake : EmitterFlow {
private var lastMessage = String()
override fun emitFlow(data: String) {
lastMessage = data
}
fun getLastMessage(): String = lastMessage
}
interface ExecutionFlow {
fun contextFlow(scope: ContextScope)
}
class ExecutionFlowFake(
private val newContext: NewContext
) : ExecutionFlow {
override fun contextFlow(scope: ContextScope) {
scope.onContext(newContext.param)
}
}
data class NewContext(
val param: String
)
// Estrutura de testes manual
fun main() {
val expected = "ANY"
val newContext = NewContext("any")
val fakeEnvironment = ExecutionFlowFake(newContext)
val emitterFlowReceiverFake = EmitterFlowReceiverFake()
val processState: ClientFlow = ClientFlowTransform(fakeEnvironment, emitterFlowReceiverFake)
processState.executeFlow()
val result = terminateEnvironmentFake.getLastMessage()
println(expected == result) // Saída: True
}
class LegacyExecutionFlow : ExecutionFlow {
// Contexto não interpretável isolado
private val legacyContext = LegacyContext()
// Contexto transformado e emitido
override fun contextFlow(scope: ContextScope) {
/**
* Criações, invocações e definições dos dados que
* gostaria de passar para a nova estrutura de execução
* do código.
*/
val contextData = // Código final mapeado.
scope.onContext(newContext)
}
}
class NewFeatureContext : EmitterFlow {
// Método de recepção e processamento final.
override fun emitFlow(data: Any) {
/**
* Criação dos novos algoritmos que serão
* mantidos e estruturados de forma testável.
*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment