3

It is stated in the specifications and the requiremnets of the project, that

Id of Product should not be changeable..it is of type Long

Does it mean, it must be immutable? If yes, how to check for immutability of an object programmatically?

Marvin
  • 13,325
  • 3
  • 51
  • 57
Amrmsmb
  • 1
  • 27
  • 104
  • 226
  • _Does it mean it must be immutable ?_ : Yes. _How to check immutability or not of an object ?_ : Do you mean programmatically or by design ? – Arthur Attout Sep 15 '19 at 13:28
  • @ArthurAttout programmtically..i modified the question# – Amrmsmb Sep 15 '19 at 13:29
  • In general, there are two different pathways of detecting if an instance of an object is immutable; at compile time or at run time. At present, Java's design and platform doesn't really enable detection at compile time. I have created a very small Open Source library that will detect it at runtime. I describe the general solution as a StackOverflow Answer (which contains the link to Github where the code is published) located here: https://stackoverflow.com/a/75043881/501113 – chaotic3quilibrium May 10 '23 at 16:30

4 Answers4

2

does it mean, it must be immutable?

Yes, "not changeable" and "immutable" are synonyms.

how to check immutability or not of an object

(see below for updated answer for updated question)

By looking at its documentation and API of the object's class. If it doesn't provide any mutation operations (setters, etc.), then the object is immutable. The class would also need to be final or have no protected fields, since otherwise you could subclass it and modify the protected fields.

Long is immutable, for instance (unless you use reflection to break into a specific implementation). If you look through its method list, it doesn't provide any mutator operations, and it's a final class.


After this answer was posted, you modified the question to:

how to check immutability or not of an object programmatically

I don't think you can. There's nothing in reflection that tells you whether a method is a mutator or not, and it would be extremely unreliable to make assumptions based on method names. Of course, if the object's class is final and offers no instance methods at all, that probably means it's immutable. But lots of immutable classes have instance methods (including Long).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • can we check that programmatically..is there any where to do so – Amrmsmb Sep 15 '19 at 13:30
  • 1
    @user2121 - I don't think so. I can't see why you would need to. – T.J. Crowder Sep 15 '19 at 13:32
  • @user2121: there's no simple flag or anything like that, if that's what you're looking for. But one can check most of the things one would check manually programmatically, but it's not usually worth it (because most of the time you want to verify that a whole *type* is immutable and not just a specific instance which sometimes can't be done programmatically (for example a `List` field may or may not be immutable, depending on what it references). – Joachim Sauer Sep 15 '19 at 13:33
1

Yes you can determine whether an object is immutable. However, it is very complicated business, so a solution would not fit within an answer here on Stack Overflow.

There are two approaches to determine whether a class is immutable:

  • Via static analysis
  • Via runtime checking

An existing static analysis tool is MutabilityDetector at https://github.com/MutabilityDetector.

An existing runtime checking tool is Bathyscaphe at https://github.com/mikenakis/Bathyscaphe (I am the author.)

In my opinion, static analysis can be useful at certain times and under certain scenarios, but it does not provide a complete solution to the problem at all times. A complete solution requires runtime checking as I explain on my blog here: https://blog.michael.gr/2022/05/bathyscaphe.html, and that's why I have written Bathyscaphe.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
  • That's a very nice solution. It is very close to the one I describe in my StackOverflow answer here: https://stackoverflow.com/a/75043881/501113 – chaotic3quilibrium May 10 '23 at 16:31
  • I've just added your answer into my answer. I did so as the needs in this area can be quite varied. And it is very likely your solution is superior to mine for at least some subset of this whole domain. Perhaps even all. If we provide enough Open Source options, it can only help the overall Java community. Tysvm, again for creating your solution. – chaotic3quilibrium May 10 '23 at 16:40
  • 1
    @chaotic3quilibrium I looked at your code and I must admit I do not understand how it works. Would you like to exchange e-mails and talk about it? (Either via e-mail or perhaps even over video.) On my stack overflow profile there are instructions for finding my e-mail address . – Mike Nakis May 10 '23 at 18:57
  • 1
    @chaotic3quilibrium actually I will read this https://stackoverflow.com/a/75043881/773113 and hopefully I will understand. But my invitation still stands to talk about it at some point in the future, since we both have this common interest. – Mike Nakis May 11 '23 at 09:40
  • 1
    I'd love to video chat. I will hit you up on your email. – chaotic3quilibrium May 11 '23 at 15:59
0

The issue is not whether 'Long' is immutable; the issue is whether the the id of a 'Product' is immutable.

You provide immutability of the id by making the id field private, by not implementing any method that will change the id, and by not writing any code in the Product class that changes the id.

Why isn't the immutability of Long relevant? Consider this example that fails to meet your requirement that the id should not be changeable:

class Product {
    private Long id;
    Product() { id = 42; }
    Long getId() { return id; }
    void setId(Long newId) { id = newId; }
       :
}

All of those Longs are themselves immutable, but the product id changes nevertheless: because setId assigns a different immutable Long value to the id member.

However, if you just delete that setId method (and don't write anything similar in the Product class) then the product id is now not changeable.

0

how to check immutability or not of an object programmatically?

We can't. Moreover I don't feel this must be done programmatically. Read further,

Let's have an imaginary Exception class as below,

public class MutationOfImmutableException extends Exception {

  /**
   * 
   */
  private static final long serialVersionUID = 1L;

  public MutationOfImmutableException(String string) {
    super(string);
  } 

}

And our class (I can't think of a great name, but I guess this conveys the idea) have

public void setName(String name) throws MutationOfImmutableException {
    throw new MutationOfImmutableException("Cannot mutate this immutable instance");
}

And, in our main class, whenever someone calls setName() by mistake, the compiler warns us to handle the Exception properly.

p.setName("Anees"); // Cannot do this until handled!

In short, if you have access to the class Product which is immutable, you can throw a Checked Exception from setId(), to avoid everything going haywire!

Better still, make your setters private so that you cannot even encounter this scenario.

Mohamed Anees A
  • 4,119
  • 1
  • 22
  • 35