New Object Creation vs. Field Setters

I know this is massively context dependent, but is there some rule of thumb to follow when it comes to deciding between
i) Making an class's fields final and creating a new object with new field values when needed, and
ii) Leaving a class's fields mutable and using setter methods to alter the field.
I tend toward option one, because not only do I tend to shy away from setters, but also because it helps prevent me from accidentally maintaining an old reference. However, purely from a performance standpoint, which option should you assume is better? How many object's of X size do I have to be making per unit of time before the performance benefits of "final" are lost?
Thanks!

I've been wishing for a while that Java would add a language level concept of immutability. Either an immutable keyword or an annotation. The compiler would bitch if you declared a class immutable and each of its fields was not final and either a primitive or a reference to an immutable class. Or perhaps it could simply check that there was no assignment to any field.
It would be handy for me as a user of a class to know that it's immutable, for things like copying and thread-safety. It might or might not allow for runtime optimizations too.
As for whether to make a given class immutable, like others say--it depends on the semantics of the class. If it's intended to represent something dynamic--e.g. a clock, or a piece on a board whose position changes with time, or the state of a network interface including packet sent and received--then it will make your code clunky and nonintuitive if you have to create a new object everytime the state of the thing you're modeling changes. But if it's something that changes less frequently, or that represents a fairly static entity or "value", then make it immutable.
I do agree with duffymo: Better that an object comes out of construction in a valid and useful state. So even if the object is mutable, pass field values to the c'tor or set them to reasonable defaults inside the c'tor (e.g., "now", etc.)

Similar Messages

  • Use String Variable in New Object Creation

    Thanks to those who review and respond. I am new to Java, so please be patient with my terminoloy mistakes and fumblings. I am reading in a file and I want to create a new object based on specific field (car for example). As you will notice I grab field 8 here label sIID.
    String sIID = dts.group(8);
    BTW this regex grouping works fine. The problem is seen when I try to use the sIID variable in my new object creation process.
    DateParse sIID = new DateParse();
    My IDE is reporting "Variable sIID is already defined in the scope"
    Is this possible? The assumption is that the sIID will have different value during the processing of the file. For example, car could mean truck, sedan, etc with operators like color, number of doors, mileage, top speed, etc.

    Thanks for the reply. I have include similar and much shorter code for the sake of brevity.
    My problems are centered around the x variable/object below. Ideally this would translate to three objects PersonA, PersonB, etc that I could reference later in the code as PersonA.newname if I wanted to. Hopefully this makes sense.
    public class TestingObjects {
      public static void main(String[] argv) {
           String [] names;
           names = new String[3];
           names[0] = "PersonA";
           names[1] = "PersonB";
           names[2] = "PersonC";
           for (String x:names) {
             PN x = new PN();  // <- Problem
             x.name = x;
             x.SayName();
            System.out.println(x.newname);
    public class PN {
           String name;
           String newname;
      public String SayName() {
           newname = "Name = " + name;
           System.out.println(name);
          return newname;
    }

  • Aborting new object creation

    I want to test the input parameters to a constructor and determine if an invalid parameter has been supplied.
    If I use:
    Thingy myThingy = new Thingy("invalid value");
    is it up to the programmer of the above to catch the error, either through exception handling or some other form of error checking, and perform
    myThingy = null;
    to render the partially initialized object ready for garbage collection?
    Is there a way in the constructor itself to indicate that the object shouldn't be created and null should be returned as the result of the "new" operation?
    Thanks,
    John

    But I'd say Clem1986 still has a point. Even in the constructor
      Foo() throws Exception {
        throw new Exception("Bollocks");
      }there's the implicit call to super() and instance initializers before you arrive at throw. From JVM spec: The new instruction does not completely create a new instance; instance creation is not completed until an instance initialization method has been invoked on the uninitialized instance. Which is done above. Whether this qualifies in OP's context as completing instance creation or instantiating an object I don't know. But you could work with it in the constructor, and once you get to throw, memory has been allocated, all superclasses have been initialized (which might involve heavy allocation/computation), default values were assigned to fields and instance initializers have executed. Only now can you decide to "abort new object creation" by completing abruptly and not "returning" the reference to the newly-(partially-)created object to the caller.

  • Doubt in creation of a new object

    Hi All,
                 I have one doubt in creation of a new object.If a new object is to be created and it is not a subtype
    of any existing object, then what should we enter in the Program field for creating the object?
    I hope I am clear with my question.
    Thanks in Advance,
    Saket.

    Hi Saket,
    Following will be required for created a custom business object.
    1. Object Type - ZTEST (Internal Techincal Key)
    2. Object Name - ZTESTNAME (Technical Key Name)
    3. Name - TEST (Name of BO, it is used while selecting the object type)
    4. Description - (Short Description of BO)
    5. Program - ZTESTPROGRAM (ABAP program in which the methods of the object type are implemented)
    6. Application - A or B.. etc (Area to which your BO is related)
    Please remember that you can learn these basic things by giving F1 help on those fields and in HELP.SAP.COM.
    Regards,
    Gautham Paspala

  • Getting ORA-20001: Creation of new object is not allowed: !!

    Hi Am getting ORA-20001: Creation of new object is not allowed while enabling constraints after importing the dumps from source to target datbase,can anyone assist me to fix this issue.

    Hi Osama/Mustafa,Thanks for your quick response,can you please explain me the following things-
    1)As i don't have privilege to run the DBA_XX views,am not able to run those queries-
    SELECT OWNER, TRIGGER_NAME, TRIGGER_BODY FROM DBA_TRIGGERS WHERE TRIGGER_TYPE IN ('AFTER EVENT', 'BEFORE EVETN') AND TRIGGERING_EVENT LIKE '%CREATE%';
    can you tell me what output it'll throw,based on this output how will we fix the issue.
    2)SELECT * FROM dba_sys_privs WHERE privilege = 'UNLIMITED TABLESPACE';
    why we need to check this privilege?as i don't have privilege to run this one in my db.
    3)select * from dba_source where upper(text) like upper('%Creation of new object is not allowed%');
    as i don't have privilege to run this one in my db,already i got the object name from my logfile
    and more you have quoted"This is an error of someone that coded purposely on your database, probably dba or a developer who has privilege and again it is in a database event trigger"
    4)can you explain me much more deeper about the root cause and as already sent note to my DBA,can you explain me the solution to fix this issue ?

  • Creation of new object link for DMS

    i have searched a lot  about Creation of new object link for DMS on internet .
    and all replies  focus on that documentation :
    1.     Program two screens for the following module pools for the SAP object that is to be linked additionally:
    u2013 SAPLCV00
    u2013 SAPLCVIN
    The process logic must be according to that of screen 0204 in program SAPLCV00 and must not be changed.
    2.     Create the function module OBJECT_CHECK_XXXX (XXXX = name of the SAP object).
    i need  to know how to implement that  in more detailed step by step
    as  i know DMS and  abap also.

    Hi Reda,
    Hope the below URL will help to understand how the Process of adding a object link works.
    Enhancement Without Modification of the Object Links - Engineering Change Management (LO-ECH) - SAP Library
    Thanks & Regards,
    Seshadri.

  • Adding new object type (field BKPF-AWKEY) for BAPI posting

    Hi everyone,
    I am posting to SAP GL using an input file to read the data and transfer it to BKPF and BSEG tables.
    The problem is I have to use BAPI_ACC_DOCUMENT_POST, and it expects values for OBJ_KEY and OBJ_TYPE.. For now, OBJ_TYPE creates a problem, because if I use BKPF, it says it cannot post using this object type, as it is for SAP internal use only.
    Does anyone know how to add a new object type for the customer namespace, which can be manually used for this kind of posting? I know that the new entry must be made in tables TTYP, TTYPT, and possibly TTYPV, for which the maintainence view exists: V_TTYPV.
    How to add an entry here, or where can I find it in customizing?
    All helpful answers will be awarded.
    Thank you very much
    Srdjan

    perform fill_internal_tables.
    if check_l = 'X'.
      call function 'BAPI_ACC_DOCUMENT_CHECK'
           destination dest
           exporting
                documentheader    = gd_documentheader
                customercpd       = gd_customercpd
                contractheader    = gd_fica_hd
           tables
                accountgl         = it_accountgl
                accountreceivable = it_accountreceivable
                accountpayable    = it_accountpayable
                accounttax        = it_accounttax
               currencyamount    = it_currencyamount
                criteria          = it_criteria
                valuefield        = it_valuefield
                extension1        = it_ext
                return            = it_return
                paymentcard       = it_paymentcard
                contractitem      = it_fica_it.
               extension2        = it_ext2
               realestate        = it_re.
      write: / 'Result of check lines:'.                        "#EC NOTEXT
      perform show_messages.
    endif.
    if check_a = 'X'.
      call function 'BAPI_ACC_DOCUMENT_CHECK'
        destination dest
        exporting
          documentheader    = gd_documentheader
          customercpd       = gd_customercpd
          contractheader    = gd_fica_hd
        tables
          accountgl         = it_accountgl
          accountreceivable = it_accountreceivable
          accountpayable    = it_accountpayable
          accounttax        = it_accounttax
          currencyamount    = it_currencyamount
          criteria          = it_criteria
          valuefield        = it_valuefield
          extension1        = it_ext
          return            = it_return
          paymentcard       = it_paymentcard
          contractitem      = it_fica_it.
         extension2        = it_ext2
         realestate        = it_re.
      write: / 'Result of check all:'.                          "#EC NOTEXT
      perform show_messages.
    endif.
    if post = 'X'.
      data: l_type like gd_documentheader-obj_type,
            l_key  like gd_documentheader-obj_key,
            l_sys  like gd_documentheader-obj_sys.
      if dest = space or
         dest = gd_documentheader-obj_sys.
       post synchron
        call function 'BAPI_ACC_DOCUMENT_POST'
          exporting
            documentheader    = gd_documentheader
            customercpd       = gd_customercpd
            contractheader    = gd_fica_hd
          importing
            obj_type          = l_type
            obj_key           = l_key
            obj_sys           = l_sys
          tables
            accountgl         = it_accountgl
            accountreceivable = it_accountreceivable
            accountpayable    = it_accountpayable
            accounttax        = it_accounttax
            currencyamount    = it_currencyamount
            criteria          = it_criteria
            valuefield        = it_valuefield
            extension1        = it_ext
            return            = it_return
            paymentcard       = it_paymentcard
            contractitem      = it_fica_it.
           extension2        = it_ext2
           realestate        = it_re.
        write: / 'Result of post:'.                             "#EC NOTEXT
        perform show_messages.
      else.
      create Idoc
        it_receivers-logsys = dest.
        append it_receivers.
        call function 'ALE_ACC_DOCUMENT_POST'
          exporting
            documentheader    = gd_documentheader
            customercpd       = gd_customercpd
            contractheader    = gd_fica_hd
          tables
            accountgl         = it_accountgl
            accountreceivable = it_accountreceivable
            accountpayable    = it_accountpayable
            accounttax        = it_accounttax
            currencyamount    = it_currencyamount
            criteria          = it_criteria
            valuefield        = it_valuefield
            extension1        = it_ext
            paymentcard       = it_paymentcard
            contractitem      = it_fica_it
           extension2        = it_ext2
           realestate        = it_re
            receivers         = it_receivers
          COMMUNICATION_DOCUMENTS =
          APPLICATION_OBJECTS     =
          exceptions
            error_creating_idocs    = 1
            others                  = 2  .
        if sy-subrc = 0.
          write: / 'IDoc created'.                              "#EC NOTEXT
        else.
          write: sy-msgid.
        endif.
      endif.
    endif.
    if rev_p = 'X' or rev_c = 'X'.
      data: rev like bapiacrev,
            rev_key like ref_key.
      rev_key       = ref_key.
      rev_key(1)    = 'R'.
      rev-obj_type  = gd_documentheader-obj_type.
      rev-obj_key   = rev_key.
      rev-obj_sys   = gd_documentheader-obj_sys.
      rev-obj_key_r = ref_key.
      if rev_c is initial.
        if dest = space or
           dest = gd_documentheader-obj_sys.
          call function 'BAPI_ACC_DOCUMENT_REV_POST'
            exporting
              reversal = rev
              bus_act  = gd_documentheader-bus_act
            tables
              return   = it_return.
        else.
          it_receivers-logsys = dest.
          append it_receivers.
          call function 'ALE_ACC_DOCUMENT_REV_POST'
            exporting
              reversal                      = rev
              busact                        = gd_documentheader-bus_act
            OBJ_TYPE                      = 'BUS6035'
            SERIAL_ID                     = '0'
            tables
              receivers                     = it_receivers
            COMMUNICATION_DOCUMENTS       =
            APPLICATION_OBJECTS           =
            exceptions
              error_creating_idocs          = 1
              others                        = 2
          if sy-subrc <> 0.
            message id sy-msgid type sy-msgty number sy-msgno
                    with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
          else.
            write: / 'IDoc created'.                            "#EC NOTEXT
          endif.
        endif.
      else.
        call function 'BAPI_ACC_DOCUMENT_REV_CHECK'
          exporting
            reversal = rev
            bus_act  = gd_documentheader-bus_act
          tables
            return   = it_return.
      endif.
      write: / 'Result of Reversal Posting:'.                   "#EC NOTEXT
      perform show_messages.
    endif.
    commit work.
    chk this
    Give points if useful

  • New object type creation...in MASS transaction..

    Hi,
    I want to create new object type for Maintainace plan mass mainainace how to do it....can anybody tell me..??
    In standard MASS transaction i am not getting object type for Maintainace plan
    Regards,
    San Rao..

    hi
    O1CL-->select Table you asscosiate with class type( If it it not exists the click on New Item)
    ->Lets consider that it is MARA>double click on Plant->click on object types>click on New Item--->click on Object
    Similerly maintain class status,Org Area etc
    You can also check the existing class for Example...this will help you.
    Regards
    Sujit

  • How to show object creation in UML

    How to show object creation in UML

    In a sequence diagram, it's a line (with arrow) pointing to the new object and the <creates> or <new> tag as mentioned above.
    | obj 1  |
         |
         |    <creates>     ----------
         | -------------->  | obj 2  |
         |                  ----------or----------
    | obj 1  |
         |
         |      <new>       ----------
         | -------------->  | obj 2  |
         |                  ----------

  • It will not parse! Creating a new object in the universe

    Hi, we have a universe and BO reports. They work fine for our clients. We are on BO XI r3.1. Now, one client captures an additional piece of info. They would like to report against this and add it high up on our drilling heirarchy. "Sure, no problem". For the following I was logged in as administrator.
    The additional data field is a 3 character code.
    1) We added an additional column to the actual database table.
    2) In Universe Designer, I refreshed universe structure and could see the additional column
    3) Created an object 'Acode' that refers to db.new_field
    4) Exported universe
    Maybe worth mentioning that I can see this object and use it in reports fine in Infoview.
    Now, I need to create a new object that will be one of 2 strings based on the 3 character code (Acode) i.e. the 'Atype' can be X or Y.
    Here's my code and it just will not parse:
    CASE
    WHEN @Select(AFolder\Acode) = 'CEL'
    THEN 'X'
    ELSE u2018Yu2019
    END
    Error I get is:
    Parse failed:Eception:DBD ODBC SQL Server driverStatement could not be prepared.State 42000
    I'd appreciate any help, believe me I have searched the forums!
    Thanks, Eddie

    Look at following SAP NOtes.
    1373739
    1184304
    Regards,
    Bashir Awan

  • Object creation of string

    Hello
    Please tell me what is the difference between these two object creation of string.
    String str = new String("Hello");.
    String str="Hello";
    Thanks.

    RGEO wrote:
    hello,
    Is the string pool is part of a heap? Huh? I suppose yes, you could regard the String pool as part of the heap... but (I guess) that interned String objects would be placed directly into the permanent generation, which is not garbage collected... and therefore I don't really think of the permanent generation as part of the heap (except when tuning heap allocations)... but I think I'm talking over your noob head here, yes... and so to the noob-stuff.
    If you get bored you might like to scan (for now) http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html#generations ... and come back to it in a couple of years time (when every second word isn't new and baffling to you;-)
    jvm what will do when he encounter the following code,
    String s1 = new String ("hello");The VM will:
    1. Create a new String object, and then
    2. copy the characters 'h','e','l','l','o' from the interned String "hello" to the new String,
    3. and then assign a reference to the new String to variable s1.
    Note that the result is subtley different from String s1 = "hello", which just does step 3... it assigns a reference to the existing interned String object "hello" to the variable s1... it does not create and "populate" a new String object.
    Try this just for fun... what is the output of the following program? Why?
    package forums;
    public class StringEquals
      public static void main(String[] args) {
        try {
          String a = "Hello";
          String b = "Hello";
          System.out.println("a==b is "+(a==b));
          String c = new String("Hello");
          System.out.println("a==c is "+(a==c));
        } catch (Exception e) {
          e.printStackTrace();
    }Now, what's the correct way to evaluate equality of String objects in Java?
    HTH. Cheers. Keith.

  • To add new object link in DMS

    Hi Sir/Madam,
    Currently we are implementing DMS(Document Management System) and
    our main requirement is to add document to the delivery and billing
    document.In t-code dc10 in "define object link" lips and vbrp object is
    not present in the default list so how we can add these new object in
    order to attach new document to delivery as well as billing document.
    Is it possible to attach document at header level because we have to
    attach lorry number at delivery header which will be common for all the
    items.
    The function module object_check_lips already exist in se37 but we
    have to create new function module for object vbrp.How to create this
    function module? How we have to create screens for these objects? If we
    have to create it by copying some function module like
    object_check_equithan what will be the funtion group.
    IN delivery document (vl03n) in menu bar in "extras" document
    option is not there than how we will see the attached document, do we
    have to create this option with help of abaper or this option will
    automatically reflect after all the cofiguration?
    Thanks and Regards
    Abhilash Nayak

    Hi Abhilash,
    You need to gofor z-development for this. The Abap'r will add the new required object in object link field. Also the DMS screen will appear in the required t-code.
    Meantime you need to add this object in SPRO , "maintain key fields".
    I hope this will resolve the query.
    Regards,
    Ravindra

  • Need the code to make these to new objects in BW world, please help...

    I have two fields that I get from the source (to DSO):
    CREATE_DATE (YYYYMMDD)
    REPORT_MONTH (YYYYMM)
    First I want to make a infoobjects (called CREATE_MONTH) that takes the YYYYMM from the CREATE_DATE.
    The I also want to make an indicator (called MONTH_IND) that have a test on infoobjects called CREATE_MONTH and REPORT_MONTH.
    The logic should be something like this:
    If CREATE_MONTH is 3 month earlier than REPORT_MONTH the indicator should say ‘over 2 month
    If CREATE_MONTH is 4 month earlier than REPORT_MONTH the indicator should say ‘over 3 month
    Etc….
    Conclution:
    Need two new objects:
    1. CREATE_MONTH
    2. MONTH_IND
    Can someone give me some help on how to do this Please?

    Hi Elaine!
    First of all I´d like to thank your answer.
    I know what you mean; I had a gif animated file in my web site and I converted it in a swf file, that is the reason why I couldn´t do the correct to make the link. I thought that I could make the link with a simple code but thanks to this foro, now I know that it is a bit more complicated.
    Anyway, I think that it is better if I read the tutorial to know how this work.
    Thank you again and have a nice day!
    afp5trip

  • Design and registration of new objects

    We have the following three objects:
    - Order, which contains:
    -- OrderStatus
    -- Vector: OrderStatusHistoryItem
    Whenever order.setStatus(newStatus) is called we would like to create a new OrderStatusHistoryItem and add that to the vector of history inside the Order.
    Our first guess was to put this in the setStatus method of the Order object, so that noone would bypass the adding to history. But... When creating the OrderStatusHistoryItem inside the Order we of course get an error from TopLink, saying that the object was not registered in the UOW.
    Is there some way that we can tell TopLink that this relationship should be registered automatically on commit? If not, what would be the best way to design this? Of course we do not want to expose our domain layer to the internals of TopLink. Would a factory be the best way to handle registration upon creation?
    Thanks,
    Anders,

    Anders,
    New objects created and attached to working copies will be discovered during commit cycle and added to the persistent model including the appropriate INSERT. The only issue you will have is that you must make sure that setStatus(newStatus) is ONLY called on working copies read from or registered with a UnitOfWork. If this is true you should be able to create the new OrderStatusHistoryItem within the setStatus method and add it to the collection without registering it in the UnitOfWork.
    Doug

  • While Loop - Object Creation

    Hello,
    I have a question on object creation and while loops. Have a look at the following code snippet:
    while(true)
           Object obj = new Object();
           // Pass off obj to a new thread
           Thread job = new Thread(new ObjectHandler(obj));
           job.start();
    }My question is, do I have to wait until the newly created Thread is finished with the Object obj before I can create a new Object called obj in the while loop?
    Also does anyone have any documentation on this sort of thing?
    Thanks,
    Tony.

    Jaxie wrote:
    I'm still not sure you get what I'm on about, you might want to read up on java methods and pass by value.I think we know how it works. Most of us have been programming in Java for serveral years.
    >
    When you pass an object to a method in java you pass it a copy of a reference to that object. Leading on from that, before an object is eligible for garbage collection in java, all references to that object must be dropped.
    So with all that in place, my question was, is the creation of an object in a while loop dependent on previous objects of the same name? Objects don't have names. Have we mentioned that before?
    You have a reference, larry that is referencing an unnamed object. You can also create other references that reference the same object. The thread will have one reference. You can then make larry reference another object. That will not change anything in the thread. It will still reference the old object, and that object will not be claimed by the gc until that thread stops referencing it.
    So the second time we go through the loop below, do we have to wait until larry has been garbage collected, before a new larry can be created?Read the articles/tutorials and what I have written above. What do you think?
    Do also note that the GC isn't executed synchronously.

Maybe you are looking for

  • Why can't I delete this video file from my trash can?

    I have a video file that I will not disappear from my trash can when I click the "empty track" button. I managed to move the folder containing the video file from documents to the trash after a lot of effort, but it kept telling me that I didn't have

  • Trying to export/share in a format readable by Powerpoint2010 when insert video

    Using Premier 11 Elements...... I'm trying to export/ share videos to my computer, then trying to insert them into a Powerpoint slide. It works fine if I use a raw WMV format straight from the camera, but they need editting. I'm doing the editing enh

  • KM and CM

    Hi ,    are knowledge management and content management same or different . and Is KM and collabaration part of NW 2004s are do we deply them seperately. thanks

  • UCM 11g with IBR 10g

    Anyone try to connect UCM 11g to IBR 10g? I've tried it but unfortunately got the following error "No server defined for FUILD_CURRENT_JOB_STATUS. Exception type is 'java.lang.Throwable'.

  • PS CC does not display images

    I use (hope to) PS CC in combo with LR and Windows 8. When I select right click in LR and edit in PS CC, PS loads but does not display the image. If I look in PS under recently opened files, the file imported from LR shows. If I initiate the opening