Refactoring difficult code

Hi all
Slightly complicated but ill try and keep it simple � the code:
int[] seq = new int{0,0,0,0};
int limit = 9;
while(!done){
     //Print out array - (uses a for loop)
     seq[0]++;
     if(seq[0] > limit){
          seq[0] = 0;
          seq[1]++;
          if(seq[1] > limit){
               seq[1] = 0;
               seq[2]++;
               if(seq[2] > limit){
                    seq[2] = 0;
                    seq[3]++;
                    if(seq[3] > limit){
                         seq[3] = 0;
                         done = true;
}Basically the code prints every possible combination of numbers from 0,0,0,0 to 9,9,9,9 (8,9,9,9 actually but that�s not relevant: the last iteration never hits the print statements)
In this example the array has only 4 elements � but the actual program has 149 elements. To add one element to the array (5 elements) you simply add another nested if statement, but writing 149 nested ifs would take a very long time. Can anyone suggest a better way using loops � the reason I�m having problems is because the if statements are nested.
Thanks, in advance

Here is a recursive algorithm that can do what you expect. its much cleaner but may not be as efficient as yours. You can extend this as much as you want.
class Test{
    static int limit;
    static int array[];
    static int aLen;
    static void init(int lim,int alen){
        limit =lim;
        array = new int[alen];
        aLen = array.length;
    public static void main(String args[]){
        init(9,4);
        process();
        print();
    static void process(){
        while(overFlowCheck(0)){
            print();
    static boolean overFlowCheck(int index){
        if(index>=aLen){
            System.out.println("Limit Overflow");
            return false;  
        if(array[index]>=limit){
            array[index++]=0;
            return overFlowCheck(index);
        else array[index]++;
        return true;
    static void print(){
        for(int i=(aLen-1);i>=0;i--)System.out.print(array[i]+",");  
        System.out.println();
}

Similar Messages

  • How to refactor ActionScript code into Utility or Helper Classes ?

    Hello
    My application is growing in size. Many of my components are now 1000+ lines of code, most of which is ActionScript functions.
    What is the best way to refactor this into classes? Are there any tutorials explaining something like this?
    I'd like to do something like "myComponent1Util" and "myComponent2Util" respectively, to handle common functions. I notice I have a lot of functions that could be refactored into smaller functional code.
    Anybody have any tips or advice before I journey down that road? It would be appreciated.
    Thanks!

    There is no general rule of thumb. Most probably your classes are overloaded
    with responsibilities. You can try to read Martin Fowler's refactoring as a
    starting point. Examples are in Java and C# but you'll get the big picture.
    C

  • Code refactoring

    Hell code refactoring!
    I inhirite a Java application that was written 15 years ago with millions lines of code
    The code has many problems, including some very basic stuff like comparing object using ==. But somehow, it works and the company keeps using it
    The problem we are facing is the code doesn't support debugging. ALL of the methods have very limited number of variables. The coders writting something like this all over places
    if(getA().getB().getC().getD().getE().getM().equals(getA().getB().getC().getD().getE().getN()){
         getA().getB().getC().getD().getE().getM().setZ(getA().getB().getC().getD().getE().getN().getZ());
    int num = getA().getB().getC().getD().getE().getM().getList().size();
    for(int i = 0; i<num; i++){
        getA().getB().getC().getD().getE().getM().getList().get(i).setSomething();;
    It is unbelievable but it is real. Some of them have more than 10 get() on the same line
    I try to refactor it, adding local variables into the methods, so we can resuse the objects instead of using lines of get()
    It also help debugging the code possible because there are many recursive calls plus the above style make it almost impossible now. Whenever something happens, it took me days to figure out what is wrong
    I am going to break the get() chains but since the code base is huge, I don't know if we have some tools availble.
    If someone has solved similar problem, please give me some advice.
    Thank you very much

    2/ The code has many problems, not a single one. but I feel most important is debuggable.
    Well so far you haven't mentioned a single problem with the code. Further, the code sample you posted is 'debuggable'. But, again, you don't need to 'debug' code that works correctly.
    The below is a real function of the code that I renamed all the terms
    What is it about that code that makes you think it is not 'debuggable'?
    You have to pick your battles. You can't try to rewrite/refactor code just because you don't like the way it was written. That is NOT productive.
    Assuming you even have a need to refactor anything the first step is to identify the CRITICAL code sections/elements/classes/methods. Critical either because they are performance issues or critical because they are what keeps breaking.
    There are almost no comments in the code,
    Then, as I already mentioned, the FIRST step is to analyze the code and DOCUMENT IT. You posted a code snippet and said ABSOLUTELY NOTHING about what that method is supposed to be doing. Why not? Why didn't you post a comment? Have you 'analyzed' that code you posted? If not, why not?
    Your analysis should START with the method signature; the parameters and return type. Have you look at that for the sample you posted? If not, why not?
    Do you see anything unusual about it? I do.
    private Double returnCRValue(TsTRatingOperation aetnRatingOperation, String id) throws Exception {  
    Throws Exception? Almost any coded might throw an exception so why does this method just mention a generic exception instead of a specific one.
    The signature declares that the method returns an instance of Double. Does it actually do that?
    BigDecimal dbvalue = null;
    return dbvalue == null ? null : new Double(dbvalue.doubleValue());  
    Why does the method use BigDecimal in the body but then convert the value to a Double for the return? What if that BigDecimal value can't be converted properly to a Double without losing precision? Why isn't the method returning a BigDecimal? Then the caller can perform any conversions that might be necessary.
    The SECOND place to look for issues is the logic flow of the method. Does every IF statement have an ELSE? If not then why not. A common source of bugs is missing ELSE statements that cause code to fall through and work wrong when the IF condition isn't met. Same with CASE/SWITCH statements; big problem with fall through execution if a BREAK statement is missing when it is needed.
    Do you see any logic issues with that code you posted? I do.
            int nPolModTotal = 0;  
            if (aetnRatingOperation.getTsTRatingPASOperationTerm().get(0).getOperationCRs() != null) {  
                nPolModTotal = aetnRatingOperation.getTsTRatingPASOperationTerm().get(0).getOperationCRs().size();  
            //loop CRs  
            for (int n = 0; n < nPolModTotal; n++) {  
                String sid = aetnRatingOperation.getTsTRatingPASOperationTerm().get(0).getOperationCRs().get(n).getCRTypeReferenceCode().trim();  
                if (sid.equals(id.trim())) {  
                    dbvalue = aetnRatingOperation.getTsTRatingPASOperationTerm().get(0).getOperationCRs().get(n).getModFactorValue();  
    .. even more, possibly disastrous processing follows
    The value of 'nPolModTotal' is set to zero.
    Then there is an IF statement that MIGHT SET it to a real non-zero value.
    But WHAT IF IT DOESN'T? The rest of the code in the method will still execute. That for loop will escape ok because of its initialization statements but the next FOR loop will still execute. Is that the correct behaviour? I have no way of knowing. But it is certainly suspicious code for the second part to execute and compute a return value when the first part failed to execute.
    I would want to know why the code works that way and if it is correct or a bug waiting to happen.
    Loops of all kinds are also problematic: wrong initialization, wrong termination, unnecessary code within the loop instead of before the loop. Do you see any of the problems in the method you posted? I do.
    //loop CRs    
            for (int n = 0; n < nPolModTotal; n++) {  
                String sid = aetnRatingOperation.getTsTRatingPASOperationTerm().get(0).getOperationCRs().get(n).getCRTypeReferenceCode().trim();  
                if (sid.equals(id.trim())) {  
                    dbvalue = aetnRatingOperation.getTsTRatingPASOperationTerm().get(0).getOperationCRs().get(n).getModFactorValue();  
    Why does EVERY iteration potentially set (and overwrite) the value of 'dbvalue'?
    If the code is looking for a single match then it should EXIT the loop when it finds it. Why iterate through hundreds or thousands of entries (depending on the value of 'nPolModTotal') if you found your 'sid' on the very first match?
    What if there are two matches for that IF statement above? The value of 'dbvalue' will be set to the LAST ONE found. Is that the correct behaviour?
    There is nothing inherently wrong with those concatenated 'get' operations.  I'm assuming by your comments that you want to 'refactor' this line of code
    aetnRatingOperation.getTsTRatingPASOperationTerm().get(0).getOperationCRs()
    by creating an instance variable and capturing that value and then using that instance variable in the following loop?
    myOperationsCRs = aetnRatingOperation.getTsTRatingPASOperationTerm().get(0).getOperationCRs() ;
    for (int n = 0; n < nPolModTotal; n++) {    
                String sid = myOperationsCRs.get(n).getCRTypeReferenceCode().trim();
      Why? Why do you think you should 'refactor' that code and use an instance variable for the intermediate result?
    As I said before if I were you I would forget refactoring the code and focus on:
    1. analyzing what it does
    2. adding appropriate comments and annotations (e.g. for the parameters and return type
    3. identifying any logic issues (as I did above)
    4. researching those logic issues with a possible plan to fix them

  • Difficult CAPTCHA codes

    If you forget your password at http://www.linksyssmartwifi.com , it takes you to a password reset page where it generates CAPTCHA codes for you to type in, like this one: What code is that?!Most of these difficult codes not only prevent bots from using it, but also normal human beings. Can anyone guess what the above code is? I see what looks like the 4-letter word in the 2nd word.If you have a more complex code, post it here; maybe someone can figure it out.

    This Captcha code is enough of a reason to never buy Linksys again. I have been buyibng routers and modems for over 3o years now and owned virtually every brand. This Captcha code on the Linksys EA6350 is enough for me to chuck it and buy another brand. I spent 45 minutes trying, my wife spent an hour and our daughter spent 45 minutes. I and my family have  already invested enough time in tryin to decode it to justify buying another. Goodbye Linksys!!!

  • Any way to search for casts in java source code?

    Anyone know of a decent way to search your java source files to find all the casts?
    I ended up doing a simple text search for
         " = ("(quote marks not included) which works for my code because I am strict about writing my casts with spaces like
         String s = (String) iterator.next();Unfortunately, the above search has all kinds of problems with both false positives and negatives. It picks up lots of irrelevant lines like
         int index = (number > 0) ? 0 : 1;as well as misses casts that appear nested inside expressions like
         ((String) iter.next()).charAt(...)I suppose that one could do a regular expression search for any pair of open and close parens which bound non-blank text, but that would pick up even more non-cast expressions in typical java code.
    I think that the only way to properly do this is to have a tool which understands java syntax.
    Anyone know of an IDE which will do this? Does IntelliJ or Netbeans support this kind of search?
    In case you are wondering why I am interested in this, it is because I am refactoring some code to fully use generics, and searching for casts is one source of identifying candidates for genericity.

    cliffblob wrote:
    Better late than never?Yes!
    cliffblob wrote:
    ...The answer I found to ID unnecessary casts was, using Eclipse IDE, In compiler error and warning preferences to warn on unnecessary casts.Thanks for pointing IDEs out. I just opened IntelliJ, and going back to at least version 7.04 (maybe earlier) they have an inspection for "Redundant type cast".
    cliffblob wrote:
    I would still be interested to know if there is a way to identify casts in general in your source, perhaps now four years later there is a way?The only solutions that I can think of are either a complicated regex search, or you must use some tool like an IDE that understand Java syntax and can determine if a cast is happening.

  • How to solve "Error: code segment of method _jspService(...) too large"

    Hi, I am trying to compile a JSPX Page and I keep getting "Error: code segment of method _jspService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) too large", in some Forums say that this Error is due to a Limit in the Size of Code that a Try/Catch Block can contain (64K), They suggest to remove such Blocks but I don't know how to do this in JDeveloper 10.1.3.2.0, some advice or suggestion?
    Thanks in Advance.
    PD: I cannot refactor the Code into different Pages.

    Hi,
    if I remember well then the problem is solved by setting the compiler used to JAVAC. This is a setting in the project properties
    Frank

  • BUG: 10.1.3 EA1 - Refactor errors when handling arrays

    Hi,
    I declare my arrays like this:
    int n[];
    Rather than the way JDeveloper likes it:
    int[] n;
    So when JDeveloper refactors my code I either get too many [] or not enough.
    E.g, JDeveloper makes a method out of some code, or moves definitions up the class hierarchy and it ends up like this:
    int[] n[];
    Its like it knows it's an array so it writes "int[]" then it writes the variable as it originally found it "n[]". I have also seen it drop the [] in a method parameter argument that was an array.
    JDeveloper should preserve my definitions the way they were or at least get them right if it insists on changing it to its own style.
    Regards,
    Simon.

    Thanks for looking into it.
    You have to split the array definition from the method code so that it has to pass the array as a parameter.
    E.g.
    String s;
    Object i[] = new Object[3];
    if(i==null || i.length == 0)
    s = "i is null";
    System.out.println(s + i.toString());
    Leave the definitions behind and just make a method of just the if statement. Mine generated:
    String s;
    Object i[] = new Object[3];
    s = test(i);
    System.out.println(s + i.toString());
    and
    private String test(Object i)
    String s;
    // TODO type initialisation here
    if(i==null || i.length == 0)
    s = "i is null";
    return s;
    Note that 'int i' is wrong and causes the syntax errors.
    If you change the definition to "int[] i;" it works OK.
    It also works if you include the definition (as it was) in the refactor code.
    The indenting of the new method was mucked up too. Not as shown here because this forum strips out all leading blanks. Indenting appears to get mucked up if you have set the tabstop and indent set to 4 in the preferences. A 'reformat' fixes it.
    Cheers,
    Simon.

  • [HTML5/Flash CC] Example code to add/run sound programmatically?

    Anyone have a code snippet to do this? I managed to make a really stupid work-around for the moment. Created a movieclip in it with nothing but the sound, gave it an instance name and now I can do mcBeep.gotoAndPlay('start') to play it, but for obvious reasons, I'd like to be able to do this without having to leave an empty movieclip lying around on stage...
    Thanks in advance!

    JLudwig wrote:
    Any reason why you call getSourceDataLine() twice? ..Oh wait, I know this one (..snaps fingers. yes) it is because I am a mor0n, and forgot the class level (static) attribute declared earlier in the source when I (re)declared the local attribute and called getSourceDatLine (which was redundant, given the next line, which as you point out also called getSourceDataLine).
    There are (at least) two ways to correct this problem.
    1) Remove the class level attribute and the second call.
    2) Remove the local attribute as well as the first call (all on the same code line).
    Method 1 makes more sense, unless you intend to refactor the code to only instantiate a single SDL for however many times the user presses (what was it? Oh yeah..) 'Generate Tone'.
    My 'excuse' for my odd programming is that this was 'hacked down' from a longer program to form an SSCCE. I should have paid more attention to the fine details (and perhaps run a lint checker on it).
    Thanks for pointing that out. I guess from the fact you spotted it, that you have already corrected the problem. That you thought to report it, gives me confidence that you 'will go far (and be well thought of, besides)' in the open source community.
    ..This is quite handy, thank you.You're welcome. Thanks for letting us know about the error (OK - the pointless redundancy). Thanks to your report, other people who see this code later, will not have to wonder what (the heck) I was thinking when I did that.
    Another thing I noted, now I run the source on a 400MHz laptop (it's hard times, here) is that the logic could be improved. At the speeds that my laptop can feed data into the SDL, the sound that comes out the speakers approximates the sound of flatulence (with embedded static, as a free bonus!).
    Edit 1: Changed one descriptive word so that it might get by the net-nanny.
    Edited by: AndrewThompson64 on Mar 27, 2008 11:09 PM

  • Example: Code to generate audio tone

    This code shows how to generate and play a simple sinusoidal audio tone using the javax.sound.sampled API (see the generateTone() method for the details).
    This can be particularly useful for checking a PCs sound system, as well as testing/debugging other sound related applications (such as an audio trace app.).
    The latest version should be available at..
    <http://www.physci.org/test/sound/Tone.java>
    You can launch it directly from..
    <http://www.physci.org/test/oscilloscope/tone.jar>
    Hoping it may be of use.
    package org.physci.sound;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.SourceDataLine;
    import javax.sound.sampled.LineUnavailableException;
    import java.awt.BorderLayout;
    import java.awt.Toolkit;
    import java.awt.Image;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JButton;
    import javax.swing.JSlider;
    import javax.swing.JCheckBox;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.border.TitledBorder;
    import java.net.URL;
    Audio tone generator, using the Java sampled sound API.
    @author andrew Thompson
    @version 2007/12/6
    public class Tone extends JFrame {
      static AudioFormat af;
      static SourceDataLine sdl;
      public Tone() {
        super("Audio Tone");
        // Use current OS look and feel.
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                SwingUtilities.updateComponentTreeUI(this);
            } catch (Exception e) {
                System.err.println("Internal Look And Feel Setting Error.");
                System.err.println(e);
        JPanel pMain=new JPanel(new BorderLayout());
        final JSlider sTone=new JSlider(JSlider.VERTICAL,200,2000,441);
        sTone.setPaintLabels(true);
        sTone.setPaintTicks(true);
        sTone.setMajorTickSpacing(200);
        sTone.setMinorTickSpacing(100);
        sTone.setToolTipText(
          "Tone (in Hertz or cycles per second - middle C is 441 Hz)");
        sTone.setBorder(new TitledBorder("Frequency"));
        pMain.add(sTone,BorderLayout.CENTER);
        final JSlider sDuration=new JSlider(JSlider.VERTICAL,0,2000,1000);
        sDuration.setPaintLabels(true);
        sDuration.setPaintTicks(true);
        sDuration.setMajorTickSpacing(200);
        sDuration.setMinorTickSpacing(100);
        sDuration.setToolTipText("Duration in milliseconds");
        sDuration.setBorder(new TitledBorder("Length"));
        pMain.add(sDuration,BorderLayout.EAST);
        final JSlider sVolume=new JSlider(JSlider.VERTICAL,0,100,20);
        sVolume.setPaintLabels(true);
        sVolume.setPaintTicks(true);
        sVolume.setSnapToTicks(false);
        sVolume.setMajorTickSpacing(20);
        sVolume.setMinorTickSpacing(10);
        sVolume.setToolTipText("Volume 0 - none, 100 - full");
        sVolume.setBorder(new TitledBorder("Volume"));
        pMain.add(sVolume,BorderLayout.WEST);
        final JCheckBox cbHarmonic  = new JCheckBox( "Add Harmonic", true );
        cbHarmonic.setToolTipText("..else pure sine tone");
        JButton bGenerate = new JButton("Generate Tone");
        bGenerate.addActionListener( new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
              try{
                generateTone(sTone.getValue(),
                  sDuration.getValue(),
                  (int)(sVolume.getValue()*1.28),
                  cbHarmonic.isSelected());
              }catch(LineUnavailableException lue){
                System.out.println(lue);
        JPanel pNorth = new JPanel(new BorderLayout());
        pNorth.add(bGenerate,BorderLayout.WEST);
        pNorth.add( cbHarmonic, BorderLayout.EAST );
        pMain.add(pNorth, BorderLayout.NORTH);
        pMain.setBorder( new javax.swing.border.EmptyBorder(5,3,5,3) );
        getContentPane().add(pMain);
        pack();
        setLocation(0,20);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        String address = "/image/tone32x32.png";
        URL url = getClass().getResource(address);
        if (url!=null) {
          Image icon = Toolkit.getDefaultToolkit().getImage(url);
          setIconImage(icon);
      /** Generates a tone.
      @param hz Base frequency (neglecting harmonic) of the tone in cycles per second
      @param msecs The number of milliseconds to play the tone.
      @param volume Volume, form 0 (mute) to 100 (max).
      @param addHarmonic Whether to add an harmonic, one octave up. */
      public static void generateTone(int hz,int msecs, int volume, boolean addHarmonic)
        throws LineUnavailableException {
        float frequency = 44100;
        byte[] buf;
        AudioFormat af;
        if (addHarmonic) {
          buf = new byte[2];
          af = new AudioFormat(frequency,8,2,true,false);
        } else {
          buf = new byte[1];
          af = new AudioFormat(frequency,8,1,true,false);
        SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
        sdl = AudioSystem.getSourceDataLine(af);
        sdl.open(af);
        sdl.start();
        for(int i=0; i<msecs*frequency/1000; i++){
          double angle = i/(frequency/hz)*2.0*Math.PI;
          buf[0]=(byte)(Math.sin(angle)*volume);
          if(addHarmonic) {
            double angle2 = (i)/(frequency/hz)*2.0*Math.PI;
            buf[1]=(byte)(Math.sin(2*angle2)*volume*0.6);
            sdl.write(buf,0,2);
          } else {
            sdl.write(buf,0,1);
        sdl.drain();
        sdl.stop();
        sdl.close();
      public static void main(String[] args){
        Runnable r = new Runnable() {
          public void run() {
            Tone t = new Tone();
            t.setVisible(true);
        SwingUtilities.invokeLater(r);
    }

    JLudwig wrote:
    Any reason why you call getSourceDataLine() twice? ..Oh wait, I know this one (..snaps fingers. yes) it is because I am a mor0n, and forgot the class level (static) attribute declared earlier in the source when I (re)declared the local attribute and called getSourceDatLine (which was redundant, given the next line, which as you point out also called getSourceDataLine).
    There are (at least) two ways to correct this problem.
    1) Remove the class level attribute and the second call.
    2) Remove the local attribute as well as the first call (all on the same code line).
    Method 1 makes more sense, unless you intend to refactor the code to only instantiate a single SDL for however many times the user presses (what was it? Oh yeah..) 'Generate Tone'.
    My 'excuse' for my odd programming is that this was 'hacked down' from a longer program to form an SSCCE. I should have paid more attention to the fine details (and perhaps run a lint checker on it).
    Thanks for pointing that out. I guess from the fact you spotted it, that you have already corrected the problem. That you thought to report it, gives me confidence that you 'will go far (and be well thought of, besides)' in the open source community.
    ..This is quite handy, thank you.You're welcome. Thanks for letting us know about the error (OK - the pointless redundancy). Thanks to your report, other people who see this code later, will not have to wonder what (the heck) I was thinking when I did that.
    Another thing I noted, now I run the source on a 400MHz laptop (it's hard times, here) is that the logic could be improved. At the speeds that my laptop can feed data into the SDL, the sound that comes out the speakers approximates the sound of flatulence (with embedded static, as a free bonus!).
    Edit 1: Changed one descriptive word so that it might get by the net-nanny.
    Edited by: AndrewThompson64 on Mar 27, 2008 11:09 PM

  • Seeking refactoring advice

    I'm trying to refactor the code in my small JSP/servlet-based application, and I'm at a standstill because I can't decide on the best of several approaches to take. I'd like to settle on a definite public API so that any further refactoring can be done as painlessly as possible, but in order to do this, I need to make a decision. Please read further if you would like to help me out, I appreciate it.
    MY SITUATION:
    In my application, I have a class that contains a reference to an ArrayList. Let's call it MyList. MyList is essentially a wrapper around that ArrayList, I thought this would be a good idea since I can always change to another Collection implementation if I find a good reason to (better performance, etc). Currently, MyList also contains a method called toHtml(), which generates an HTML table representing the contents of the ArrayList (actually it contains detailed info on each item in the ArrayList, but that's beside the point).
    MY THOUGHTS:
    At first it seemed like a good idea to have the toHtml() method in MyList, because anywhere I'm using a MyList instance, I can quickly generate an HTML representation of the list. And if I need a differently-formatted HTML representation, I can always create a new method that generates the output differently, using the same information. But then I wondered if I should refactor and create a new class, MyListHtmlDisplay. The purpose of this would be to keep all display logic out of MyList. If I need to generate an HTML representation of a MyList instance, I can just pass a MyList instance to MyListHtmlDisplay and use one of its methods to generate the display.
    The reason I thought this would be a good idea was that it makes MyList a little more versatile, I can use it in a non-HTML version of my application (and it is very likely that I will be writing a Swing client to complement the JSP/servlet application I have already started). Obviously HTML display methods are extra baggage if I'm going to use the MyList class in a non-HTML application.
    MY QUESTION:
    If anyone can suggest which of the following make the most sense from a design standpoint -- I am not very well-schooled in OO design -- that would be great.
    1. Should I create a MyListHtmlDisplay class that uses static methods? I would create a method for each kind of HTML representation of a MyList and pass the MyList as an argument to the static method. This solution does not seem very object-oriented, but sounds like a workable solution.
    2. Should I create a MyListHtmlDisplay class whose constructor accepts a MyList instance as an argument? I would instantiate a MyListHtmlDisplay object in my application and pass in the MyList, then call any methods that I might need which can use the MyList to generate the HTML output.
    3. Or would it be best to just leave things as they are, where MyList contains any methods necessary to display its contents? This keeps things simple, though I may end up with methods that I do not need later on if using MyList elsewhere.
    Please don't limit yourself to one of the above choices if you have a better idea. Thanks in advance for your suggestions.

    MY SITUATION:
    In my application, I have a class that contains a
    reference to an ArrayList. Let's call it
    MyList. MyList is essentially a wrapper around
    that ArrayList, I thought this would be a good idea
    since I can always change to another Collection
    implementation if I find a good reason to (better
    performance, etc). So, why dont you just use the List interface instead of ArrayList? No need to create your own class.
    1. Should I create a MyListHtmlDisplay
    class that uses static methods? No. Create a MyListHtmlDisplay class that takes some formatting parameters in it's constructor and then implement a method called display(List list) or similar that does the actual formatting. This way you can easily create an interface that only contains the display(List list) method and you can have different implementing classes that displays the list in different formats.
    3. Or would it be best to just leave things as
    they are, where MyList contains any methods necessary
    to display its contents? This keeps things simple,
    though I may end up with methods that I do not need
    later on if using MyList elsewhere.There is no general rule where to put methods like this. My approach is to first determine the interface I want to have towards an object. I try to keep this interface as small and clean as possible. I always create an interface, not a base class. I always access objects through this interface, not the implementation.
    When I want to perform a method on an object implementing this interface, I first check if I can perform the operation using only the interface. If this is the case, I usually put the method in a separate class as this enhances the separation of concerns, simplifies the design and reduces dependencies between classes. If it can't be done using only the interface, I add a new method to the interface.
    Hope this helps some!

  • XML String encoding - anyone have the the code?

    I need to encode strings for use in XML (node values) and replace
    items like ampersands, < and > symbols, etc with the proper escaped strings.
    My code will be installed on systems where I CANNOT add additional libraries to whatever they may already have.
    So, I cannot use JAXP, for example.
    Does anyone have the actual Java code for making strings XML compatible ?
    I am particularly concerned that the if the string already contains a valid encoding that it is NOT 're-processed' so that this (excuse the extra -'s):
    'Hello &-amp-;'
    does not become this:
    'Hello &-amp-;-amp-;'
    Thanks.

    It isn't especially difficult code. Here's what you have to do:
    1. Replace & by &amp;
    2. Replace < by &lt;
    3. Replace > by &gt;
    4. Replace " by &quot;
    5. Replace &apos; by &apos;
    Note that it's important that #1 come first, otherwise you will be incorrectly processing things twice. The order of the rest doesn't matter. (Technically you don't have to do all of these things in all situations -- for example attribute values have different escaping rules than text nodes do -- but it isn't wrong to do them all.)
    And note that this is called "escaping", not "encoding".
    I am particularly concerned that the if the string already contains a valid encoding that it is NOT 're-processed'This isn't a valid design criterion. You have to set up your design so that you have unescaped strings and you are creating escaped strings, or vice versa. If you have a string and you don't know if it has already been escaped or not, then that's a design failure.

  • X31 WinXP USB after standby Code 38

    Hallo everyone!
    I have a very annoying problem. My Thinkpad X31 supports internally only 802.11b that is too slow today. So I got Fritz!WLAN USB Stick which can 802.11g.
    The Problem: The stick stops to work after standby. Worse: Not always. Rarely It works after first standby but by second one for sure. In Device Manager under USB controllers I can see that  "USB mass storage device" has a trouble : 
    Windows cannot load the device driver for this hardware because a previous instance of the device driver is still in memory (Code 38)
    I guess there is not a problem with WLAN USB Stick but interplay of Windows driver with hardware.
    Has anyone idea how i get clue with this problem?
    Thanx in advance
    P.S. Microsoft  recommends to restart pc. funny guys. :-E

    It doesn't matter if it's a Swing timer or a Util timer. It behaves the same either way. That was one of the first things I tried.
    I ended up refactoring the code to go from a grid of individual controls (think checker board where each square is a control that draws itself), to a single "board" control that draws a grid. That seems to have fixed the issue. I can go in/out of Standby and the app doesn't eat a ton of CPU any more. The real problem may still be there, just too small of an effect to notice.
    I don't know why the original design would work fine before a Standby, but not after. Having ~200 little controls doing repaints twice a second must confuse something in the JVM/Windows versus having 4 large controls doing the same amount of drawing.
    It's working, so time to move on.

  • Regex refactoring

    Hi all,
    I'm currently in the process of refactoring some code to which i need to make bulk changes. I have a particular example in mind. I've got a lot of constants defined, for example's sake similar to-
    public static final Car CAR_333 = new Car("CAR_333", BodyType.SEDAN, "RED", 2, null, null, false);There's a lot of these constants in this class. But we've changed the way we're representing BodyType- it's no longer going to be an object but a String representation (essentially so we don't have to serialise the object when we sent it across, but that's another kettle of fish). So the new code will need to look like the following:
    public static final Car CAR_333 = new Car("CAR_333", "SEDAN", "RED", 2, null, null, false);My question is, what would be the best way to make this change? I've done a lot of these bulk changes through regular expressions, but I can't quite seem to fathom one to turn BodyType.XXX into "XXX".
    Any thoughts?

    uncle_alice wrote:
    The exact syntax will vary depending on the tool you use to do the replacements. In my editor (EditPad Pro), I would use search: BodyType\.(\w+)
    replace: "$1" In a Java program I would do something like str = str.replaceAll("BodyType\\.(\\w+)", "\"$1\"");
    Brilliant!
    Many thanks Uncle_Alice, you've saved me from a lot of tedium!

  • Elimination of Junk Code

    Hello All,
    I am working on a large project which has been developed over a long time with many developers.
    The problem I am facing is
    1. There are many unused functions. These unused functions cause code bloat and unnecessary maintenance.
    2. Unused/repetead constants. Every module has constants files. also there are constants file in the common area. Many constants defined in common area and module specific files are not being. On the other hand, some things like "yes", "no", "cancel" are defined many times in module specific constants files.
    3. Resource bundles being used for i18n have many unused resources.
    Is there a utility or script available which will point out these things so that I can just go an remove these functions, variables etc?
    The other way is to do a manual code review but it is taking a very a very long time.
    regards,
    Abhishek.

    I do not want to start completely refactoring the code
    yet. So I don't want the tool to do "replace temp with
    query" or "change bi-directtional to unidirectional
    assosiation" kind of stuff.
    I want to do just cleanup.
    Do you have a tool in mind which does only this kind
    of cleanup ?
    regards,
    Abhishek.sorry i cant help you but im interest to know if a tool like that exsit, please reply his post (by the way does someone have problem with email notification, i didnt receive email notification even if someone reply to a topic i watch since, humm, 2-3 weeks... and i dont even change my setting, and my mailserver work fine)
    thx

  • WebPart drop down values working fine on PostBack in Dev. Environment (Single Machine) not in Farm

    We have three drop downs (ddlRotation, ddlOnCallType and ddlHospital) in our webpart. All values are being populated dynamically. One from list (ddlHospital) and other from tool part properties. For dropdown populated from list, we are storing values  in
    View State.
    WebPart is working fine in development environment (single  machine) while on production ( 1 front end, 1 index and 1 db server), drop down values disappear after post back. Below is the code.
    protected void Page_Load(object sender, EventArgs e)
    try
    if (!Page.IsPostBack)
    LoadData();
    if (!string.IsNullOrEmpty(webPart._rotationDetail))
    ddlRotation.Items.Add(new ListItem("All", "0"));
    int i = 1;
    string[] strRotationDetail = webPart._rotationDetail.Split(':');
    foreach (string str in strRotationDetail)
    ddlRotation.Items.Add(new ListItem(str, i.ToString()));
    i++;
    if (!string.IsNullOrEmpty(webPart._onCallTypes))
    ddlOnCallType.Items.Add(new ListItem("All", "0"));
    int j = 1;
    string[] strOnCallTypes = webPart._onCallTypes.Split(':');
    foreach (string str in strOnCallTypes)
    ddlOnCallType.Items.Add(new ListItem(str, j.ToString()));
    j++;
    catch (Exception ex)
    private void LoadData()
    SPSecurity.RunWithElevatedPrivileges(delegate()
    using (SPSite spSite = new SPSite("SITE_URL"))
    using (SPWeb spWeb = spSite.OpenWeb())
    SPList oList = spWeb.Lists[webPart.destListName];
    SPListItemCollection setuplistItems = oList.Items;
    if (setuplistItems != null && setuplistItems.Count > 0)
    DataTable dtSetupData = setuplistItems.GetDataTable();
    if (ViewState["SetupData"] != null)
    ViewState.Remove("SetupData");
    ViewState.Add("SetupData", dtSetupData);
    else
    ViewState.Add("SetupData", dtSetupData);
    LoadHospitalCombo();
    dateControl.SelectedDate = DateTime.Now;
    else
    // some error message
    private void LoadHospitalCombo()
    if (ViewState["SetupData"] != null)
    DataTable dt = (DataTable)ViewState["SetupData"];
    DataView dv = dt.DefaultView;
    ddlHospital.Items.Clear();
    ddlHospital.DataTextField = "TITLE";
    ddlHospital.DataValueField = "TITLE";
    ddlHospital.DataSource = dv.ToTable(true, "TITLE");
    ddlHospital.DataBind();
    ddlHospital.Items.Insert(0, "All");
    Any help?
    http://farhanfaiz.wordpress.com

    Running your code in try/catch and doing nothing on exception, is not a good idea. Please try to put logging in your code as I believe your code is throwing exception. It's difficult to say seeing such a code what's wrong. Maybe the list doesn't exist or
    exists with different name/title, or viewstate is disabled or webpart properties are not populated... there's so many possibilities. Also if possible refactor your code as shown below:
    //Your Code, you are loading all items from database and then counting it
    SPListItemCollection setuplistItems = oList.Items;
    if (setuplistItems != null && setuplistItems.Count > 0)
    //Refactored Code
    if (oList.ItemCount > 0)
    Thanks,
    Sohel Rana
    http://ranaictiu-technicalblog.blogspot.com

Maybe you are looking for

  • Shipment Cycle

    Dear All, Can anybody tell me, what are the steps involved in processing the Shipment Cycle and capturing the Transporter's (vendor) cost calculation ? Rgds, Indrajit Dey

  • No search help for Custom field ZZKUKLA in vk11

    Hi, I have added the field KUKLA - Customer classification as a pricing field in KOMP. Created an access sequence as follows: Sales Org.-> Customer Classification - material group. In the creation of the record in VK11 I'm not getting the search help

  • Exchange2010 SP3 RU4, database in a DAG setup fail error 3145

    We are an Exchange 2010 sp3 ru4 running on a hybrid Physical(MB servers) virtual (CAS/HUB servers) with 6 DBs' inonw DAG in a single site with local witness server. We experienced a failure on one of the DBs wit an error 3145 " Incremental seeding of

  • About the smartforms in hr-abap

    hi board,                  i need a smartforms in hr-abap... i know the  tcode for the smartform............but the problem... i need a standard smartfoms in hr-abap.. tcode will be : hrforms................................

  • Lost my referenced masters after update 3.0.1

    Dear all, after the update to 3.01 a few hours ago I have no more access to my referenced masters. When I try to open Photoshop or other plug-ins there is an error message. After having so much trouble with the update from A2 to A3 whilst getting the