Using a function in two unrelated Java classes - java

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.

[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.
One would expect that all the code in your program was useful. That is, it had utility, so such a name conveys no information about the class.
It might be argued that 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.

Create a Utility class and put all common utility methods in it.

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.

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.

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 (+:

Related

When are dot operators required?

When calling a method, I get that you have to use instanceName.method() or className.method(). However, in some cases the instanceName or className is omitted in the code and just method() is written.
Programming language is Java. Just covering this for the AP Computer Science test and I have relatively limited knowledge of coding outside of the parameters of the course so a easy to understand explanation would be greatly appreciated.
My book says something about client programs but I'm not exactly sure what it means (both in general and about client programs specifically).
I'll put my explanation as simply as possible - Usually you would use instanceName.method() when trying to effect the variables within a class. For example a "Cat" object, you could make a cat - Cat catOne = new Cat() and then use its methods catOne.setName("Kitty");. This will set this objects name to "Kitty", leaving all other cat objects with the ability to have their own unique name.
Using className.method() is done when using a static method within a class, eg public static int method(), and then using it in another class. This does not require you to instantiate an object for that class, and can use them willingly. For example, having a class called MathConstants and using something like MathConstants.getPi() ( Sorry for the crude example ).
When methods are called like methodName() , this means that the method is located within the class itself. Usually we use this , as in this.methodName(), but just using methodName() is okay.
Hope that is easy to understand

Put methods in actual class or as static in separate class

Is it better to have methods in the actual class or to have them in an Util class as static?
example:
String name = user.getName();
or
String name = Utils.getName(user);
Is there a difference in performance?
It is better to put the methods where they logically belong. If a user has a name that can be accessed, then in the User class define the getName() method. It is simple and organized and facilitates maintenance of your code.
If you're trying to access things in a static way, and you don't need anything to do with a particular instance of a class, then keep a static.
It will be more readable, you'll save memory (no new keyword!), and it will be easier to manage.
There are at least two reasons to prefer putting the methods in the relevant class:
Grouping strongly related code together makes reading easier.
Using the minimum scope reduces the risk of a method developing several uses that are only coincidentally related. That can inhibit refactoring.
Neither of those reasons apply to genuine utility methods, such as Math.sin.
One more consideration is that if you have the static method approach like Utils.getName(user) you should have either
a non-private user.name or
a public getter on user.name
First kills encapsulation, and second creates redundancy in cases where Utils.getName(user) is just a simple get.
User.getName(user) preserves encapsulation but allows for the advantages of a static function. All of these options are likely to be as performant as you need.

Java Class That Has 90% Static Members. Good Practice Or What?

I'm 14 and have been learning java for about 4/5 months. I'm coding a game now called super mario winshine and i wanted to know if it is good practice to have a class that is mostly static variables.
The class is the one that holds all the information for the game's level/world. Since I only need one version of this class, and lots of other classes will be using it, I choose to make all the variables static. Is this good practice?
I have considered the fact that i could keep the variables "non-static" and just clone the main object i use for that class, but I thought i would rather sacrifice "O-O" for memory in this case.
As soon as you want to have two or more worlds this will fail. Say, when your first release is a runaway success and you want to add the "parallel universe" expansion set.
In my experience, 90% of the time when marketing says "oh, don't worry, there will only be one Application/Window/Database/User" they are wrong.
ADDED
I would also avoid using a true Singleton pattern with World.getInstance() etc. Those are for the rare cases where it really is an essential requirement that there only be one of something. In your case, you are using it as a convenience, not a requirement.
There is no perfect fix, YMMV, but I'd consider a single static method, something like
World World.getWorld(String name)
and then you call real (non-static) methods on the World that is returned. For V1 of your program, allow null to mean "the default world".
Some might put that method into a class named WorldManager, or, perhaps showing my age, a more clever name like Amber. :-)
It all depends upon what your methods and classes are. There is no problem in defining utility methods as static methods in a class. There is no need to make it a singleton as others are suggesting. Look at the Math class from java.lang package. It has lot of utility methods but it isn't a singleton.
Also check out static imports functionality. Using this you doesn't need to qualify method calls with the class name.
Well, what you are doing is definitely an option. Or you could use a singleton pattern:
public class World {
private static World instance = new World();
private World() {
}
public static World getInstance() {
return instance;
}
}
Now just use World.getInstance() everywhere to have a unique object of this type per application.
I would say it's definitely not a good practice.
I've not seen your code, but having several static variables in a class that other classes access freely seems to indicate that you're not really using object orientation/classes but more just writing procedural code in Java. Classes should generally encapsulate/hide all their variables - static or not - from access from other classes so that other classes don't depend on how the class is implemented.
The static part also causes problems with making threads work (global variables are hard to lock in a good way so that nothing deadlocks) and with unit testing (mocking is all but impossible)
I also agree with the other posters, if you need "global variables", at least make them singletons. That allows you to change strategy easier later and does not lock you to one world.
Edit: I'm definitely not advocating singletons as a good pattern here if someone read it like that, but it does solve some problems with static variables, esp. regarding testing/mocking compared to just statics so I'd say it's a ever so slightly lighter shade of gray :) It is also a pattern that is easier to gradually replace with better patterns by for example using a IoC container.
I think it is fine as long as you don't need anything more sophisticated, in other words, static fields are OK as long as different objects (including subclasses if there will be any) do not need different values.
You code by yourself, refactoring is easy with modern tools, me says don't fix it until it is broken, and focus on the algorithmic aspects of your project.
Perhaps you may think to encapsulate all those static fields within a different static class, as it is a good principle to "keep what changes seperate from what does not". Chances are one day you will want to initiate that static class with different values, for example want to read the initial values from an XML file and/or registry, add behaviour, etc. so instead of a static class you will implement it with a Singleton pattern.
But clearly that is not the concern of today. Till then, enjoy!
You may wish to look into implementing this class as a singleton, while there is nothing particularly wrong with your approach it may lead to some inflexibility further down the road.
Also you should take in to consideration the purpose of static members which is to be a member of the class and 'act' on/with the class not an instance of it. For example the static method in a singleton returns either a new instance of the class if one doesn't already exist or returns the instance, and because the method is static you do not instantiate a new one. This is probably worth a read because it can be somewhat confusing when determining the appropriate use of static members
I'm not sure what you are really talking about from your short description, so I'll try this:
public class Level {
static List<Mushroom> mushrooms;
static List<Coin> coins;
...
}
Is that you were describing?
You asked if this is "good practice" and I can tell you that this looks very odd, so, no, it's not.
You gain absolutely nothing by doing this. You make it impossible to have more than one Level, which brings no advantage, but it could cause trouble in the future.
I didn't understand your last paragraph where you say you made most things static to save memory. You would usually create one Level and it would be passed around (without cloning) to the various classes/methods that read from it or modify it.

Best way to add functionality to built-in types

I wonder what is the best way in terms of strict OOP to add functionality to built-in types like Strings or integers or more complex objects (in my case the BitSet class).
To be more specific - I got two scenarios:
Adding a md5 hashing method to the String object
Adding conversion methods (like fromByteArray() or toInteger()) to the BitSet class.
Now I wonder what the best practices for implementing this would be.
I could e.g. create a new Class "BitSetEx" extending from BitSet and add my methods. But I don't like the idea since this new class would need describing name and "BitSetWithConversionMethods" sound really silly.
Now I could write a class consisting only of static methods doing the conversions.
Well I got a lot of ideas but I wan't to know what would be the "best" in sense of OOP.
So could someone answer me this question?
There are a few approaches here:
Firstly, you could come up with a better name for the extends BitSet class. No, BitsetWithConversionMethods isn't a good name, but maybe something like ConvertibleBitSet is. Does that convey the intent and usage of the class? If so, it's a good name. Likewise you might have a HashableString (bearing in mind that you can't extend String, as Anthony points out in another answer). This approach of naming child classes with XableY (or XingY, like BufferingPort or SigningEmailSender) can sometimes be a useful one to describe the addition of new behaviour.
That said, I think there's a fair hint in your problem (not being able to find a name) that maybe this isn't a good design decision, and it's trying to do too much. It is generally a good design principle that a class should "do one thing". Obviously, depending on the level of abstraction, that can be stretched to include anything, but it's worth thinking about: do 'manipulating the set/unset state of a number of bits' and 'convert a bit pattern to another format' count as one thing? I'd argue that (especially with the hint that you're having a hard time coming up with a name) they're probably two different responsibilities. If so, having two classes will end up being cleaner, easier to maintain (another rule is that 'a class should have one reason to change'; one class to both manipulate + convert has at least 2 reasons to change), easier to test in isolation, etc.
So without knowing your design, I would suggest maybe two classes; in the BitSet example, have both a BitSet and (say) a BitSetConverter which is responsible for the conversion. If you wanted to get really fancy, perhaps even:
interface BitSetConverter<T> {
T convert(BitSet in);
BitSet parse(T in);
}
then you might have:
BitSetConverter<Integer> intConverter = ...;
Integer i = intConverter.convert(myBitSet);
BitSet new = intConverter.parse(12345);
which really isolates your changes, makes each different converter testable, etc.
(Of course, once you do that, you might like to look at guava and consider using a Function, e.g. a Function<BitSet, Integer> for one case, and Function<Integer, BitSet> for the other. Then you gain a whole ecosystem of Function-supporting code which may be useful)
I would go with the extending class. That is actually what you are doing, extending the current class with some extra methods.
As for the name: you should not name at for the new features, as you might add more later on. It is your extended BitSet class, so BitSetEx allready sounds better then the BitSetWithConversionMethods you propose.
You don't want to write a class with the static methods, this is like procedural programming in an OOP environment, and is considered wrong. You have an object that has certain methods (like the fromByteArray() you want to make) so you want those methods to be in that class. Extending is the way to go.
It depends. As nanne pointed out, subclass is an option. But only sometimes. Strings are declared final, so you cannot create a subclass. You have at least 2 other options:
1) Use 'encapsulation', i.e. create a class MyString which has a String on which it operates (as opposed to extending String, which you cannot do). Basically a wrapper around the String that adds your functionality.
2) Create a utility/helper, i.e. a class with only static methods that operate on Strings. So something like
class OurStringUtil {
....
public static int getMd5Hash(String string) {...}
....
}
Take a look at the Apache StringUtils stuff, it follows this approach; it's wonderful.
"Best way" is kinda subjective. And keep in mind that String is a final class, so you can't extend it.
Two possible approaches are writing wrappers such as StringWrapper(String) with your extra methods, or some kind of StringUtils class full of static methods (since Java 5, static methods can be imported if you wan't to use the util class directly).

Java need help checking if string is instance

I have an interface, GenericExpression, that gets extended to create expressions (ie AndExpression, OrExpression etc.).
Each GenericExpression implementation has a string that represents it (ie "&", "+", etc.) (stored as a static variable "stringRep")
Is there any way to take a user input String and check if it represents a GenericExpression?
If not (seems likely this is the case), is there any way to achieve a similar effect with a refactored design?
Thanks!
EDIT: Offered a little bit more detail above.
Also, the end goal is to be able to arbitrarily implement GenericExpression and still check if a string represents an instance of one of its subclasses. As such, I can't just store a map of implementation - string representation pairs, because it would make make it so GenericExpression is no longer easily extendible.
Also, this is homework
Well I think you will need to define somewhere what expressions are supported by your program. I think the best way is to use a map, where you map your interface to strings. That way you can easily look up an expression with its representing string. Where you will define this map is dependant on your design. One possibility is a static method in a helper class that resolves expressions to a string like:
Expressions.get("&").invoke(true, false);
Where get is a static method on Expressions that looks up the desired expression in a static map. You will have to initialize this map in a static initializer, or let the expression instances add themselves on creation.
EDIT:
(I wanted to comment this on an answer but it seems to be deleted)
Personally I don't like the idea of classes registering themselves. It gives me the feeling of not being in control of my code. I would prefer to instantiate the classes in the Expressions class itself. The code for registering a class must be written for every new subclass anyway. I prefer to centralize this code in a single class so if I want to change logic or refactor, I only have to touch one class.

Categories

Resources