Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

7 Sins of Java fixed in Kotlin

502 views

Published on

Since the release of Java 1.4.2 most of the developers thought the language designed by Sun was a blast for object-oriented programming and through the years a lot of so-called Java-design-patterns infected object-thinking and development process showing us tedious language syntax and dark magics. Then, 15 years later, a language by JetBrains tries to simplify the things: Kotlin, what is it? What does it try to simplify? Let's see at least 7 inconvenient Java aspects fixed in Kotlin

Published in: Technology
  • Be the first to comment

7 Sins of Java fixed in Kotlin

  1. 1. 7 Sins of fixed in otlin Made with ❤ and ♫ Twitter @lucaguada
  2. 2. ● Java/JS developer ● Poem performer ● Mountain biker ● Blade Runner ● DC/Manga Comicbooks reader ● Go Nagai Animes watcher ● PS4 gamer ● Vanilla Pudding eater ● Ellen Page lover (well I wish...) Luca Guadagnini @lucaguada @tryIO who the hell… ?
  3. 3. public final class Optional<T> { private static final Optional<?> EMPTY = new Optional<>(); private final T value; private Optional() { this.value = null; } public static<T> Optional<T> empty() { @SuppressWarnings("unchecked") Optional<T> t = (Optional<T>) EMPTY; return t; } private Optional(T value) { this.value = Objects.requireNonNull(value); } … public static <T> Optional<T> ofNullable(T value) { return value == null ? empty() : of(value); } … public Optional<T> filter(Predicate<? super T> predicate) { Objects.requireNonNull(predicate); if (!isPresent()) return this; else return predicate.test(value) ? this : empty(); } } Lust: “If you wanna be bad, you gotta be good” ● public not default? ● EMPTY encapsulated within? ● iaargh!! an @Annotation! ● casting style stuck to 90’s ● runtime null-checking ● methods are too long to write
  4. 4. ● public and final class by default! ● always know when a value is nullable ● inline method definitions! ● semi-colon (;) no-more! ● static methods no-more! ● new keyword no more! just call constructor as-is ● lambda-expr. are first-class citizen ● typealias!! ● out part of new generics system (too long to explain it, next time ;) ) Lust: Talk to me pleasantly // Kotlin 1.1 typealias Predicate = (T) -> Boolean class Optional<out T>(private val value:T?) { private constructor(): this(null) … fun filter(predicate: Predicate) = if (value?.let(predicate) ?: false) this else Optional<T>() fun get() = this.value ?: throw IllegalStateException() … } val o = Optional(“Hello Kotlin”) val kotlin = o.filter { it.contains(“Kotlin”) }.get() println(“Java? $kotlin”)
  5. 5. Gluttony: Static methods // Java 6/7 public class NumUtils { public static int max(int… nums) { … } } // Java 8 public interface NumUtils { static int max(int… nums) { … } } int[] nums = new int[] {1, 2, 3}; int max = NumUtils.max(nums); ● ugly procedural style ● code-smell ● silly class/interface names ● lead to a ton of duplicated code ● no use case, just a helper ● hard to understand where it’s used
  6. 6. Gluttony: Extension methods // Kotlin 1.1 fun Array<Int>.max():Int { ... } val nums = arrayOf(1, 2, 3) val max = nums.max() ● Array is an object, so let’s use it in that way! ● max is a method which has decorated the Array object in order to extend it ● with a single dot we can know if something is already implemented, without seek for a particular method through every single package to find that particular SomethingUtils class ● Self-documented: “I find max-number in the array you’re actually using, not any unknown array which I don’t know where it comes from”
  7. 7. ● a couple of minutes to write ● two properties, then 4 methods! before Java7 has been proposed «property» syntax… but it was rejected ● any Printable implementation must handle IOException ● each interface/class, we have a file ● primary constructors with DI are not standard ● still possible to define abstract interfaces, because of Java 1.0!! Cupidity: Conservative Tradition public abstract interface Printable { void print() throws IOException; } public class Book implements Printable { private String title; private String text; public Book(String title, String text) { this.title = title; this.text = text; } // getters and setters - 4 methods by the way @Override public void print() throws IOException { // print on something that may throw an IOException, but is that // really needed? } // and of course toString, equals, hashcode overriding too }
  8. 8. Cupidity: Progressive Legacy ● less than 5 secs ● properties are implicit ● : inspired by C++/C# ● all exceptions are unchecked ● everything can be defined in one single file ● by default all classes are Closed for modification and Open for extendibility interface Printable { fun print() } class Book(var title:String, var text:String) : Printable { override fun print() { … } }
  9. 9. Sorrow: Java Bean public class Book { private String title; private String text; public Book() {} public Book(String title, String text) { … } public void setTitle(String title) { this.title = title; } public String getTitle() { return this.title; } public void setText(String text) { this.text = text; } public String getText() { return this.text; } @Override public String toString() { return “Title: ” + title + “ Text: ” + text; } @Override public boolean equals(Object obj) { Book b = (Book) obj; return title.equals(b.getTitle()) && text.equals(b.getText()); } @Override public int hashcode() { return Objects.hash(title, text); } } ● it’s so 2000! (JDK 1.3) ● 2 fields, so 4 methods! ● default constructor must be there! ● implicit extension of java.lang.Object ● 1 minute to write a C-struct ● a hell lock-in to JEE frameworks! even Spring is going far away from this, Hibernate as well
  10. 10. Sorrow: Java Bean in Data class // Kotlin 1.1 - first step data class Book( var title:String, var text:String ) // second step data class Book(var title:String, var text:String) { constructor() } // but it won’t compile, Kotlin forces you to call the primary c. data class Book(var title:String, var text:String) { constructor(): this(“”, “”) } ● inspired by Scala ● properties implicit implementation ● primary c. is the real constructor you actually need ● you can define yours, but you’re forced to call the primary one (❤) ● java.lang.Object methods overrided by Kotlin (❤) ● the copy-method implemented by Kotlin is a gift from Heaven
  11. 11. Pride: Null Pointer Exception public class Book { private Writer writer; ... } public class Writer { private String fullName; ... } public String getUpperCasedWriter(Book book) { return book getWriter() getFullName() toUpperCase(); } public String getUpperCasedWriter(Book book) { if (book != null && book.getWriter() != null && book.getWriter().getFullName() != null) { return book.getWriter().getFullName().toUpperCase(); } return null; } ● null is part of your type-system! ● Null Pointer Exception?!? Java has nothing to do with pointers! C++ and Borland Turbo Pascal 7.0 does ● how can I express required fields? if you don’t use primitive types, you can’t actually (just with runtime checking) ● or you can use @Annotations! for God’s sake, don’t ● in Java8 you can use Optional to mitigate NPE, but few understand it
  12. 12. Pride: Elvis to the rescue! // Kotlin 1.1 data class Book(var writer:Writer) data class Writer(var fullName:String) fun getUpperCasedWriter(book:Book):String = book.writer.fullName.toUpperCase() // hence var mobydick:Book? = Book(Writer(“Herman Mellvile”)) getUpperCasedWriter(mobydick) // won’t compile! since mobydick is nullable and parameter is not var bartleby:Book = Book(Writer(“Herman Mellvile”)) getUpperCasedWriter(bartleby) // no problem ❤ ● null is still part of your type system, but only if you want it and it’s much more handleable anyway ● you can define required and non-required properties/parameters ● ? in called properties/methods is the Elvis-operator, if null-check fails, null will be returned immediately and no NPE ● no @Annotations used, no Optional pattern needed (but you can use it anyway with takeIf and let functional patterns)
  13. 13. Wrath: Checked and Unchecked Exceptions // Java // I want to sleep for a while but not more than 10secs public void sleepFor(long mills) { if (mills <= 10000) { Thread.sleep(mills); } else { throw new IllegalArgumentException(); } } // sorry compile error, you need to catch InterruptException public void sleepFor(long mills) { try { if (mills <= 10000) { Thread.sleep(mills); } else { throw new IllegalArgumentException(); } } catch (InterruptException ie) { // log and re-throw an unchecked exception } } ● Checked Exception: any exception that extends java.lang.Exception; InterruptException is a Checked Exception (catch it!) ● Unchecked Exception: any exception that extends java.lang.RuntimeException; IllegalArgumentException is an Unchecked Exception (no need to catch it!) ● the more you handle them, the more code is bloated, the more you’re gonna be crazy!
  14. 14. Wrath: Exception is Nothing // Kotlin 1.1 // the solution in Kotlin fun sleepFor(mills:Long) = if (mills <= 10000) Thread.sleep(mills) else throw IllegalArgumentException() // not a valid parameter fun notValidParameter():Nothing = throw IllegalArgumentException() fun sleepFor(mills:Long) = if (mills <= 1000) Thread.sleep(mills) else notValidParameter() ● There’s no checked-exception in Kotlin ● throw keyword has a different meaning: retrieves a type named Nothing, if exception is created ● Nothing says “if I’m retrieved, runtime-flow stops”
  15. 15. Sloth: Enterprise or Community? + huge ecosystem + 1st lang in the world + nerdy then Oracle + OpenJDK free and open + JVM rocks - Oracle - no one uses JEE - OracleJDK not tot.free - Enterprise driven - Java9 delay (againx3)
  16. 16. Sloth: Enterprise or Community? + Java interoperability + mix obj. and func. + adopted by Piv./Google + community driven + just take 1h to learn - func. not for all - Intellij lock-in (?) - community driven - very fast progression can you keep up?

×