Reputation: 675
I have two classes in my Java project that are not 'related' to each other (one inherits from Thread, and one is a custom object. However, they both need to use the same function, which takes two String arguments and does soem file writing stuff. Where do I best put this function? Code duplication is ugly, but I also wouldn't want to create a whole new class just for this one function.
I have the feeling I am missing a very obvious way to do this here, but I can't think of an easy way.
Upvotes: 0
Views: 1098
Reputation: 2376
To answer the first part of your question - To the best of my knowledge it is impossible to have a function standalone in java; ergo - the function must go into a class.
The second part is more fun - A utility class is a good idea. A better idea may be to expand on what KitsuneYMG wrote; Let your class take responsibility for it's own reading/writing. Then delegate the read/write operation to the utility class. This allows your read/write to be manipulated independently of the rest of the file operations.
Just my 2c (+:
Upvotes: 0
Reputation: 48616
[a function], which takes two String arguments and does soem file writing stuff
As others have suggested, you can place that function in a separate class, which both your existing classes could then access. Others have suggested calling the class Utility
or something similar. I recommend not naming the class in that manner. My objections are twofold.
Utility
is a suitable name because the class is utilized by others. But in that case the name describes how the class is used, not what it does. Classes should be named by what they do, rather than how they are used, because how they are used can change without what they do changing. Consider that Java has a string
class, which can be used to hold a name, a description or a text fragment. The class does things with a "string of characters"; it might or might not be used for a name, so string
was a good name for it, but name
was not.So I'd suggest a different name for that class. Something that describes the kind of manipulation it does to the file, or describes the format of the file.
Upvotes: 1
Reputation: 12901
Sounds like an ideal candidate for a FileUtils
class that only has static functions. Take a look at SwingUtilities
to see what I'm talking about.
Upvotes: 1
Reputation: 240860
Create a Utility
class and put all common utility methods in it.
Upvotes: 1
Reputation: 2923
You could make the function static in just one of the classes and then reference the static method in the other, assuming there aren't variables being used that require the object to have been instantiated already.
Alternatively, create another class to store all your static methods like that.
Upvotes: 0