Strategy to make a mutable class immutable

Hi,
i posted this topic in the wrong forum:
http://forum.java.sun.com/thread.jspa?threadID=5129395&messageID=9463016#9463016
Could you help me?
(I mentioned it already to the moderator)

class Immutable {
final Mutable delegatee;
public Immutable(Mutable m) {
delegatee = m; // <---- You must create adefensive copy of m first.
ImmutableChild getChild() {
return new ImmutableChild(delegatee.getChild());
Note that you must create a defensive copy of the
Mutable object in your Immutable constructor.
Otherwise the caller can modify the supposedly
Immutable through the Mutable reference it passed to
the constructor.Like Stefan, i don't see your point. In this example, the only caller who can change the original mutable object, is the wrapper class. But that's no problem because the wrapper is designed by the creator of the mutable object.
If you look to my specific problem, and you create a class SourceUnit, who has a reference to the class ImmutableAST, which is an immutable wrapper of my AST node class, i don't see how the client, that calls the method instanceOfSourceUnit.getImmutableAST() can modify the original abstract syntax tree (under condition that the the wrapper class does not delegate to original AST methodes that can change the state of the tree and that the fields it returns are also immutable (wrapper) classes)

Similar Messages

  • How can 1 make an object of user defined class immutable?

    Hi All,
    How can one make an object of user defined class immutable?
    Whats the implementation logic with strings as immutable?
    Regards,

    Hi All,
    How can one make an object of user defined class
    immutable?The simple answer is you can't. That is, you can't make the object itself immutable, but what you can do is make a wrapper so that the client never sees the object to begin with.
    A classic example of a mutable class:
    class MutableX {
        private String name = "None";
        public String getName() {
            return name;
        public void setName(String name) {
            this.name = name;
    }I don't think it's possible to make this immutable, but you can create a wrapper that is:
    class ImmutableX {
        private final MutableX wrappedInstance;
        public ImmutableX (String name) {
            wrappedInstance = new MutableX();
            wrappedInstance.setName(name);
        public String getName() {
            return wrappedInstance.getName();
        // Don't give them a way to set the name and never expose wrappedInstance.
    }Of course, if you're asking how you can make your own class immutable then the simple answer is to not make any public or protected methods that can mutate it and don't expose any mutable members.
    Whats the implementation logic with strings as
    immutable?
    Regards,I don't understand the question.

  • Immutable Vs Mutable Classes

    Hi.
    I want to know the following:
    1. What are immutable classes/objects?
    2. How to implement an immutable class?
    3. Is Math class immutable? I know it's final but is it immutable? what's the difference?
    4. Difference between Immutable/Mutable class - Implementation wise...
    Thanks

    Hi.
    I want to know the following:
    1. What are immutable classes/objects?An immutable object is one whose internal state (its fields or instance variables) cannot be changed once it has been created. An immutable class... I guess that would be a class whose objects are immutable.
    2. How to implement an immutable class?Make all instance variables private and do not provide any methods that change them.
    3. Is Math class immutable? I know it's final but is
    it immutable? what's the difference?The question doesn't apply, because you cannot create an object of class Math. The modifier "final" means that you cannot declare a subclass of the class; it has nothing to do with whether its objects are immutable.
    4. Difference between Immutable/Mutable class -
    Implementation wise...?
    >
    Thanks

  • Making a class immutable

    Ho w to make a class immutable??
    Thanx in advance

    Example
    import java.util.Date;
    * Planet is an immutable class, since there is no way to change
    * its state after construction.
    * @is.Immutable
    public final class Planet {
      public Planet (double aMass, String aName, Date aDateOfDiscovery) {
         fMass = aMass;
         fName = aName;
         //make a private copy of aDateOfDiscovery
         //this is the only way to keep the fDateOfDiscovery
         //field private, and shields this class from any changes
         //to the original aDateOfDiscovery object
         fDateOfDiscovery = new Date(aDateOfDiscovery.getTime());
      //gets but no sets, and no methods which change state
      public double getMass() {
        return fMass;
      public String getName() {
        return fName;
      * Returns a defensive copy of the field.
      * The caller of this method can do anything they want with the
      * returned Date object, without affecting the internals of this
      * class in any way.
      public Date getDateOfDiscovery() {
        return new Date(fDateOfDiscovery.getTime());
      // PRIVATE //
      * Primitive data is always immutable.
      private final double fMass;
      * An immutable object field. (String objects never change state.)
      private final String fName;
      * A mutable object field. In this case, the state of this mutable field
      * is to be changed only by this class. (In other cases, it makes perfect
      * sense to allow the state of a field to be changed outside the native
      * class; this is the case when a field acts as a "pointer" to an object
      * created elsewhere.)
      private final Date fDateOfDiscovery;

  • How to make a class immutable?

    I hav attend the interview where they ask this question.
    I know little bit is Make the class final and declare all variables as static final .
    Can any Help me.
    This question

    Thi is just my opinion;
    An immutable object is an object that once created, it's values can no longer be changed.
    Thus an immutable object could be an object that allows it's values to be changed only when created with the use of the constructor, and only has get methods to retrieve those values (no set methods).
    @Peetzore
    Defining them as final is something I never did, however it makes sense :) and will start doing so as well
    Regards,
    Sim085

  • I want to make this class immutable. How to optimize performance?

    Hi,
    I designed an immutable class for other people to use. And I'm wondering if there's any way to optimize it for performance.
    ie.
    class MyImmutableList
      final List myList;
      public MyImmutableList(List list)
        myList = list;
      public MyImmutableList append(Item item)
        List copy = myList.copy();
        copy.append(item);
        return new MyImmutableList(copy);
    }But I find that many times, other people use the class like this:
    someList = someList.append(item);So in a case like this, append() is unnecessarily making a copy of the list.
    Is there anyway to optimize this?
    Thanks
    -Cuppo
    Edited by: CuppoJava on 20-Jul-2008 5:44 AM
    Edited by: CuppoJava on 20-Jul-2008 5:44 AM

    DrClap wrote:
    Well, of course, what else should they do when the method returns an ImmutableList?
    What I would do with that append() method would be to remove it from the API entirely. The class is supposed to be immutable? Then it doesn't need an append() method. Unless, of course, the append() method isn't meant to change the state of the object, which seems a bit, let's say, unintuitive. Returning a copy of the list with the object appended then wouldn't change the state of the object, but it would return a new object. Which in fact is what the code does. But why? I'm like those other people, I would do that too. I don't understand the purpose of the method.The Defence calls java.math.BigDecimal
    >
    BigDecimal, would it be fair to say, you are an immutable class?
    It would.
    Would it also be true to say that you have an add() method?
    I do
    And would it be fair to say that adding could be construed as a mutating operation?
    I suppose so
    And what does this method do, given that you claim to be immutable?
    It returns a new object which is the result of the add() operation
    Thankyou

  • Trying to make a square class

    hi i am trying to write a class that creates a square but it has to use to use the rectangle package so far i get an error cannot not find symbol on this line square = new Rectangle(0,0); and i get errors when i return my x and y variables if anyone has any ideas please i need some help thank you
    import java.awt.Rectangle;
    public class square
         private int length;
      private int width;
         public square ()
              square   = new Rectangle(0,0);
         public square (int length, int width)
             square = new Rectangle(0,0,length, width);
             this.length = length;
              this.width = width;
          /*Constructor:*/
        public square(int x, int y, int length, int width)
              square = new Rectangle(x, y, width, length);
                 this.length = length;
             this.width = width;
      public int getLength()
        return length;
      public int getWidth()
        return width;
      public int getX()
           return x;
      public int getY()
           return y;
      public void setBounds()
      return side;
    }

    You realize that by definition a square has equal sides? You don't need a width or a height, you just need a length. My "Square" class would only have a getLength() method and possibly setLength() if you want it to be mutable. If this is intended for use with AWT you could subclass Rectangle and guarantee that all sides are equal. Given your current design it would be trivially easy for me to create a Square that is in fact not a square at all.
    public class Square {
        private Rectangle rect;
        public Square(int x, int y, int length) {
            super();
            rect = new Rectangle(x, y, length, length);
        public Rectangle getRectangle() {
            return rect;
    }Of course, they could easily modify that Rectangle to make it not be a Square anymore. You could change the code to make a defensive copy. Then they could change the Rectangle, but it wouldn't affect you, so your Square would always return a square even if they made the returned Rectangle not a square at some later point. You'd do that like so:
      * Returns a square rectangle.  The returned Rectangle is mutable
      * and as such it could be mutated to no longer be a square.  It is the
      * responsibility of the client to ensure this does not happen.  Each
      * returned Rectangle is unique and mutations in one will not affect
      * the others.
      * @return A Rectangle that is a perfect square.
    public Rectangle getRectangle() {
        return new Rectangle(rect);
    }You could subclass Rectangle, but it's internals are exposed so you couldn't ever guarantee your Square was a square. Alternatively it looks like you could subclass Rectangle2D or RectangularShape and just be sure to override anything that could mutate your Square into something not a square. Also, you could just implement the Shape interface if that suits your purposes.
    Just some things to think about.

  • How to make a Exception class in java ?

    I want to make a class called SomeException. I want to throw this exception from my class Myclass. How to do it ??

    Just let SomeException extend Exception (or RuntimeException) and throw it the same way you'd throw any other exception. There's no magic involved.

  • Don't know how to make my main class import a jar file

    OK, the title doesn't make much sense but here are my create-jar.bat and manifest files:
    create-jar.bat:
    jar cvmf manifest.txt dassimul-admin.jar player/ admin/ com/ connector/ common/ *.class
    manifest.txt:
    Main-Class: admin.DASAdmin
    the problem is that in connector/ folder there is the jdbc mysql connector driver (.jar file).
    in Eclipse I can add this jar to the Java Build Path, so the program runs.
    When I double-click the dassimul-admin.jar file, I get a Class Not Found Exception
    C:\MYWORK\dassimul>java -jar dassimul-admin.jar
    FATAL ERROR WHILE LOADING SQL DRIVER: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    I think that the problem lies in the fact that admin.DASAdmin can't see and import the jar file in connector/ folder... am I right?

    It looks like you are putting the mysql jar file inside the dassimul jar. That won't work unless you write custom code. You should use the Class-Path attribute of the manifest to define a relative path(s) to the other jar(s) that you need to use.
    [http://java.sun.com/docs/books/tutorial/deployment/jar/index.html]

  • Best strategy to make commits by group of 100/200 insert/update

    Hi,
    I have a Java batch written in Java and i want to improve performances when writing to database.
    For 6000 lines of inserts, i 'd like to group insert by 100/200 in a Unit Of Work then commit.
    - i should use the methode useBatchWriting to group the inserts
    - in my class, i declare a global variable for my UnitOfWork...before beginning the 200 iterations, i do the acquire of this Unit Of Work...after the 200 iterations, commit then release the UnitOfWork. Then reuse it (acquire..) before the next 200 iterations..etc etc.. I do not know if this a good strategy or if i should release uow once all the iterations have finished.
    Thanks for your advice
    Laurent

    I applied what you suggested yesterday , but stll have problems
    One UnitOfWork ..do the acquire before the first 100 inserts
    Commit
    ReAcquire UnitOfWork without releasing uow object
    Next 100 inserts
    commit etc...
    Doen't work... Java freeze .
    I'm working with TL 9.0.3.4 in jdk 13
    So i came back on my first version : Acquire a Unit Of Work for each row, insert, commit, release...but the performances are not good at all
    I'd really like to batch inserts by groups of 100/200 rows
    Laurent

  • Strategy for mapping existing Java classes to db uing toplink

    I have simple POJO, I used the JDev Class Diagram to add relations to the POJO and then tried to map using Toplink to Database. Is this the correct Strategy? or Should I directly use POJOs without the relationsships, to map to DB using TOPLINK?

    Assuming your schema is as follows
    User table has a primary key ID with other columns
    MentorRel table has two columns (e.g. mentor_id and protege_id) that are FKs pointing to the User.ID ( primary key)
    I would suggest that you normalize your schema further by creating a column in User table called MentorID which will be a self referencing FK. This will automatically capture your 1:M relationship between a Mentor and Protege (as a User can be a Mentor or a Protege). You will also get rid of the MentorRel table this way.
    Once you are done, you will be able to map this nicely. Let me know if this does not work.

  • Is it possible to make a local class accessible in SE24 subclasses?

    G'Day,
    The scenario is simple: I have a global class created in SE24 with a local helper class defined in the local definitions/implementations sections. The issue is anything declared here is private; however I would like my local class to be available in the subclasses of the global class as well. In other words I want a protected local class.
    ZCL_SUPER  --> contains local utility class LCL_HELPER
        |
        V
    ZCL_SUB    --> needs to make use of LCL_HELPER's methods.
    I've messed about with different definitions and FRIENDS but no joy.
    I can think of two alternatives:
    1. Write a protected wrapper method in zcl_super to expose each lcl_helper method to the subclasses. Annoying, cumbersome, defeats the object of using a local class in first place.
    2. Define LCL_HELPER in an include which is added to all subclasses. This effectively makes it public as I no longer control where LCL_HELPER is used. (Unless I do funky stuff with packages which we don't do on this project).
    Any better suggestions/ideas/workarounds?
    Cheers,
    Mike

    Hi Naimesh,
    Thanks for the input. Interesting idea about interfaces, I need to play around with this a little.
    I don't agree what I'm trying to do would violate encapsulation. I'm after the same visibility level as other class component type. i.e. methods can be private, protected or public. Classes can be local or global - a protected class visible to subclasses would fit the principles quite well.
    Consider a global class GADGET which has a protected attribute WIDGET, type ref to a local class. The widget's methods and attributes should really be separate because it is it's own entity, but at the same time it has no business in the wider SAP system. ==> Perfectly sensible use of a local class.
    Now, this widget can turn, open, close, light up. So in a GADGET method I can say WIDGET->TURN( ). Create a subclass of GADGET and boom, all such code working with WIDGETs is broken. In some ways it makes local classes a little un-future-proof.
    The bothersome thing about the workarounds is that they de-object-orient the two objects by forcing us to create protected methods TURN_WIDGET LIGHT_WIDGET OPEN_WIDGET etc. on the GADGET class. Which goes back to my original point that there's little benefit of creating a local class if we need to do this....
    Or am I missing something?
    Cheers,
    Mike

  • Keeping a queue class immutable

    Hi,
    I recently got hooked on the concept of immutable classes. I'm not really sure why, but anyway...
    I have a class that queues up tasks to a worker thread for execution, which is currently immutable. However, I never implemented a way to stop the worker thread if I wanted the queue to shutdown, so I'm trying to come up with a way to do so while retaining the immutability of the class.
    Normally, I'd have a boolean value, and then set the boolean to false or true or whatever, and then the run() method in the worker thread would return. However, If I have to set a boolean, it would break the concept of immutability.
    So while this question may seem somewhat ridiculous, I'm more curious than anything to see if there's a way to solve this problem.
    Here's my queue class, with an incomplete shutdown() method, which I'd like to, in the future, "stop" the ThreadWorker thread:
    public final class ThreadQueue {
         private final ExecutorService pool;
         private final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(5);
         public ThreadQueue() {
              pool = Executors.newSingleThreadExecutor();
              (new Thread(new ThreadWorker())).start();
         public synchronized void addToQueue(Runnable task) {
              try {
                   queue.put(task);
              } catch (InterruptedException ignored) {
         public void shutdown() {
         private final class ThreadWorker implements Runnable {
              public void run() {
                   for (;;) {
                        try {
                             pool.execute(queue.take());
                        } catch (InterruptedException ignored) {
    }If I'm just being pedantic with the whole immutability thing, so be it; I'm really curious.
    Any advice will be greatly appreciated.
    Thanks,
    Dan

    Well it looks as if I need to look up the definition of immutable again. I didn't think that adding things to a list would constitute changing the state of the object, but now that I think about it, that obviously does.
    Anyway, my question is answered; the question was a bit ridiculous like I had thought, but oh well.
    > >
    It seems to me tho that while shutdownNow could potentially stop the pool (which it seems is just 1 thread), it won't stop the other threads... BTW, all the threads seem to do is to loop and tell the single executor to run the next job... Are they actually running the jobs? Otherwise, why do you need more than 1 of them?
    As to this, shutting down the ExecutorService stops that thread, and it won't stop the thread running from ThreadWorker (which is why I changed my code as I'll show later). Anyway, the point of ThreadWorker is to execute each task in a "background" thread. Actually, since the ExecutorService runs in its own thread, it seems as if ThreadWorker is pretty worthless. If I added pool.execute(queue.take());it doesn't seem like it'll matter. Looks like I'll have to try that out and see what happens.
    Anyway, here's the most recent update of my code, with the new shutdownQueue() method and a new loop in ThreadWorker:
    public final class ThreadQueue {
         private final ExecutorService pool;
         private final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(5);
         private volatile boolean stopThreadWorker;
         public ThreadQueue() {
              pool = Executors.newSingleThreadExecutor();
              stopThreadWorker = false;
              (new Thread(new ThreadWorker())).start();
         public synchronized void addToQueue(Runnable task) {
              try {
                   queue.put(task);
              } catch (InterruptedException ignored) {
         public void shutdownQueue() {
              stopThreadWorker = true;
              pool.shutdownNow();
         private final class ThreadWorker implements Runnable {
              public void run() {
                   while(stopThreadWorker) {
                        try {
                             pool.execute(queue.take());
                        } catch (InterruptedException ignored) {
    }Thanks for all the help!

  • When is the next Strategy Management (SSM) Technical Overview class?

    The next SSM class is February 4-8 in Chicago. To register:
    1. Go to http://www50.sap.com/useducation/index.asp
    2. In the Course Search Field type in CPM.
    3. On the list select  TZCPM1 SAP Strategy Management Technical Overview (Chicago).
    Any questions?

    The next SSM class is February 4-8 in Chicago. To register:
    1. Go to http://www50.sap.com/useducation/index.asp
    2. In the Course Search Field type in CPM.
    3. On the list select  TZCPM1 SAP Strategy Management Technical Overview (Chicago).
    Any questions?

  • Planning Strategy for make to order!

    Dear Gurus!
           My client has Scenario like this:
                  By period they has customer forecast. 1 fininish good may be ordered by many customer.
                  Base on this customer forecast, they will buy raw material seprately follow 1 customer (customer want to make sure material buy on time, and they have staff in my client to follow).
                  When real sale order come, it will consump forecast (finish good and raw material) by itself.
                  IF my client wants to use this raw material for add-hoc case. They must be accepted by customer and buy to full fill.
         Do you have any configure or busness process or whatever  solution, please advise me.
         Thank you in advance.
         Regards,
    Tony

    Hi Tony,
    Strategy 50 is for the MTO scenario wherein you do the production specific to the customer, in general words, you cannot swap sales order stock. So you can use strategy 50, as you are saying that it is customer oriented, and definitely customers are going to give orders.
    I think are you saying that the raw material for the finished product which the customers of your client are needing can also be used by your own client, right.
    Strategy 50 is planning without final assembly so here you can plan for the components for the final assembly without assembling and when the sales order comes then it can consume the PIR (planned independent requirement). So the production is done for the components till the finished product level and kept in stock, then when the sales order comes into picture then this slaes order can consume the PIR.
    "IF my client wants to use this raw material for add-hoc case. They must be accepted by customer and buy to full fill." what did you meant by this line ? Please elaborate on this....
    Regards,
    Abhijeet

Maybe you are looking for

  • Help! How can I transfer all my sms from my old iphone to my new one?

    Someone can help me? Sorry for my English!!!

  • PO Value Exceeded

    Dear Friends, I've generated a PO for Rs. 100. I have to pay advance to Vendor Rs. 50. While creating a Down Payment Request (f-47) for Rs. 50, I'm getting a Error Message as 'Purchase order Value Exceeded'. Could any body please help me? with regard

  • Lumia 720 battery

    Hi everybody... Anyone having Lumia 720 ? What about the battery backup u are getting? I am getting only 6-7 hours of net using only. Battery drain very fast. After full charge it shows only 16 hours stanby left with battery saver on. Is this normal?

  • CRM 4.0 SR1 install: DBIF_RSQL_INVALID_REQUEST

    Hello, After installation of the ABAP stack of CRM 4.0 SR1 with the export of IDES we got the following error after login into the system: runtime error DBIF_RSQL_INVALID_REQUEST for DOKTL. Every cluster/pool table generates this error, when trying t

  • Need the win7 64 bit download of elements premiere 10

    need the win7 64 bit download of elements premiere