Advertisement
Advertisement

More Related Content

Advertisement
Advertisement

How Much Immutability Is Enough?

  1. /22@yegor256 1 How Much Immutability Is Enough Yegor Bugayenko
  2. /22@yegor256 2 object is a representative
  3. /22@yegor256 3 File f = new File(“picture.jpg”); if (f.length() > 1000) { f.delete(); }
  4. /22@yegor256 4 immutability means loyalty
  5. /22@yegor256 5 class Book { private int isbn; private String title; public setIsbn(int isbn) { this.isbn = isbn; } public setTitle(String title) { this.title = title; } }
  6. /22@yegor256 6 class Book { private final int isbn; private final String title; public Book(int isbn, String title) { this.isbn = isbn; this.title = title; } }
  7. /22@yegor256 7 thread-safe
  8. /22@yegor256 8 List<String> list = new ArrayList<>(); list.add(“x”); // thread A list.add(“y”); // thread B
  9. /22@yegor256 9 failure atomicity
  10. /22@yegor256 10 class Numbers { private int[] array; private int position; void add(int x) { this.position++; if (x < 0) { throw new Exception(“only positive”); } this.array[this.position] = x; } }
  11. /22@yegor256 11 no identity mutability
  12. /22@yegor256 12 Map<Book, Boolean> map = new HashMap<>(); book.setId(1); map.put(book, true); book.setId(2); map.put(book, true);
  13. /22@yegor256 13 side effect free
  14. /22@yegor256 14 void print(Book book) { System.out.println( “book ID is: ” + book.getId() ); book.setId(123); }
  15. /22@yegor256 15 no temporal coupling
  16. /22@yegor256 16 request.setURI(“http://google.com”); request.setMethod(“GET”); request.addHeader(“Accept”, “text/html”); String body = request.fetch();
  17. /22@yegor256 17 trust
  18. /22@yegor256 18 monster objects
  19. /22@yegor256 19 reader = new Reader(); reader.setFile(“/tmp/names.csv”); reader.setFormat(“CSV”); reader.setColumn(3); reader.setAllCaps(true); reader.setCache(true); List<String> x = reader.read();
  20. /22@yegor256 20 object composition
  21. /22@yegor256 21 List<String> x = new CachedList<>( new AllCaps( // List<String> new OneColumn( // List<String> new CSV( // List<List<String>> new LinesFromStream( // List<String> new FileInputStream( new File(“/tmp/names.csv”) ) ) ), 3 ) ) );
  22. /22@yegor256 22 www.yegor256.com
Advertisement