Do not declare interfaces for immutable objects
[EDIT] Where the objects in question represent Data Transfer Objects (DTOs) or Plain Old Data (PODs)
Is that a reasonable guideline?
Up to now, I've often created interfaces for sealed classes that are immutable (data cannot be changed). I've tried to be careful myself to not use the interface anywhere where I care about immutability.
Unfortunately, the interface begins to pervade the code (and it's not just my code I'm worried about). You wind up being passed an interface, and then wanting to pass it to some code that really wants to assume that the thing being passed to it is immutable.
Because of this problem, I'm considering never declaring interfaces for immutable objects.
This might have ramifications with respect to Unit Testing, but other than that, does this seem a reasonable guideline?
Or is there another pattern I should be using to avoid the "spreading-interface" problem I'm seeing?
(I'm using these immutable objects for several reasons: Mainly for thread safety since I write a lot of multi-threaded code; but also because it means I can avoid making defensive copies of objects passed to methods. Code becomes a lot simpler in many cases when you know something is immutable - which you don't if you've been handed an interface. In fact, often you can't even make a defensive copy of an object referenced via an interface if it doesn't provide a clone operation or any way of serialising it...)
[EDIT]
To provide a lot more context for my reasons for wanting to make objects immutable, see this blog post from Eric Lippert:
I should also point out that I'm working with some lower-level concepts here, such as items that are being manipulated/passed around in multi-threaded job queues. These are essentially DTOs.
Also Joshua Bloch recommends the use of immutable objects in his book Effective Java.
Follow Up
Thanks for the feedback, all. I've decided to go ahead and use this guideline for DTOs and their ilk. It's working well so far, but it's only been a week... Still, it's looking good.
There are some other issues relating to this that I want to ask about; notably something I'm calling "Deep or Shallow Immutability" (nomenclature I stole from Deep and Shallow cloning) - but that's a question for another time.
List<Number>
which can holdInteger
,Float
,Long
,BigDecimal
, etc... All of which are immutable themselves.