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:

JavaScript

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…

JavaScript

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…

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement