Top Banner
ЭПИЧНЫЕ ГРУВИ ПАЗЗЛЕРЫ ВТОРОЙ СЕЗОН: МЕСТЬ СКОБОК!
137

The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Jan 06, 2017

Download

Software

JavaDayUA
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

ЭПИЧНЫЕ ГРУВИ

ПАЗЗЛЕРЫ

ВТОРОЙ СЕЗОН:

МЕСТЬ СКОБОК!

Page 2: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 3: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Ну этих точно никто не знает…

Page 4: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

1. Дваклевыхпацанана сцене

Page 5: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Ты кто такой?

linkd.in/jbaruch

stackoverflow.com/users/402053/jbaruch

Page 6: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Как два?! А Где второй?!

Page 7: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Вместе мы:

Page 8: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Первый Сезон Хорошо Пошёл!

Page 9: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

1. Дваклевыхпацанана сцене2. Смешные задачки3. Выголосуете! Да-да!4. Новыеклевыефутболкилетятв

зал! Лягушки тоже.5. Унас есть хэштег!

groovypuzzlers

Page 10: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 11: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Все работает (т.е. не работает) на версии 2.4.4

Page 12: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 13: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 14: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

'а'..'я'.each { println it }

B. NoSuchMethodError

C. z

D. Не побежит

A. абв...я

Page 15: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 16: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Вы знали, да?

('a'..'z').each { println it }

Page 17: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

“Все проблемы в программировании можно решить добавив пару скобок”

John McCarthy, изобретатель LISP

Page 18: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 19: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def back = 'back'

def quotes = ["I'll be $back",

"I'll be ${-> back}",

"I'll be ${back}",

"I'll be "+back]

println quotes

back = 'bach'

println quotes

A.Никаких Бахов

B.Один Бах

C.Два Баха

D.Три Баха

Page 20: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 21: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

В рантайме отрабатывают только closures, всё остальное инлайнится

Page 22: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def back = 'back'

def quotes = ["I'll be $back",

"I'll be ${-> back}",

"I'll be ${back}",

"I'll be "+back]

В рантайме отрабатывают только closures, всё остальное инлайнится

Page 23: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def back = 'back'

def quotes = ["I'll be $back",

"I'll be ${-> back}",

"I'll be ${back}",

"I'll be "+back]

В рантайме отрабатывают только closures, всё остальное инлайнится

А это единственный closure

Page 24: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 25: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Как напечатать 666?

A. def beast = '6' * Math.PI

B. def beast = '6' * '3’

C. def beast = '667' – 1

D. def beast = '6' + '6' + 0 + 6

Page 26: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 27: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def beast = '6' * Math.PI

Page 28: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def beast = '6' * 3.1415926…

Page 29: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 30: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

/**

* Repeat a String a certain number of times.

*

* @param self a String to be repeated

* @param factor the number of times the String should be repeated

* @return a String composed of a repetition

* @throws IllegalArgumentException if the number of repetitions is < 0

* @since 1.0

*/

public static String multiply(String self, Number factor) {

int size = factor.intValue();

}

Page 31: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def beast = '6' * 3.1415926…

Page 32: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def beast = '6' * 3

Page 33: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Pop Quiz!

B. def beast = '6' * '3’

C. def beast = '667' – 1

D. def beast = '6' + '6' + 0 + 6

Куку!

Page 34: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 35: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

@groovy.transform.InheritConstructors

class TreaayeMap extends HashMap {

}

TreaayeMap a = [5]

TreaayeMap b = [6]

println "${a.getClass()} ${a.equals(b)}"

Page 36: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

@groovy.transform.InheritConstructors

class TreaayeMap extends HashMap {

}

TreaayeMap a = [5]

TreaayeMap b = [6]

println "${a.getClass()} ${a.equals(b)}"

A. class HashMap true

B. class TreaayeMap false

C. class TreaayeMap true

D. class HashMap false

Page 37: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 38: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 39: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 40: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

TreaayeMap a = [5]

Page 41: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

TreaayeMap a = [5]

Page 42: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

TreaayeMap a = [5]

Page 43: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

TreaayeMap a = [5]@groovy.transform.InheritConstructors

class TreaayeMap extends HashMap {

}

Page 44: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

TreaayeMap a = [5]@groovy.transform.InheritConstructors

class TreaayeMap extends HashMap {

}

/**

* Constructs an empty <tt>HashMap</tt> with the specified initial

* capacity and the default load factor (0.75).

*

* @param initialCapacity the initial capacity.

* @throws IllegalArgumentException if the initial capacity is negative.

*/

public HashMap(int initialCapacity)

Page 45: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 46: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 47: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class THERE_CAN_BE_ONLY_ONE { }

class MacLeod {

THERE_CAN_BE_ONLY_ONE getTHERE_CAN_BE_ONLY_ONE() {

Class clazz = THERE_CAN_BE_ONLY_ONE

return clazz.newInstance()

}

}

println new MacLeod().THERE_CAN_BE_ONLY_ONE

Page 48: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class THERE_CAN_BE_ONLY_ONE { }

class MacLeod {

THERE_CAN_BE_ONLY_ONE

getTHERE_CAN_BE_ONLY_ONE() {

Class clazz = THERE_CAN_BE_ONLY_ONE

return clazz.newInstance()

}

}

println new MacLeod().THERE_CAN_BE_ONLY_ONE

A. Не побежит

B. No such property: THERE_CAN_BE_ONLY_ONE for class: MacLeod

C. THERE_CAN_BE_ONLY_ONE@3d74bf60

D. Навернется по-другому

Page 49: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 50: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

A.MultipleCompilationErrorsException

B.StackOverflowError

C.NullPointerException

D.Навернется ещё как-нибудь

Page 51: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 52: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class MacLeod {

THERE_CAN_BE_ONLY_ONE getTHERE_CAN_BE_ONLY_ONE() {

Class clazz = THERE_CAN_BE_ONLY_ONE

return clazz.newInstance()

}

}

Page 53: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class MacLeod {

THERE_CAN_BE_ONLY_ONE getTHERE_CAN_BE_ONLY_ONE() {

Class clazz = getTHERE_CAN_BE_ONLY_ONE()

return clazz.newInstance()

}

}

Page 54: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Как мы это чиним?

Class<THERE_CAN_BE_ONLY_ONE> clazz = THERE_CAN_BE_ONLY_ONE.class

Page 55: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class MacLeod {

THERE_CAN_BE_ONLY_ONE getTHERE_CAN_BE_ONLY_ONE() {

Class<THERE_CAN_BE_ONLY_ONE> clazz = THERE_CAN_BE_ONLY_ONE.class

return clazz.newInstance()

}

}

Page 56: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 57: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class MacLeod {

THERE_CAN_BE_ONLY_ONE getTHERE_CAN_BE_ONLY_ONE() {

Class<THERE_CAN_BE_ONLY_ONE> clazz = getTHERE_CAN_BE_ONLY_ONE().class

return clazz.newInstance()

}

}

Page 58: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Как мы это чиним?

Class<THERE_CAN_BE_ONLY_ONE> clazz = (THERE_CAN_BE_ONLY_ONE as Class)

Page 59: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class MacLeod {

THERE_CAN_BE_ONLY_ONE getTHERE_CAN_BE_ONLY_ONE() {

Class<THERE_CAN_BE_ONLY_ONE> clazz = (THERE_CAN_BE_ONLY_ONE as Class)

return clazz.newInstance()

}

}

Page 60: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 61: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class MacLeod {

THERE_CAN_BE_ONLY_ONE getTHERE_CAN_BE_ONLY_ONE() {

Class<THERE_CAN_BE_ONLY_ONE> clazz = (getTHERE_CAN_BE_ONLY_ONE() as Class)

return clazz.newInstance()

}

}

Page 62: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Как мы это чиним?

Page 63: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 64: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

String truth = 'false'

boolean groovyTruth = truth

println groovyTruth

Page 65: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

A.false

B. true

C. ClassCastException

D.Не побежит

String truth = 'false'

boolean groovyTruth = truth

println groovyTruth

Page 66: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 67: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 68: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 69: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 70: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class Kitty { def fur }

def kitties = [new Kitty(fur: 'soft'),new Kitty(fur: 'warm'),new Kitty(fur: 'purr') ]

println kitties.collect { it.fur }

println kitties*.fur

println kitties.fur

Сколько будет одинаковых строк?

A. Все разные

B. Две одинаковые

C. Все одинаковые

D. Не скомпилируется

Page 71: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 72: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class Kitty { def fur }

def kitties

println kitties.collect { it.fur }

println kitties*.fur

println kitties.fur

Сколько будет одинаковых строк?

A. Все разные

B. Две одинаковые

C. Все одинаковые

D. Не скомпилируется

Page 73: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 74: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class Kitty { def fur }

def kitties

println kitties.fur

Page 75: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class Kitty { def fur }

def kitties

println kitties.fur

Page 76: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class Kitty { def fur }

def kitties

println kitties.collect { it.fur }

Page 77: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class Kitty { def fur }

def kitties

println kitties.collect { it.fur }

public static Collection asCollection(Object value) {

if (value == null) {

return Collections.EMPTY_LIST;

}

}

Page 78: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class Kitty { def fur }

def kitties

println kitties*.fur

Page 79: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class Kitty { def fur }

def kitties

println kitties*.fur

Page 80: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class Kitty { def fur }

def kitties

println kitties*.fur

Page 81: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

[]nullCaught: java.lang.NullPointerException: Cannot get property 'fur' on null object

Page 82: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 83: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

ArrayList<String> expendables = [Arnie', 'Chuck', Sly']

def expendable = //кто нибудь из списка сверху

for(String hero in expendables) {

if(hero == expendable){

expendables.remove(hero)

}

}

println expendables

Page 84: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

A. Никого

B. Arnie

C. Chuck

D. Sly

ArrayList<String> expendables = [Arnie', 'Chuck', Sly']

def expendable = //кто нибудь из списка сверху

for(String hero in expendables) {

if(hero == expendable){

expendables.remove(hero)

}

}

println expendables

Кого подставить чтобы не было ConcurrentModificationException?

Page 85: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 86: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 87: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

А вас предупреждали

Page 88: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

List expendables = Arrays.asList(new String[]{”Arnie", "Chuck", ”Sly"});

String expendable = "Chuck";

Iterator iterator = expendables.iterator();

while(iterator.hasNext()) {

String hero = (String)iterator.next();

if(hero.equals(expendable)) {

expendables.remove(hero);

}

}

Декомпильнём-ка!

Page 89: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

while(iterator.hasNext()) {

String hero = (String)iterator.next();

if(hero.equals(expendable)) {

// expendables.remove(hero); }

}

Page 90: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

while(iterator.hasNext()) {

String hero = (String)iterator.next();

if(hero.equals(expendable)) {

// expendables.remove(hero); }

}

public E next() {

checkForComodification();

cursor = i + 1;

}

Модификации

проверяются в

следущем заходе

Готовим индекс к

проверке hasNext() в

следующем заходеpublic boolean hasNext() {

return cursor != size();

}

Выход по индексу

последнего элемента +1 ==

size()

Посмотрим как должно

работать

Page 91: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

while(iterator.hasNext()) {

String hero = (String)iterator.next();

if(hero.equals(expendable)) {

// expendables.remove(hero); }

}

public E next() {

checkForComodification();

cursor = i + 1;

}

public boolean hasNext() {

return cursor != size();

}

После Слая курсор равен

3

Size тоже равен 3

Всё ясно. Теперь давайте попортим.

Page 92: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

while(iterator.hasNext()) {

String hero = (String)iterator.next();

if(hero.equals(expendable)) {

expendables.remove(hero);

}

}

public E next() {

checkForComodification();

cursor = i + 1;

}

public boolean hasNext() {

return cursor != size();

}

В итерации Чака курсор

равен 2

Оп-ля, и size теперь тоже

равен 2!

А всё, никаких next() не будет,

checkForComodification не вызывается!

Теперь мы убираем Чака

Page 93: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Эй, а как же я?!

Page 94: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

while(iterator.hasNext()) {

String hero = (String)iterator.next();

if(hero.equals(expendable)) {

expendables.remove(hero);

}

}

public E next() {

checkForComodification();

cursor = i + 1;

}

public boolean hasNext() {

return cursor != size();

}

В итерации Слая курсор

равен 3

Теперь размер 2!

2!=3, пошли на еще кружок!

Не важно, что мы уже за концом цикла,

checkForComodification будет вызван!

Убираем елемент

Page 95: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 96: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

assert 1L == 1println 1L.equals(1)

Page 97: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

assert 1L == 1println 1L.equals(1)

A. Assertion failed

B. true

C. false

D. MissingMethodException

Page 98: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 99: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 100: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 101: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 102: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 103: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

A. [[2, 3, 5], [2, 4, 8], [42, 73, 2147483647, 0]]

B. Не побежит

C. [[null, null, null, 5]]

D. null

Page 104: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 105: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 106: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 107: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 108: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def jailhouseRockdef loveMeTender

def rockAroundTheClock = [1,2,3]

jailhouseRock?:[] + loveMeTender?:[] + rockAroundTheClock?:[]

*Да, это не Элвиса, мы знаем.

Page 109: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def jailhouseRockdef loveMeTender

def rockAroundTheClock = [1,2,3]

jailhouseRock?:[] + loveMeTender?:[] + rockAroundTheClock?:[]

A. [null]

B. null

C. []

D. [1,2,3]

Page 110: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 111: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def jailhouseRockdef loveMeTender

def rockAroundTheClock = [1,2,3]

jailhouseRock?:[] + loveMeTender?:[] + rockAroundTheClock?:[]

Page 112: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def jailhouseRockdef loveMeTender

def rockAroundTheClock = [1,2,3]

jailhouseRock?:[null]?:[] + rockAroundTheClock?:[]

Page 113: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def jailhouseRockdef loveMeTender

def rockAroundTheClock = [1,2,3]

jailhouseRock?:[null]?:[1,2,3]?:[]

Page 114: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def jailhouseRockdef loveMeTender

def rockAroundTheClock = [1,2,3]

jailhouseRock?jailhouseRock:[null]?[null]:[1,2,3]?[1,2,3]:[]

Page 115: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def jailhouseRockdef loveMeTender

def rockAroundTheClock = [1,2,3]

null?null:[null]?[null]:[1,2,3]?[1,2,3]:[]

Page 116: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def jailhouseRockdef loveMeTender

def rockAroundTheClock = [1,2,3]

false?null:true?[null]:true?[1,2,3]:[]

Page 117: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def jailhouseRockdef loveMeTender

def rockAroundTheClock = [1,2,3]

false?null:true?[null]:[1,2,3]

Page 118: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def jailhouseRockdef loveMeTender

def rockAroundTheClock = [1,2,3]

false?null:[null]

Page 119: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

def jailhouseRockdef loveMeTender

def rockAroundTheClock = [1,2,3]

[null]

Page 120: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Как мы это чиним?

(jailhouseRock?:[])+(loveMeTender?:[])+(rockAroundTheClock?:[])

Ну, вы в курсе, да?

Page 121: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Бенчмаркнем на троих?

Page 122: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

class Test {

void run() {

long start = System.nanoTime()

try {

throw new Exception('fail!')

}

finally {

long end = System.nanoTime()

long time = end - start

println time

}

}

}

new Test().run()

A. 254106635 Caught: java.lang.Exception: fail!

B. Caught: java.lang.Exception: fail!254106635

C. MissingPropertyException: No such property: time for class: Test

D. Не побежит

Page 123: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 124: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 125: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 126: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Как работает finally?

def a

try {

//хрень или случится, или нет

a = 'a'

} catch (Exception e) {

a = 'a'

throw e

}

try {

//хрень или случится, или нет

} finally {

def a = 'a'

}

Page 127: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

А вот что нам сгенерилосьlong start = System.nanoTime()

long end //это сгенерилось

//а где мой long time?!

try {

throw new Exception('fail!')

end = System.nanoTime()

time = end - start

println time

} catch (Exception e){

end = System.nanoTime()

time = end - start

println time

throw e

}

Page 128: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
Page 129: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Как мы это чиним?

class Test {

void run() {

long start = System.nanoTime()

try {

throw new Exception("fail!")

}

finally {

long end = System.nanoTime()

long time

time = end - start

println time

}

}

}

new Test().run()

Page 130: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Как мы еще это чиним?

long start = System.nanoTime()

try {

throw new Exception('fail!')

}

finally {

long end = System.nanoTime()

long time = end – start

println time

}

Page 131: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

А еще можно вот так

@CompileStatic

class Test {

void run() {

long start = System.nanoTime()

try {

throw new Exception('fail!')

}

finally {

long end = System.nanoTime()

long time = end - start

println time

}

}

}

new Test().run()

Кстати, время изменилось с 254106635 на 56845

Page 132: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Выводы

Page 133: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

1. Пишитечитабельныйкод

2. Комментируйте всетрюки

3. Иногда этобаг

4. Пользуйте static code analysis - intellij IDEA!

5. Rtfm

6. Скобки! Всегда добавляйте скобки!

Page 134: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Мыпродолжаемразвлекаться! (смотритекакиеужефутболочкиняшные!)

Наткнулисьнапаззлер? Давайтеегосюда!- puzzlers jfrog.com- Groovypuzzlers

Page 135: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Вот, мы рассылаем футболки, честно!

Page 136: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses

Понравилось?Хвалитенасвтвиттерескорее!

groovypuzzlers- Groovypuzzlers- jekaborisov- jbaruch

Непонравилось?/dev/null

Page 137: The Epic Groovy Puzzlers S02: The Revenge of the Parentheses