To static or not to static

Hello, i have a little discussion with a colleage of mine about the use of statics.
say we have a class (sqlManager) which is used to do all the sql work including the db connection.
would it be wise to make this class static. in my opinion no. perhaps make it a singleton, but not static.
My colleage thinks otherwise, make it static i do not need an object of it. it makes it easier to code and smaller.. perhaps this is true, i personally find it ugly. any suggestions.
Maqish

I think if in the constructor method there are
important things to be executed, then the singleton
pattern will be better. Otherwise, the static
solution is better.There's always a static initializer (static { .. }) for static classes that have the same basic role for static content as constructors do for instance content. Not playing favorites, just pointing it out for any future readers.
If you are sure that the class has features that make
this class immutable, that is, probably it never
will be necessary to inherit the class because of its
characteristics, then you may declare its methods as
final and static.Inheritability is definitely a major factor.
This doubt is only about the architecture of the
application, that is, about its features, that must
be analized to decide what kind of class has to be
developed.As mentioned, I think a good general rule is that if you need singleton behavior, use a singleton. If you just need some utility methods, use static methods.

Similar Messages

  • Assigning Static IP (not local static, internet) to server

    I use linksys router in my office. WRT54GS V4
    I have T1 line and my ISP provides 5 Static IP address.
    DHCP option is turned on in my router. My server is connected to the router.
    If I configure my server with static IP that my ISP provided, my server will not connect to internet.
    It seems to me that only way to assign static IP to my server is to get a switch/hub
    and connect server and my router to this switch/hub.
    Or turn off DHCP option and configure networksetting for each PC n my office. For this case,
    I have to assign some with local IP and some with static IP. Can it work?
    If you have any suggestion, let me know. 
    Thanks.
    Solved!
    Go to Solution.

    The WRT54GS is a consumer router. It does not support multiple public IP addresses.
    The only way it will work is the way you already found: connect a switch to the internet line and then connect the server and the internet port of the WRT to the switch. Of course, you should make sure to configure the firewall on the server very well as it is fully exposed to the internet.
    Otherwise you have to get a business router which supports multiple public IP addresses, e.g. the Cisco Small Business series or better.

  • Work area or table not referenced statically in the program

    Hi Friends,
    When i make extended syntax check for my program, i am getting error as this work area or table not referenced statically in the program .
    How can i overcome that .
    Please give solution nfor this .
    Thanx.
    Title was edited by:
            Alvaro Tejada Galindo

    While Rich has already provided you the right solution, I think you are concerned about this error only because of your "Project Standards" - which says no EPC errors.
    So delete the work area or field from your data definitions if you think that it is not being used.
    If you think it being used dynamically put a comment of " #EC NEEDED next to it. The error will now be hidden.
    Regards,
    Srihari

  • Is a DB cloass acees should be public static or not.

    Hiiiiiiiii,
    I have a java class which query database or insert or update database.Class have separate method for each functionality and during this design I have something to know. IS the method will be public static or not. If I made the methods public static and after that want to make it a t*hread safe with synchronized* then there will be c*lass level lock,*so it will prevent to access other method. But in opinion of my senior it must be public static.
    Please providing me a solution with proper reason which will give me a ground to get into field.

    ejp wrote:
    Because a class that only has static methods is generally an indication of bad design, especially if it also has static data members. Usually such a class should be converted to the Singleton pattern.Which is bad design, formalized.

  • Static initializer not invoked

    Why is the static initializer of B (in the example below) is not invoked?
    public class A {
         public static void m1() {
              System.out.println("static m1 in A");
    public class B extends A{
         static {
              System.out.println("static init B");
         public static void m2() {
              System.out.println("static m2 in A");
    public class Main {
         public static void main(String[] args) {
              B.m1();
    Surprisingly the console output is just 'static m1 in A'.

    Class B doesn't have a static method named m1(). But its superclass does, so it's that method that is called. (Static methods are not inherited.) To call a method of class A, it's only necessary to load class A.

  • Reflection - how can I find out whether method is static or not.

    Hi all,
    I'm using reflection to get a reference to a method. Is there a way to find out whether this method is static or not ?
    There is no such method "boolean isStatic()" in the Method class.
    Holger

    You're so close. You use the getModifiers method in
    Method which returns an int. Then use the
    java.lang.reflect.Modifier class's static methods. In
    this case you use public static boolean isStatic(int
    mod)
    The int that you pass into the isStatic method is the
    same int that you get out of the getModifiers method.
    Hope it helpsThanks. I didn't read the documentation carefully enough - only looking for the key word "static" in the javadoc of class Method. May the duke be with you !

  • Reason for not allowing static declarations inside an inner class

    Is the reason for not allowing static declarations inside an inner class is due to the fact that it can never be accessed at a class level as the outer class has to create an instance of the inner class and any attributes/methods of the inner class has to be accessed through that.
    Typically, an instance (non-static) variable can never be accessed in a statement or expression inside a static context but the class variable can be accessed inside a non-static context. Given this, shouldnt the static declarations be allowed inside an inner class?
    Correct me if my understanding is wrong.
    Thanks

    I still couldnt get it clearly. Why i cant i have a static value ( variable ) for all the instances of the inner class irrespective of its enclosing instances of it ( i.e outer class instances). Say in this example below,
    class Outer
    static int i = 0;
    public Inner inner = new Inner();
    class Inner // inner class ( non-static nested class )
    int j = 0;
    static final int k = 2; // compile time constants are allowed
    // ininner class
    public void m1()
    j++;
    System.out.println("j is " + j);
    i++
    System.out.println("i is " + i);
    public static void main(String[] arg)
    Outer outer1 = new Outer();
    outer1.inner.m1(); // j will be 1 & i will be 1
    Outer outer2 = new Outer();
    outer2.inner.m1() // j will be 1 again & i will be 2. But I would
    // want j to be 2. Why is this not allowed?
    Looks like something missing..

  • [SOLVED] netcfg static IP not persisting across reboots in VM

    I ran into an issue with netcfg static IP not persisting across reboots in a VM. I figured it out, but it took me awhile as a brand new user, so I thought I'd post it.
    Setup
    Using VMWare Workstation 8.0.3 build-703057 with bridged networking
    Host OS: Linux Mint 14 64-bit
    Guest OS: Arch Linux 2013.03.01 x86_64
    Given a fresh install on the guest, setup netcfg:
    cd /etc/network.d
    cp examples/ethernet-static ./myprofile
    nano myprofile
    # customize this file. I also added NETMASK='255.255.255.0'
    systemctl enable netcfg@myprofile
    systemctl start netcfg@myprofile
    Test the configuration. It should be successful:
    ping google.com
    Problem
    See if the changes survive a reboot.
    reboot
    ping google.com
    I got the error "connect: Network is unreachable".
    Check the logs:
    journalctl
    G
    I found the following netcfg failure..
    [email protected]: main process exited, code=exited, status=1/FAILURE
    ..prior to the following device initialization:
    kernel: e1000 0000:02:00.0 eth0: Intel(R) PRO/1000 Network Connection
    system-udevd[117]: renamed network interface eth0 to emp2s0
    Solution
    It looks like netcfg is being started before the device it depends on has been initialized. Inform systemd of the
    dependency so they start in the proper order:
    # nano /etc/systemd/system/multi-user.target.wants/[email protected]
    # Add the following to [Unit]. Remember to replace enp2s0 with your device name.
    Requires=sys-subsystem-net-devices-enp2s0.device
    After=sys-subsystem-net-devices-enp2s0.device
    Test again:
    reboot
    ping google.com
    This should now be successful.

    fukawi2 wrote:
    $ man netcfg-profiles wrote:
           Miscellaneous options
               IPCFG
                   Array of arguments to pass to ip. The power of this options is
                   that it allows both simple and complicated routing
                   configurations, within the framework of netcfg.
               SKIPNOCARRIER
                   ‘yes’/‘no’. Don’t abort interface setup if no carrier is
                   found.
    Thank you, [Solved].

  • Why interfaces can not declare static methods?

    Why interfaces can not declare static methods?

    Why are you shouting?
    Is your internet broken?
    [http://www.google.co.uk/search?q=interface+static+methods+java] 2,440,000 hits.

  • Static or not

    Hi all,
    Top gun questions, assist us please:
    1) Is there any performance gain between
    a) Declare a static class and access its methods by not creating an object
    b) Declate a class, create an object (instance of the class) type class, and access the class methods via the object
    2)I don't know the benefits of declaring a variable type static
    static int iMyInt = 0; ??
    as opposed to
    int iMyInt = 69;
    Thanks
    Trajano

    Yes, yes, yes. I agree totally with YoGee and tsith: Do NOT use static vs. non-static based on performance considerations. That decision is a design decision, based on whether the variable or method makes more sense to associate with a specific instance of a class or with the class as a whole.
    Examples:
    public static final int FOO_LEVEL = 1;
    public static final int BAR_LEVEL = 2;Since the above are final (never changing) and used as symbolic constants to hide magic numbers, there's no need to create a separate copy for each instance of the object.
    private static int numberInPool;You may use the above when you create a number of instances of a class to be shared in a pool. There may be some static methods that manage the pool and that keep track of how many instances exist. Again, since the quantity is the same across the class, and doesn't represent the state of a specific object, you make it static.
    private String thisPersonsName;Might be used to assign a name to each instance of a Person object--it makes more sense to apply to each individual Person than to the class as a whole.
    Likewise with methods. Those that operate on a specific instance of the class and use or set its state would not be static. Those that operate independently of any particular instance--perhaps creating an instance in a factory method, or managing the pool in the above example--would be static.

  • Dynamic call of a static method of an static attribute

    Hi all,
    is it possible to call dynamically a static method of a static attribute of a class.
    The statement without dynamic call would look like this:
    cl_test_class=>static_attribute=>static_method( ).
    I would like to do it like this:
    ('CL_TEST_CLASS')=>static_attribute=>static_method( ).
    Netiher the one nor the other way works for me - I'm getting the error "The notation used is reserved for business object classes".
    Regards, Stefan

    I guess, it is not possible to call method using the short form (parameters in brackets) is not possible in Dynamic Access. You may need to get the attribute first and then call the method.
    CLASS lcl_main DEFINITION.
      PUBLIC SECTION.
        CLASS-DATA: o_same TYPE REF TO lcl_main.
        METHODS: run.
    ENDCLASS.                    "lcl_main DEFINITION
    CLASS lcl_main IMPLEMENTATION.
      METHOD run.
        WRITE: 'success'.
      ENDMETHOD.                    "run
    ENDCLASS.                    "lcl_main IMPLEMENTATION
    START-OF-SELECTION.
      DATA: lo_same TYPE REF TO lcl_main.
      CREATE OBJECT lcl_main=>o_same.
    *  lcl_main=>o_same=>run( ).
      TRY.
          FIELD-SYMBOLS: <fs> TYPE REF TO lcl_main.
          ASSIGN ('LCL_MAIN')=>('O_SAME') TO <fs>.
          CALL METHOD <fs>->('RUN').
        CATCH cx_root.
      ENDTRY.
    Regards,
    Naimesh Patel

  • Non Static Variable addressed to Static Variable

    Hi,
    I am new to java, I am getting (Non Static Variable sb,serverAddress addressed to Static Variable)
    Here is the code. Thanks for reading, any help or explanation would be appreciated-
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package webcheck;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.ProtocolException;
    import java.net.URL;
    * @author
    public class checkhttp {
          private URL serverAddress = null;
          private StringBuilder sb = null;
          public checkhttp(java.net.URL serverAddress,java.lang.StringBuilder StringBuilder)
              this.serverAddress=serverAddress;
              this.sb=sb;
      public static void main(String[] args) {
          HttpURLConnection connection = null;
          OutputStreamWriter wr = null;
          BufferedReader rd  = null;
          String line = null;
          int x;
          //checkhttp check= new checkhttp();
          try {
              serverAddress = new URL("http://www.yahoo.com");
              //set up out communications stuff
              connection = null;
              //Set up the initial connection
              connection = (HttpURLConnection)serverAddress.openConnection();
              connection.setRequestMethod("GET");
              connection.setDoOutput(true);
              connection.setReadTimeout(10000);
              connection.connect();
              //get the output stream writer and write the output to the server
              //wr = new OutputStreamWriter(connection.getOutputStream());
              //wr.write("");
              //wr.flush();
              //read the result from the server
              rd  = new BufferedReader(new InputStreamReader(connection.getInputStream()));
              sb = new StringBuilder();
              while ((line = rd.readLine()) != null)
                  sb.append(line + '\n');
              System.out.println(sb.toString());
              System.out.println("Server is up");
          } catch (MalformedURLException e) {
              e.printStackTrace();
          } catch (ProtocolException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          finally
              //close the connection, set all objects to null
              connection.disconnect();
              //rd = null;
              //sb = null;
              //wr = null;
              connection = null;
    }

    Someone please correct me if I'm wrong, but since main is static, any fields it access must also be static.
    The static keyword declares that something is accessable no matter the class state, thus you can call main() and run your program without having something make an instance of the object that your progam defines. For example:
    class Foo {
          static public String strText = "Hello World";
    //Later in some method, this is valid.
    String MyString = Foo.strText;
    //However, if strText was not static you need to
    Foo fooExample = new Foo();
    String myString = fooExample.strText;Static should not override private, so static private fields/members are not accessable. To be accessable you still need to be public.
    Edited by: porpoisepower on Jan 21, 2010 2:18 PM

  • How to reference a static variable before the static initializer runs

    I'm anything but new to Java. Nevertheless, one discovers something new ever' once n a while. (At least I think so; correct me if I'm wrong in this.)
    I've long thought it impossible to reference a static variable on a class without the class' static initializer running first. But I seem to have discovered a way:
    public class Foo  {
      public static final SumClass fooVar;  // by default initialized to null
      static  {
         fooVar = new SumClass();
    public class Bar  {
      public static final SumClass barVar;
      static  {
         barVar = Foo.fooVar;  // <<<--- set to null !
    }Warning: Speculation ahead.
    Normally the initial reference to Foo would cause Foo's class object to instantiate, initializing Foo's static variables, then running static{}. But apparently a static initializer cannot be triggered from within another static initializer. Can anyone confirm?
    How to fix/avoid: Obviously, one could avoid use of the static initializer. The illustration doesn't call for it.
    public class Foo  {
      public static final SumClass fooVar = new SumClass();  // either this ..
    public class Bar  {
      public static final SumClass barVar = Foo.fooVar;  // .. or this would prevent the problem
    }But there are times when you need to use it.
    So what's an elegant way to avoid the problem?

    DMF. wrote:
    jschell wrote:
    But there are times when you need to use it. I seriously doubt that.
    I would suppose that if one did "need" to use it it would only be once in ones entire professional career.Try an initializer that requires several statements. Josh Bloch illustrates one in an early chapter of Effective Java, IIRC.
    Another classic usage is for Singletons. You can make one look like a Monostate and avoid the annoying instance() invocation. Sure, it's not the only way, but it's a good one.
    What? You only encounter those once in a career? We must have very different careers. ;)
    So what's an elegant way to avoid the problem? Redesign. Not because it is elegant but rather to correct the error in the design.<pff> You have no idea what my design looks like; I just drew you a couple of stick figures.If it's dependent on such things as when a static initializer runs, it's poor. That's avoidable. Mentioning a case where such a dependency is used, that's irrelevant. It can be avoided. I know this is the point where you come up with a series of unfortunate coincidences that somehow dictate that you must use such a thing, but the very fact that you're pondering the problem with the design is a design problem. By definition.
    Besides, since what I was supposing to be a problem wasn't a problem, your "solution" isn't a solution. Is it?Well, you did ask the exact question "So what's an elegant way to avoid the problem?". If you didn't want it answered, you should have said so. I'm wondering if there could be any answer to that question that wouldn't cause you to respond in such a snippy manner. Your design is supposedly problematic, as evidenced by your question. I fail to see why the answer "re-design" is unacceptable. Maybe "change the way the Java runtime initializes classes" would have been better?
    This thread is bizarre. Why ask a question to which the only sane answer, you have already ruled out?

  • Calling non-static command from within static method

    Hello,
    I have a static method that reads bytes from serial port, and I want to set a jTextField from within this method. but I get error that says it is not possible to call non static method from a static one. How can it be solved?

    ashkan.ekhtiari wrote:
    No, MTTjTextField is the name of jTextFiled class instance.You haven't declared any such variable in the class you posted, not to mention that such a variable name violates standard code conventions.
    This is and instance of that object actually. You haven't declared any such variable in the class you posted.
    the problem is something else. No, it isn't, based on the information you have provided. If you want accurate guidance, don't post misleading information about your problem.
    It can not be set from within static method.A question commonly asked on Java forums concerns an error message similar to the following:
    non-static variable cannot be referenced from a static context
    In Java, static means "something pertaining to an object class". Often, the term class is substituted for static, as in "class method" or "class variable." Non-static, on the other hand, means "something pertaining to an actual instance of an object. Similarly, the term instance is often substituted for non-static, as in "instance method" or "instance variable."
    The error comes about because static members (methods, variables, classes, etc.) don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance -- an individual object. There's no way in a static context to know which instance's variable to use or method to call. Indeed, there may not be any instances at all! Thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).
    Once you understand this concept, you can fix your own problem.
    ~

  • Static variable and non-static

    I have a quick question. The following syntax compiles.
    private String t = key;
    private static String key = "key";
    But this doesn't compile.
    private String t = key;
    private String key = "key";
    Can anybody explain how it is treated in java compiler?
    Thanks.

    jverd wrote:
    doremifasollatido wrote:
    I understand that completely. I didn't say that the OP's version with static didn't work. I was just giving an alternative to show that you don't need static, if you change the order that the instance variables are declared.My problem with the underlined is that, while technically true, I can see where a newbie would take it as "oh, so that's how I can get rid of static," and focus only on how to satisfy the compiler, rather than on learning a) when it's appropriate to make something static or not from a design perspective, and b) what the implications of that decision are, for both static and non.
    I have just a wee bit of a prejudice against the "what do I type to make the error messages go away" approach. :-)That sounds good to me. We're currently trying to fix an issue caused by the fact that one class has most of its variables as static, when they should really be instance variables. There should only be one active instance of this class at a time, but the values of the static variables stick around when you call "new ThisClass()". So, old data interferes with new data, and various errors happen. The class has many static methods to access the static variables, but it should have been more of a Singleton--an actual object with non-static variables. The active instance of the Singleton would need to be replaced at logout/login (as opposed to shutdown completely and restart the JVM), but then at least when the new instance were created, then all of the variables would be initialized to empty--the old instance would disappear. The solution at the moment (solution by others--I don't agree) is to clear each static Vector and then set the reference to null (setting to null would be enough to drop the old data, but certain people don't get that...). This is fragile because many variables were missed in this "cleanup" process, and it will be easy to forget to "cleanup" new variables in the future. This class has been misdesigned for years (much longer than I've been here). The calls to static methods permeate the application, so it isn't easy to fix it quickly. There are several of these misdesigned classes in our application--a mix of static and non-static, when nothing or almost nothing should be static.

Maybe you are looking for

  • Windows 8.1 GPO's on Windows Server 2008 R2

    I have a Windows Server 2008 R2 standard as the domain controller. and we have added several windows 8.1 computers to the domain. there are several settings, like lock screen image, that we want to set for all the windows 8.1 computers, but that sett

  • Avoid Payment Block R in Vendor Invoices

    Hello, Our user is not able to clear certain documents through F110 since these documents are blocked with payment block R. When we checked these documents, there was no difference between the MIGO and MIRO amounts or quantities. Neither there is a p

  • Case sensitive

    hi, can anybody tell me how to set case sensivity off and on in oracle session . basically requirement is this. a column in a table column ' name' contains char data 'UDAY' if i query by typing following command it should give me the results select n

  • I currently own Elements 10 for PC and want to upgrade to Elements 12 for MAC.  Is there a MAC version?

    I currently own Elements 10 for PC and want to upgrade to Elements 12 for MAC.  Is there a MAC version?

  • Anything similar to paint?

    Is there anything on the Macbook or anything I can download (for free preferably) that is similar to Windows' Paint? Or maybe even Photoshop? Iphoto just doesn't the options available for good editing. thanks a bunch