Last active
December 16, 2015 15:59
-
-
Save jonatasemidio/5459460 to your computer and use it in GitHub Desktop.
"Transformando métodos complexos em closures": Exemplos de como utilizar o reference.& do groovy. Recurso que recupera a lógica de um método é transforma-o em uma closure para utilização do memoize().
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Problema: Quando temos um loop e dentro dele temos uma determinada | |
//lógica que precisará ser executada em todas as iterações; | |
(1..10).each{println "este numero é ${it+5*(10-1)}"} | |
//Solução: Podemos otimizar nosso código inserindo nossa lógica dentro | |
//de uma closure, onde ao final desta chamamos o método memoize(). | |
c = {println "este numero é ${it+5*(10-1)}"}.memoize() | |
//Por fim, chamamos esta closure de dentro do loop para que apenas a primeira | |
//interação seja 100% processada, pois nas próximas a parte repetida desta | |
//logica ficará em cache apenas sofrendo alteração de parâmetro. | |
(1..10).each(c) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MultiMethodSample{ | |
int mysterMethod(String value){ | |
return value.length() | |
} | |
int mysterMethod(List list){ | |
return list.size() | |
} | |
int mysterMethod(int x, int y){ | |
return x+y | |
} | |
} | |
MultiMethodSample instance = new MultiMethodSample() | |
Closure multi = instance.&mysterMethod | |
assert 10 == multi ('string arg') | |
assert 3 == multi (['list', 'of', 'values']) | |
assert 14 == multi (6, 8) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SizeFilter { | |
Integer limit | |
boolean filter (String value) { | |
return value.length() <= limit | |
} | |
} | |
SizeFilter six = new SizeFilter(limit:6) //#1 Construtor | |
SizeFilter five = new SizeFilter(limit:5) //#1 Chamada | |
Closure smallerSix = six.&filter //#2 Associando o método à closure | |
def words = ['long string', 'medium', 'short', 'tiny'] | |
assert 'medium' == words.find (smallerSix) //#3 Chamando a closure | |
assert 'short' == words.find (five.&filter) //#4 Passando a closure diretamente |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment