Skip to content
Advertisement

How can I avoid having to rely on an object of another class to make the methods in a different class work?

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?

Advertisement

Answer

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 ????)

And now you can call it anyway you like, for example…

public class Main {
    
    public static void main(String[] args) {
        Generator.specialValidator("some text", 8);
    }
    
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement