Running on Java 19-ea+23-1706 (Preview)
Home of The JavaSpecialists' Newsletter

3.9 Scrambler Strategy Extracted

Juppies 2 by Dr Heinz M. Kabutz

We have tried two different word scramblers by copy and pasting them. They are almost identical, except for how we scramble the char[]. A better approach is to extract the abstract method scramble(char[]) into its own interface which we will call Scrambler. Since it is an interface, this can no longer have the modifier protected. We rename our RandomScrambledWordLibrary to a RandomScrambler that instead of extending the ScrambledWordLibrary implements the Scrambler interface. This means we do not need a constructor anymore, and we need to make the scramble(char[]) method public. All methods in interfaces are public by default, even without a modifier. A subclass method can never be less visible than the superclass method.

NetBeans recommends that we add the @Override annotation to our method. This is strictly speaking not required by Java, since it was added in Java 5 and a lot of old code out there didn't have it. But I have seen the @Override annotation discover bugs, and that's a great help.

Our ScrambledWordLibrary now no longer needs to be abstract. We add another field Scrambler and initialize that in the constructor too. Inside our getScrambledWord(), we now delegate the scrambling functionality to our given scrambler.

We also rename our SortedScrambledWordLibrary to the SortedScrambler implementing the Scrambler and this now simply sorts the array of letters.

Both the SortedScrambler and the RandomScrambler are much simpler than before, doing exactly one thing. We can imagine reusing these classes in lots of different places where we need to scramble characters.

We also need to change our WordLibrary to pass in a ScrambledWordLibrary that uses a RandomScrambler instead of our earlier RandomScrambledWordLibrary.

We test it and make sure it still works.


When you load these comments, you'll be connected to Disqus. Privacy Statement.

Table of Contents

We hope you enjoyed this tutorial. If you did, you will also enjoy our courses. We suggest you start with Extreme Java - Advanced Java, followed by Extreme Java - Concurrency Performance for Java 8.

About the Author

Heinz Kabutz Java Conference Speaker

Java Champion, author of the Javaspecialists Newsletter, conference speaking regular... About Heinz

Superpack '22

Superpack '22 Our entire Java Specialists Training in one huge bundle more...

Free Java Book

Dynamic Proxies in Java Book
Java Training

We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.

Java Consulting

We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...

Java Emergency?

If your system is down, we will review it for 15 minutes and give you our findings for just 1 € without any obligation.