Detect immutable objects

Detect immutable objects

4 Kommentare zu Detect immutable objects

A recent post demonstrated how singletons can be found in a Java application. There’s another interesting pattern which can be detected using a Cypher query: immutable objects. There are some use cases where they can be very useful, e.g.

  • thread-safe design
  • parameter or return values for non-local interfaces

What are the properties of classes representing immutable objects? Let’s look at an example:

public class Person {
  private String name;

  public Person(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }
}
  • The class has a private state, i.e. at least one field with visibility private.
  • After construction of the object all fields may only be read, i.e. all write operations are performed exclusively by constructors of the class.

Taking these two conditions the following concept can be formulated which sets a label „Immutable“ on all matching classes:

<concept id="design:Immutable">
  <description>Labels all classes with an immutable state as "Immutable".</description>
  <cypher><![CDATA[
    match
      (immutable:Class)-[:DECLARES]->(field:Field),
      (accessorMethod)-[:WRITES]->(field)
    where
      field.visibility = 'private'
    with
      immutable, collect(accessorMethod) as accessorMethods
    where
      all (accessorMethod in accessorMethods where accessorMethod:Constructor)
    set
      immutable:Immutable
    return
      immutable as Immutable
  ]]></cypher>
</concept>

Reference:
http://en.wikipedia.org/wiki/Immutable_object

About the author:

@dirkmahler

4 Comments

  1. Michael Hunger  - 2. September 2014 - 9:02

    Interesting idea. Static analysis in Cypher :)

    It would be cool to also see a constraint that reports for instance all DTO’s that are not immutable. I.e. have at least one non-private field or one non-constructor method that writes to the field.

  2. Stefan Penndorf  - 10. Oktober 2014 - 9:50

    Works good but I found a little corner case not covered by your concept: If the class has a private static (final) field than it’s not flagged IMMUTABLE though it is in my optinion.

    I just changed the lines restricting the fields:
    where
    field.visibility = ‚private‘ and
    (not has(field.static) or field.static = false)
    with

    • Dirk Mahler  - 11. Oktober 2014 - 13:14

      Seems that the concept needs some more adjustment – what about inheritance? I think we need to express the condition like that:

      A class is immutable if all fields in the class itself and its super classes are declared either

      1. static final (we may discuss about final)

      or

      2. private and only written by constructors.

      Are there any other corner cases?

Leave a comment

Back to Top