Why not use the static methods - example

Hello world

I would like to continue the below thread about "why not use static methods.
Why not use the static methods
with the concrete example.

In my small application, I need to be able to send keystrokes. (java.awt.Robot class is used for this)
I created the following class for these "operations" with static methods:
public class KeyboardInput {

     private static Robot r;
     static {
          try {
               r = new Robot();
          } catch (AWTException e) {
               throw new RuntimeException(e + "Robot couldn't be initialized.");
          }
     }
     
     public static void wait(int millis){
          r.delay(millis);
     }
     
     public static void copy() {
          r.keyPress(KeyEvent.VK_CONTROL);
          r.keyPress(KeyEvent.VK_C);
          r.keyRelease(KeyEvent.VK_C);
          r.keyRelease(KeyEvent.VK_CONTROL);
     }

     public static void altTab() {
          r.keyPress(KeyEvent.VK_ALT);
          r.keyPress(KeyEvent.VK_TAB);
          r.keyRelease(KeyEvent.VK_TAB);
          r.keyRelease(KeyEvent.VK_ALT);
     }

               // more methods like  paste(), tab(), shiftTab(), rightArrow()
}
You think it's a good solution? How could it be improved? I saw something Singleton vs somewhere of static methods. Wouldn't be better to use Singleton?

Thanks for your comments in advance.
lemonboston

maheshguruswamy wrote:

lemonboston wrote:

maheshguruswamy wrote:
I think a singleton might be a better approach for you. Just kill the public constructor, and provide a getInstance method to provide late initialization.

Maheshguruswamy thanks for the tips on the steps create a singleton of this class.
Perhaps you could say also why do you say that it would be preferable to use singleton? What is behind it? Thank you!

In short, it seems to me that a single instance of your class will be able to coordinate actions across your entire application. If a singleton should be sufficient.

But who doesn't answer why he expected prefer a singleton instead of a bunch of static methods. Functionally, the two are almost identical. In both cases, there is that a single 'thing' to call methods - either a single instance of the class or the class itself.

To answer the question, the main reason to use a Singleton on a class of static methods is the same reason readers much of not static vs static decisions: polymorphism.

If you use a Singleton (and and interface), you can do something like this:

KeyboardInput kbi = get_some_instance_of_some_class_that_implements_KeyboardInput_somehow_maybe_from_a_factory();

And then everything calling public methods of KBI has to know that there an implementor of this interface, without worrying about what concrete class is, and you can replace some implementation is appropriate in a given context. If you do not need to do, then the approach of the static method is probably enough.

There are other reasons that may suggest a Singleton - serialization, persistence, use as a JavaBean pop to mind - but they are less frequent and less convincing in my experience.

And finally, if this thing keeps updated a State between method calls, even if you can manage it with static member variables, it is more in line with the OO paradigm to make them non-static fields of an instance of this class.

Tags: Java

Similar Questions

  • Why not use the static methods

    Hello world

    I was informed in a previous thread to avoid using static methods it was possible.
    Why is it, could someone please tell me a little more about this? Are there best practices, concepts on this?

    Thanks in advance,
    lemonboston

    Hi Lemonbottom,

    The rule I used generally goes like this:

    If the method does something that I can use without the object containing it instantiate, then it can be made public static.

    In the previous examples, I had various foods. Apple might have a method called "getCaloricContent" that returns the number of calories in an Apple. I don't need an actual Apple to get this information, so I do static. However, if I want to Breathe() an Apple, then I need to build an Apple to do this, so static would not be appropriate.

    It is a loose guidance to help you get started. Try to avoid as much as possible of static methods. They add an extra dimension (often unwanted) to unit tests. It's not so say it is not a proper use of static methods.

    Once you've got your head around this concept, consider the model Singleton, who, in most cases, eliminates the need for static methods of learning.

    Kind regards
    Robb Salzmann

  • XMLFile parameter is not supported by Oracle APEX, please use the setXMLFile() method

    "XMLFile parameter is not supported by Oracle APEX, please use the setXMLFile() method.

    I created a test web app in apex.oracle.com to try a few things. I created a Flash 2D pie chart in a Web page, and it seems to make very well. But before rendering, I get the error message above, on the region of graph for 1-2 seconds.

    Can anynone tell me what means the error message above and why I'm getting this. I do not use a custom XML part. Has not changed the default settings of the chart area.

    I could see above the error appearing clearly since the apex.oralce.com is so slow... and graphics region takes awhile to load. Otherwise I could not have noticed. It happens in the IE8 and Google chrome.

    Oralce Apex 4.2.5.00.006 (https://apex.oracle.com)

    Google Chrome 34.0.01847.116

    Internet Explorer 8.0.6001.19518

    Can anyone help please. I'll try to become a test application setup dispalying this awhile earlier error message.

    I used HTML5 graphics in apex 4.2.0.00.27 in my office in my real application workspace. Most of my users still use IE8. HTML5 graphics all appeared well in their IE8 browser. One fine day, some parameters must be changed by my network administrator or soemthing else could have happened. I have no idea. My webapplication HTML5 graphics disappear IE8 users. IE9 users had no problem. I contacted our IT support staff of any changes to security settings that day, or earlier. Absolutely no help from my frustration. I have to change maps of my application (only about 6 of them) to the Flash graphics to overcome this obstacle. This is the story behind why I use Flash cards. If anyone has experienced a similar problem in IE8 HTML5 graphics please shed any light for me... This problem may be nothing to do with the "XMLFile parameter error message', but I'm not sure.

    You strike again BUG introduced with Oracle Application Express 4.2.5

    http://www.Oracle.com/technetwork/developer-tools/Apex/application-express/Apex-425-known-issues-2186292.html

    18601802 - ANYCHART XMLFILE WARNING DISPLAYED BEFORE FLASH GRAPHICS RENDERING when Flash graphics that take a long time to make, the user can see the following warning message appears briefly "XMLFile parameter only is not supported by Oracle APEX, please use setXMLFile() method.» The table will be always delivered. Solution: Please advise end-users to ignore the message.

  • Hi all OneHow can you buy an IBook UK not available in Indian store a store; When you change the status of your country, your billing information and credit cards won't work; is there a solution for this using the same method of billing.

    Hello world

    How can buy you an IBook of UK not available in Indian store a store; When you change the status of your country, your billing information and credit cards won't work; is there a solution for this using the same method of billing

    There is no solution, if it is not available in your area, you can't buy it.

  • Why the first Firefox page tell me that I do not use the latest version when the "about" in the menu help says I?

    I updated Firefox 2 days after seeing the message that I was not using the latest version. Download and install led and everything seems to work normally except that I still have a message on my Firefox home page telling me that I'm not using the latest version. If, on the other hand, I navigate to 'Firefox' - 'help' - "On Firefox" I tells me that I'm running Firefox 8.0.1 and "Firefox is updated.

    You can see this message under the Google search box on www.google.com/firefox which is the old default Firefox homepage. It seems that this page is no longer maintained. You seem to have Firefox installed with the latest version 8.0.1.

    If you want to than the Google search page as homepage, change your homepage to Subject: House (a new update version is now integrated into Firefox).

    Also see-> https://support.mozilla.com/en-US/kb/Finding+your+Firefox+version

    You can also see your version on the help > troubleshooting information display

    If this answer solved your problem, please click 'Solved It' next to this response when connected to the forum.

    Not related to your question, but...

    You may need to update some plug-ins. Check your plug-ins and update if necessary:

    * Adobe PDF plugin for Firefox and Netscape: Installation/update Adobe Reader in Firefox

  • Why not in the list of countries, the Azerbaijan and the Georgia? I am a citizen of Georgia, but currently working and living in Azerbaijan. The absence of these countries created barriers to e-payment. As I said I have currently in the territory of the A

    Why not in the list of countries, the Azerbaijan and the Georgia? I am a citizen of Georgia, but currently working and living in Azerbaijan. The absence of these countries created barriers to e-payment. As I said, I currently have in the territory of the Azerbaijan can't use Visa and Master Card and also problem with cards issued in Azerbaijan! What is the reason, can you explain?

    Hello

    It is a community of support based on the user, though I'm afraid that nobody here can speak you either the reasons for decisions from Apple or whatever plans unannounced Apple (for example, if and when pay Apple will launch in a given country).

    If you are wanting to see pay Apple throw in Azerbaijan and Georgia, you can let Apple know here:

    https://www.Apple.com/feedback/Apple-pay.html

  • To access the properties of an Error Message When you use the DisplayRunTimeErrorDialogEx method

    I have a reminder that displays the standard runtime error dialog box using the method Engine.DisplayRunTimeErrorDialogEx of custom error. http://zone.ni.com/reference/en-XX/help/370052H-01/tsapiref/reftopics/engine_displayruntimeerrordial....  The parameters of this do not allow me to specify information about the error message available (via the properties of the stage of the appeal of error).  However, when built-in bed in treated TestStand display dialog runtime error through its methods of error handling he managed to fill in the details about the error.

    Anyone know how I can fill in the details and the error code from the dialog box fields when you use the DisplayRunTimeErrorDialogEx method to call it? See attached screenshot by one example of what I get when I use this method.

    Kind regards

    David

    Doug is correct; each sequence in the call stack has its own sequence context, so if you just "ThisContext" for the sequence context parameter, you provide the framework for the error callback, which has no error.  To access the context of the sequence that wrong, you use the caller property to get to the next level in the call stack, for example:

    RunState.Engine.DisplayRunTimeErrorDialogEx ("error Dialog", ThisContext.Caller, 0, False, False, False, False)

    I hope this clarifies!

  • Legend of Java in OSB not showing the available methods

    Hello

    I made a simple jar which contains a class with a static method that connects to our active directory. I use the spring to connect to the ad. The jar is built using maven. When I build the jar, I copied into a directory of Jar in my project of OSB. I created an action JavaCallout in which I can choose the pot, but it does not recognize my static method... There is no methods I choose!

    Can someone maybe tell me what's not here?

    I have compiled the jar using jdk1.5. IM using 11G ps2. The method takes a string as input and returns a list.

    Thanks in advance!

    try to use the Web Console of OSB directly, it is VERY stable and well tested. Here, you have option explicit to create a resource JAR - you can't fail.
    Once do you operate in the Web Console, just the sbconfig.jar to export and import it into Eclipse.

    Honestly when I need to do something that is not the Message flows edition, I much prefer the Web Console, it is very strong (I can't say the same of the eclipse).

  • How to use the find method to search for multiple items in a single paragraph?

    I'm desigining a script to find all instances where ctrl + b and ctrl + i are applied to body text and then replace the format of these characters replaced with chartag italic or bold.  Here's what the script is supposed to do:

    1. put the find method in a while loop that overrides seeks format character.
    2. If a substitution of format character is found, pass the text range returned by the find method and the CharPropsChange flag in the GetTextForRange method.
    3. Use a Boolean comparison between the idata of the text element to the angle of character and character constant weight.
    4. What that is the boolean is set to true, and then use the SetTextProp method to set the properties of the text range for the italic or bold character tag properties.

    This script works on the substitution of format first character found however it ignores other substitutions in the same paragraph. The cause of this is that the while loop updated the line of text control used by the find method for the following paragraph in the stream. I think I need to add an inner loop that runs through all the text in a single paragraph, where teaching iteration the loc text used by the find method is based on the same paragraph, but the offset is changed. I don't know how to do this.

    function removeOverrides (RPSC)

    {

    var vDocStart = pDoc.MainFlowInDoc.FirstTextFrameInFlow.FirstPgf;

    var vBoldFmt = getCharFmt (RPSC, "Bold")

    var vItalicFmt = getCharFmt (RPSC, 'Italic')

    initFA_errno ();

    While (FA_errno is constant .FE_Success)

    {

    var vTextLoc = new TextLoc(vDocStart,0);

    var vFindParams = findOverrideParams (CDRP);

    var vTextRange = pDoc.Find (vTextLoc, vFindParams);

    If (vTextRange.beg.obj.ObjectValid ())

    {

    var vTextItems = pDoc.GetTextForRange (vTextRange, Constants.FTI_CharPropsChange)

    If (vTextItems.length ==! 0)

    {

    If (vTextItems [0] .idata == constant .FTF_WEIGHT)

    {

    pDoc.SetTextProps (vTextRange, vBoldFmt.GetProps ())

    }

    If (vTextItems [0] .idata == constant .FTF_ANGLE)

    {

    pDoc.SetTextProps (vTextRange, vItalicFmt.GetProps ())

    }

    } else (Log (vLogFileName, ' \nERROR: none of the items were found in the table in text format but alternative size were found: ' + pDoc.Name))

    }

    vDocStart = vDocStart.NextPgfInFlow;

    }

    }

    function findOverrideParams (RPSC)

    {

    var vFindParams = AllocatePropVals (1);

    vFindParams [0].propIdent.num = Constants.FS_FindObject;

    vFindParams [0].propVal.valType = Constants.FT_Integer;

    vFindParams [0].propVal.ival = Constants.FV_FindCharacterFormatOverride;

    Return vFindParams;

    }

    Another approach (which is what I usually did) is after the first search to set vTextLoc = vTextRange.end

    Whatever it is, you might consider moving your initialization of vTextLoc and vFindParams outside the while loop. The settings do not change, why redefine them for each search?

  • How to use the find method to search for character format substitutions and FMP?

    I strongly suspect that I should be able to use the find method to search for paragraph substitutions and format as these options are available in the Find dialog box. However, because of the excruciating Extendscript documentation from Adobe, I not was able to find the key pieces of information that I need. I found these constants:

    • Constants.FV_FindPgfFormatOverride
    • Constants.FV_FindCharacterFormatOverride

    But he has literally no information about them. It is not yet a definition, so I'm actually just a guess. However, I think that I need to somehow use these constant within the parameters of the Find method. Any ideas on how to do it?

    You're right, there are still some bugs to work out of the documentation, although it has already improved since I started w / Extendscript last summer.

    Find two constants must be defined as the ival for a PropVal FindObject, for example:

    var myDoc is app. ActiveDoc;

    var docStart = myDoc.MainFlowInDoc.FirstTextFrameInFlow.FirstPgf;

    tloc var = new TextLoc(docStart,0);

    var findParams = AllocatePropVals (1);

    findParams [0].propIdent.num = Constants.FS_FindObject;

    findParams [0].propVal.valType = Constants.FT_Integer;

    findParams [0].propVal.ival = Constants.FV_FindCharacterFormatOverride;

    myDoc.Find (tloc, findParams);

    Depending on what you're trying to accomplish, you can also take a look at the property FormatOverride of the Doc, bmp and item objects.

  • Using the addEventListener method

    I want to put an addEventListener on a group of radio buttons for any button is selected the same function is executed.  However, the function can you use a term like currentTarget to tell which button has been selected?  I know with actionScript, you can use MouseEvent.CLICK in the listener then event.currentTarget service, but this doesn't seem to work.  The listener doesn't like 'click' and everything I try with currentTarget generates a run-time error.  I know that I can use the function onClick for each button, but I was wondering how to use the addEventListener method.  For some reason, I still have a horrible time, understand the documentation from Adobe.  It comes to PS CS3 & CS4 PS.  Thank you!

    Here is an example of adding an event handler for a control that does not already have a built-in Manager:

    createDialog = function ( ) {
       var dlg = new Window( 'dialog', 'Image Mouse Event Example Script' );
       var i = ScriptUI.newImage( new File('/c/k.png'));
       dlg.image = dlg.add ('image' , undefined,  i, {name:'temp'});// also accepts jpg
       dlg.btnPnl = dlg.add( 'panel', undefined );
       dlg.btnPnl.orientation = "row";
       dlg.btnPnl.alignment = "right";
       dlg.btnPnl.preferredSize [ 80, 80 ]
       dlg.btnPnl.okBtn = dlg.btnPnl.add( 'button', undefined, 'Ok', { name:'ok' });
       dlg.btnPnl.cancelBtn = dlg.btnPnl.add( 'button', undefined, 'Cancel', { name:'cancel' });
       return dlg;
    };
    initializeDialog = function( w ) {
       // Set up initial control states
       ScriptUI.events.createEvent('MouseEvent');
       w.image.addEventListener ('mouseover', btnMouseEventHandler, false);
       w.image.addEventListener ('mouseout', btnMouseEventHandler, false);
        with ( w.btnPnl ) {
             // The Ok and Cancel buttons close this dialog
             okBtn.onClick = function ( ) { this.parent.parent.close( 1 ); };
             cancelBtn.onClick = function ( ) { this.parent.parent.close( 2 ); };
          }
     }
    
    runDialog = function( w ) {
       return w.show( );
    };
    var win = createDialog();
    initializeDialog(win);
    runDialog(win)
    
    function btnMouseEventHandler (event) {
         try {
              var m = event.type// 'mouseover or mouseout
              if ( m == 'mouseover' ) win.image.icon = new File('/c/t.png');
              if ( m == 'mouseout' ) win.image.icon = new File('/c/k.png');
         }
         catch (e) {
         }
    }
    
  • Why not use * type of int?

    Why AccessCode, country code and postal code using the type short in the following script? Why not use of type int ?
    Is the following content / * note?
    Thank you
    package com.oracle.coherence.handson;
    import com.tangosol.io.pof.PofReader;
    import com.tangosol.io.pof.PofWriter;
    import com.tangosol.io.pof.PortableObject;
    import com.tangosol.util.HashHelper;
    import java.io.IOException;
    public class Phone implements PortableObject
    {
    private short AccessCode;
    private short CountryCode;
    private short AreaCode;
    private int LocalNumber;
    /**
    * Default constructor (necessary for PortableObject implementation).
    */
    public Phone() {
    }
    public Phone(short AccessCode, short CountryCode, short AreaCode,
    int LocalNumber) {
    super();
    this.AccessCode = AccessCode;
    this.CountryCode = CountryCode;
    this.AreaCode = AreaCode;
    this.LocalNumber = LocalNumber;
    }
    }
    Published by: qkc on August 25, 2009 19:13

    Comments may appear anywhere in the source code where white space is permitted. Java comments can be written in two ways: slash-slash (/ /...) comments and star oblique bar (/ *... * /) comments.
    Javadoc comments are a special case of comments of the oblique-star bar. For example,.
    /**
    Comments that start with a slash-star-star bar are JavaDoc comments.
    * These are used to extract the documentation from the Java source.
    * More on javadoc will be addressed.
    */

  • How to set the position and size of the façade using the FPRunTimePosRunCustom method in a c# application?

    How to set the position and size of the façade using the FPRunTimePosRunCustom method in a c# application?

    I found a solution! -Set the size and position of the façade with the help of the

    File > VI properties > window running Position (in category list) > custom (in position of menu drop-down).

    then just accept the current position and size (leave the boxes checked) or set values you want directly (uncheck the boxes and fill in the numbers), or physically position and size the façade and use, the "set to current location" button and press "set size" current All that is easier for you.

    OK so it does not make use of the method VI Methods (Active X) FPRunTimePosRunCustom ([Position], [Size]) but if labview want to make him difficult to use then other means must be found.

  • is not abstract and does not substitute the abstract method callLogRemoved (net.rim.blackberry.api.phone.phonelogs.CallLog)

    Can someone tell me why im getting the following error

    is not abstract and does not substitute the abstract method callLogRemoved (net.rim.blackberry.api.phone.phonelogs.CallLog)

    callLogRemoved is set, I tried to remove it and it also gives me the same error

    Here is my code

    Thanks in advance for answer

    Net.rim.blackberry.api.phone import. *;
    Net.rim.blackberry.api.phone.phonelogs import. *;
    //*******************************************************************************//
    public class mylistener extends Thread implements {PhoneLogListener}

    {} public void callLogRemoved (int arg0)
    System.out.println("/***/"); "
    System.out.println ("CallLog removed');
    System.out.println("/***/"); "
    }
    {} public void callLogAdded (int arg0)
    System.out.println("/***/"); "
    System.out.println ("CallLog added");
    System.out.println("/***/"); "
    }
    ' public void callLogUpdated (int arg0, int arg1) {}
    System.out.println("/***/"); "
    System.out.println ("CallLog update");
    System.out.println("/***/"); "
    }
    {} public void reset()
    System.out.println("/***/"); "
    System.out.println ("CallLog Reset");
    System.out.println("/***/"); "
    }

    }

    Javadoc documentation:

    public void callLogRemoved (CallLog cl)

    but you have coded:

    public void callLogRemoved (int arg0)

    An int is not a CallLog, so these signatures do not match.

  • How to use the post method?

    Hello

    I need to send an image on the server using the post method.

    I connect using Http, like this:

    HttpConnection _http = (HttpConnection) Connector.open (address);

    can someone provide an example of how can I use a post method to send the data to the server?

    Kind regards

    I solved the problem. Here is my code, which works:

    Bitmap _bitmap = new Bitmap(Display.getWidth(), Display.getHeight());
                Display.screenshot(_bitmap);
    
    JPEGEncodedImage _jpg = JPEGEncodedImage.encode(_bitmap, 20);
    DataBuffer _db = new DataBuffer();
    _db.write(_jpg.getData());
    
    _http = (HttpConnection)                    Connector.open(_url, Connector.READ_WRITE);
    
    _http.setRequestMethod("POST");
    
    _http.openOutputStream().write(_db.toArray());
    _http.getResponseCode();
    

    Kind regards

Maybe you are looking for

  • Is there a way to have a project of Photo Story 3 Auto?

    Just installed Photo Story 3.  He programs quite easily, but I don't see a way to have it auto slideshow.  Anyone know of a way to do it?

  • I have 2 profiles of user configured on my pc and now we can't open

    When I click on the user icon I get a message that says: The user profile Service service has no logon. User profile cannot be loaded.

  • Upgrades for new 7559

    I would add 8 GB of ram and an SSD of m2. I checked some other forums, but the recommended material is sketchy at best, could someone give me some thoughts on the choice of this material, please.

  • Browser on blackberry storm blackBerry Smartphones

    Hello If anyone can help! You can find this easy but I am struggling to select web pages via my browser when I highlight a web address to selct it does nothing and does not load. Any who know hat to do about it?

  • Windows 7 / Windows 8 home group problems

    How to remove a current House Group for computers laptops windows 7 and add these laptops w7 in a new group of windows home 8.  When I try to delete / leave the current w7 home group, I get an error message saying that I can't leave.  I tried to do e