Home > Software design >  How can I avoid having to rely on an object of another class to make the methods in a different clas
How can I avoid having to rely on an object of another class to make the methods in a different clas

Time:10-21

Maybe the title was confusing, so here's a snippet of what I'm trying to avoid:

public class Generator{ 
private static GUI userInterface;
public static boolean specialValidator(String specialEntryText)
{
    if(entryValidator(specialEntryText))
    {
        int specialChars = Integer.parseInt(specialEntryText);
        int maxPossible = Integer.parseInt(userInterface.getLength())-3;
        if(specialChars < 1 || specialChars > maxPossible)
        {
            return false;
        }
        return true;
    }
    return false;
}
public static void main(String[] args) {
    userInterface = new GUI();
 }
}

My program runs and functions as intended (keep in mind there is more to it than this), but I don't know if what I've done here is considered bad practice or what the downsides of doing it this way are. If my main method was not in the Generator class, this would not work, which seems like a problem to me.

Also, is there a specific name for what I did here, too?

CodePudding user response:

The main method is the entry point of the program, and it needs to be in a class. It does not need to be in the Generator class.

As long as there is access to the class that you want to use, you can call it from another class. In you case it is public so it should be OK.

If it is in another class it could be something like

package yourPackage;

public class Main {
    
     public static void main (String[] args) {
    
         Generator gen = new Generator ();
         //
         gen.specialValidator(..);
    }
}

CodePudding user response:

Many things jump out at me.

There seems to be a dependency on GUI in specialValidator which is producing a "tight coupling" - you can't use the method without GUI.

This doesn't seem to make sense to me. You want to focus on reducing this coupling/dependency by passing all the required information into the method directly, for example...

public class Generator {

    public static boolean specialValidator(String specialEntryText, int length) {
        if (entryValidator(specialEntryText)) {
            int specialChars = Integer.parseInt(specialEntryText);
            // Any resason we're not using the specialEntryText length?
            int maxPossible = length - 3;
            if (specialChars < 1 || specialChars > maxPossible) {
                return false;
            }
            return true;
        }
        return false;
    }
}

Now specialValidator doesn't care "how" the information is generated, only that the information is made available to it. This "decouples" the method and makes it more independent, meaning you can call it any way you like (it also supports "dependence injection" making it more testable

  • Related