The average utility class: A stateless class that provides some functionality by exposing static methods. Its default constructor is private to avoid instantiation. When ever the average utility class is used, a hard dependency is created.
So, referencing the utility class is the way to invoke a desired method. But couldn't we replace this class reference by a "dummy object" and remove the hard dependency? Let me show you what I mean(examples are in Java). Be aware, I tried to make things as simple/short as possible!
This is an average utility class, functionality is wrapped in static methods:
public class SomeUtilClass {
// to avoid instantiation
private SomeUtilClass(){
}
public static Object someUtil(){
return null;
}
}
Instances of the following class will serve as a "dummy objects" in order to call someUtil
. It's supposed to provide the same functionality as the SomeUtilClass
does but functionality is wrapped in non-static methods.
public class SomeUtilClassButOOP {
// to create "dummy objects"
public SomeUtilClassButOOP(){
}
public Object someUtil(){
return null;
}
}
Here, both attempts in comparison:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class BringThemBothTogether {
@Test
public void test(){
// the way it's usually done
Object thisIsBrilliant = SomeUtilClass.someUtil();
// what crossed my mind
Object butILikeThis = new SomeUtilClassButOOP().someUtil();
assertEquals(thisIsBrilliant, butILikeThis);
}
}
The downside of referencing SomeUtilClass
is the hard dependency, infamous for making Tests harder than they need to be.
All of the above was done in an attempt to get rid of hard dependencies but still use utility classes.
Well, does this attempt work out? Where is the pitfall?
I would be happy, if your shared your thoughts and ideas with me :)
SomeUtilClass
?