How Much Immutability Is Enough?

  • View
    1.241

  • Download
    0

  • Category

    Software

Preview:

Citation preview

/22@yegor256 1

How Much Immutability Is

EnoughYegor Bugayenko

/22@yegor256 2

object is a representative

/22@yegor256 3

File f = new File(“picture.jpg”); if (f.length() > 1000) { f.delete(); }

/22@yegor256 4

immutability means loyalty

/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; } }

/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; } }

/22@yegor256 7

thread-safe

/22@yegor256 8

List<String> list = new ArrayList<>(); list.add(“x”); // thread A list.add(“y”); // thread B

/22@yegor256 9

failure atomicity

/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; } }

/22@yegor256 11

no identity mutability

/22@yegor256 12

Map<Book, Boolean> map = new HashMap<>(); book.setId(1); map.put(book, true); book.setId(2); map.put(book, true);

/22@yegor256 13

side effect free

/22@yegor256 14

void print(Book book) { System.out.println( “book ID is: ” + book.getId() ); book.setId(123); }

/22@yegor256 15

no temporal coupling

/22@yegor256 16

request.setURI(“http://google.com”); request.setMethod(“GET”); request.addHeader(“Accept”, “text/html”); String body = request.fetch();

/22@yegor256 17

trust

/22@yegor256 18

monster objects

/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();

/22@yegor256 20

object composition

/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@yegor256 22

www.yegor256.com

Recommended