Constant Parameter Design - java

I am working with a Class that contains constants or parameter values that all classes can reference for example;
public class Parameters {
public static final String JUMP_TO_VALUE = "Parameters.JUMP_TO_VALUE";
public static final String EXCEPTION_ID = "Parameters.EXCEPTION_ID";
}
Some of the foundation classes in my application will use the parameter values in the Parameters class like so:
mapOfValues.put( Parameters.JUMP_TO_VALUE, "some_value")
This is simple enough I have some basic values in Parameters that most of my base classes will use them. There will be many situations where I will need to add addition parameters to the Parameters class, but I don't want to over populate or pollute the Parameters class ever time a new parameter is identified. I would rather create some subclass of Parameters like:
public class NetworkParameters extends Parameters {
public static final String HOST_NAME = "NetworkParameters.HOST_NAME";
public static final String POST_NUM = "NetworkParameters.PORT_NUM";
}
Some of my specific classes will use the values that are contained in this class versus putting them in the Parameters class.
These specific classes that need HOST_NAME for example I don't want them to reference the NetworkParameters class but rather the Parameters class.
I am sure people have done this before but I am looking for advice on how best to implement this design.

It is simply not possible, in the exact way you describe it.
When you reference static objects, you refer to the class that those objects are declared in. Quite simply, if you declare a constant in the NetworkParameters class, it does not exist in the Parameters class and is not accessible as such.
Separating vast numbers of parameters into different containing classes (which don't need to be subtypes of each other as this achieves nothing) is quite good practice and often used. Why do you have such an aversion to just using NetworkParameters.POST_NUM, as this is the name of the parameter and sounds completely sensible to me?
One thing that may help you (depending on your own tastes) is to use Java 5's static import feature. If, at the top of a class file, you declare
import static the.package.name.Parameters.*;
import static other.package.NetworkParameters.*;
then you will be able to use all of the constant names from both classes without any prefix at all. This is often quite nice when it's obvious what comes from where - but it can become a nightmare if you're statically importing from a few classes, especially if you don't have an IDE to work out the reference for you.
But again - why do you want to reference them as Parameters.FOO, but want them to live in a separate class? Either approach (everything in one file, different constants in different files) is good and fine if you do it completely, but you can't magically change the laws of Java references because you don't like the look of them. :-)

I don't think you would be overdoing it by putting a lot of constants in a single file. Just keep it well organized with good formatting and documentation. I dont think subclassing is want here. A subclass implies a certain relationship among objects. First off, you aren't really creating an object, so creating a subclass does not really fit the model here. Also, using a subclass here may just complicate things. For example, you will have to import multiple java files if you want to use several types of constants in another class.

Are you sure you want to be embedding these values in your code?
They sound to me like the kind of data you want to place in a configuration file, so they can be change easily without the code needing to be recompiled. A simple hash of name-value pairs from a configuration file, wrapped to be accessible in the way you need them to, might be a more flexible approach to the same problem.

Related

Is there any convention to store methods not particularly related to any class? [java]

I am currently learning Java and, while making a project, I created some methods that do not suit logically in any given class but are useful in the whole context of the project.
The best example I have is a method that splits camelCase worlds like this:
splitCamelCase -> Split Camel Case.
I have thought about creating a new abstract class called Toolbox and storing those methods there, but I wonder if there is any convention or best practice regarding this topic.
It's not uncommon to have utility classes (commonly named SomethingUtils) when it just doesn't make sense to put a method in an existing class.
There's nothing inherently wrong with it, but if you find yourself having a lot of methods or utility classes, then your design might be a bit off and you're programming in a more procedural than object oriented way.
As mentioned in comments, you don't make it an abstract class. It's a class filled with static methods working entirely on the parameters passed to them.
As kayaman sir has said if you are having too many utility classes and method it means that you code is more procedural rather than object oriented.
Nut if you still want to have a class which is just used to provide some utility then you can have such a class in java , just put some static method in them.
One of the best example of such a class is java.lang.Math.
for example following code will work
class MyUtilityClass
{
private MyUtilityClass()
{
// no object creation will be allowed
}
// make as many static methods you want
}
You can create your ToolBox Class and then you declare it as a package. After that you can import your ToolBox at the beginning of classes you want to use the methods from that ToolBox.

Is there a point to having a class with all non-static methods but no non-static fields? (or all static fields and methods along with a constructor)

I am looking at other peoples' code.
I see a class with no non-static fields but in which most of the methods are non-static, requiring you to make an object to access methods that effectively operate statically.
Is there a possible reason for this, that I am just not understanding?
EDIT
Someone asked for examples. Here is some more info.
For instance there is a file manager class. The only fields are static and are Comparators. There are some methods to do things like sort files in a list, count files, copy files, move files to an archive folder, delete files older than a certain time, or create files (basically take a base name as string, and return a File with given base name and date/time tacked on the end.)
9 non-static methods
5 static methods
I don't see a particular rhyme reason for the ones that are static vs non.
One particularly odd thing is that there are two methods for removing files. One that removes a file no matter what, and one that only removes it if it is empty. The former is a static method while the latter is not. They contain the same exact code except the later first checks if the file.length is 0.
Another odd one is a class that does encryption - all fields and methods are static but it has a constructor that does nothing. And an init() method that checks if a static variable contains an object of itself and if not instantiates an object of itself into that field that is then never actually used. (It seems this is done with a lot of classes - init methods that check for an object of itself in a static variable and if not instantiate itself)
private static File keyfile;
private static String KEYFILE = "enc.key";
private static Scrambler sc;
It has methods to encrypt and decrypt and some methods for dealing with key and file.
Does this make sense to anyone? Am I just not understanding the purpose for this stuff? Or does it seem weird?
Objects don't have to have state. It's a legitimate use case to create an instance of a class with only behaviour.
Why bother to create an instance ? So you can create one and pass it around e.g. imagine some form of calculator which adheres to a particular interface but each instance performs a calculation differently. Different implements of the interface would perform calculations differently.
I quite often create classes with non-static methods and no members. It allows me to encapsulate behaviour, and I can often add members later as the implementation may demand in the future (including non-functionality related stuff such as instrumentation) I don't normally make these methods static since that restricts my future flexibility.
You can certainly do it that way. You should look carefully at what the instance methods are doing. It's perfectly okay if they're all operating only on parameters passed in and static final static class constants.
If that's the case, it's possible to make all those methods static. That's just a choice. I don't know how the original developers would justify either one. Maybe you should ask them.
Let me rephrase this question a bit,
Even though methods are non-static why would one declare fields as static?
I have taken below quoting from Java Docs,
Sometimes, you want to have variables that are common to all objects. This is
accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
For example, suppose you want to create a number of Bicycle objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole.
For Bicycle example, kindly refer the Java Docs.
Making all methods non-static allows you to override them. This makes it a lot easier to use this class in testing, because instead of the actual implementation you can use a mock that behaves as you want it for the tests. Static methods are, in my book, a code smell and should be avoided unless there's a good reason (e.g. quite trivial utility methods).
Also, at some point in the future you might want to change the behaviour of the methods in some situation, e.g. in the form of a strategy.
In the case of your encryption class, you might want to hand your class an instance of the encryption class to handle encrypting/decrypting, but be able to configure the details in some other place. That would allow you to change the algorithm and much more easily test your own code without also having to test the encryption.

Is this an acceptable use of globals?

I am writing a rather complicated translation module which essentially translates between a form of logical representation and Java code. It spans several classes which are all decoupled from each other.
My problem is that I need to keep track of a rather extensive set of keywords which need to be inserted, for example, into variable names. These keywords must be accessible to all classes in the module, and be easy to change.
I understand that the use of globals is a red flag as far as design goes, but would it be acceptable in this case to create a class which does nothing but provide static access to said keywords? For example:
public final class KeyWords {
public static final String SELF = "self";
public static final String RESULT = "callResult";
// etc
}
My own thoughts is that it would work somewhat like a simple config class. I find this a lot more reasonable than using, for example, a mediator or passing some other bucket class between method calls, since the data is rather well defined and, importantly, not subject to modifcation during runtime.
OR, would it be better to put all these keywords into an interface instead, and let all my class inherit this? While it could work, it just does not feel right.
This isn't the worst thing ever, but it's somewhat out of date. If you're using Java 1.5 or above, an enum would be better; it gives you type safety, for instance.
public enum KeyWord {
SELF("self"),
RESULT("callResult")
;
public String getKeyword() {
return keyword;
}
private KeyWord(String keyword) {
this.keyword = keyword;
}
private final String keyword;
}
You're right that the "tuck them into an interface" approach doesn't feel right; an interface is about specifying behavior, which a methodless interface with static finals does not provide. Since Java 1.5, you can use static imports to get the same benefit without that "code pollution."
If you are going to be using the same set of keywords, across multiple classes that don't inherit from each other then I would suggest just creating a static class that reads in a text file that has all of these keywords in it.
If you use this method then you can use the "code once use everywhere" ideology that the pros always drone on about.
-Create a static class
-Read in a text file that has all your keywords saved in it
-write a couple functions that retrieve and compare keywords
-Use it in every class you want without worry of fragmentation.
Using this method also makes updating a snap because you can simply open the text file change add or delete what you want then it is fixed in every single class that implements it.

What are most graceful alternatives to constant interfaces?

I had been looking at some code developed by an off-shore group. I see at least one "constant interface" per module defined.
Example (not real world) :
public interface RequestConstants{
//a mix of different constants(int,string,...)
public static final int MAX_REQUESTS = 9999;
public static final String SAMPLE_REQUEST = "Sample Request";
}
Per my understanding it is an anti-pattern as these does not any utility in run-time, and should be avoided or tackled in a different way.
What are elegant ways to represent this? Can enums be used instead?
I prefer to put constants in the class where they make they're most relevant, and then if I have to refer to them elsewhere, just do so - possibly using static imports if that makes sense (e.g. for Math.PI).
The only real reason to put constants in interfaces was to allow you to "implement" the method-free interface and get access to the constants via their simple names without any further qualification. Static imports remove that reason.
En enum is probably not a good idea unless all the parameters are closely related. With the two parameters in your example I'd say they are not closely enough related to qualify as an enum.
But it's not necessarily a Bad Idea to include a constants class / interface like this. It does have the advantage of being centralized, which means this configuration stuff can easily be moved outside of the program -- for instance to a properties file, a command-line decoder, a database or even a socket interface -- with minimal impact to the other classes. It's really a question of what direction the design will take.
Unless you are thinking of going down that path, however, I'd say static finals in the classes where the respective parameters are used is the way to go, as has been suggested already.
Turn the interface into a final class with a private constructor.
Use final non-instantiable class, i.e. one with a private constructor.

Reasoning behind not using non-implemented Interfaces to hold constants?

In his book Effective Java, Joshua Bloch recommends against using Interfaces to hold constants,
The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class’s exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the con-stants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
His reasoning makes sense to me and it seems to be the prevailing logic whenever the question is brought up but it overlooks storing constants in interfaces and then NOT implementing them.
For instance,
public interface SomeInterface {
public static final String FOO = "example";
}
public class SomeOtherClass {
//notice that this class does not implement anything
public void foo() {
thisIsJustAnExample("Designed to be short", SomeInteface.FOO);
}
}
I work with someone who uses this method all the time. I tend to use class with private constructors to hold my constants, but I've started using interfaces in this manner to keep our code a consistent style. Are there any reasons to not use interfaces in the way I've outlined above?
Essentially it's a short hand that prevents you from having to make a class private, since an interface can not be initialized.
I guess it does the job, but as a friend once said: "You can try mopping a floor with an octopus; it might get the job done, but it's not the right tool".
Interfaces exist to specify contracts, which are then implemented by classes. When I see an interface, I assume that there are some classes out there that implement it. So I'd lean towards saying that this is an example of abusing interfaces rather than using them, simply because I don't think that's the way interfaces were meant to be used.
I guess I don't understand why these values are public in the first place if they're simply going to be used privately in a class. Why not just move them into the class? Now if these values are going to be used by a bunch of classes, then why not create an enum? Another pattern that I've seen is a class that just holds public constants. This is similar to the pattern you've described. However, the class can be made final so that it cannot be extended; there is nothing that stops a developer from implementing your interface. In these situations, I just tend to use enum.
UPDATE
This was going to be a response to a comment, but then it got long. Creating an interface to hold just one value is even more wasteful! :) You should use a private constant for that. While putting unrelated values into a single enum is bad, you could group them into separate enums, or simply use private constants for the class.
Also, if it appears that all these classes are sharing these unrelated constants (but which make sense in the context of the class), why not create an abstract class where you define these constants as protected? All you have to do then is extend this class and your derived classes will have access to the constants.
I don't think a class with a private constructor is any better than using an interface.
What the quote says is that using implements ConstantInterface is not best pratice because this interface becomes part of the API.
However, you can use static import or qualified names like SomeInteface.FOO of the values from the interface instead to avoid this issue.
Constants are a bad thing anyway. Stuffing a bunch of strings in a single location is a sign that your application has design problems from the get go. Its not object oriented and (especially for String Constants) can lead to the development of fragile API's
If a class needs some static values then they should be local to that class. If more classes need access to those values they should be promoted to an enumeration and modeled as such. If you really insist on having a class full of constants then you create a final class with a private no args constructor. With this approach you can at least ensure that the buck stops there. There are no instantiations allowed and you can only access state in a static manner.
This particular anti-pattern has one serious problem. There is no mechanism to stop someone from using your class that implements this rouge constants interface.Its really about addressing a limitation of java that allows you to do non-sensical things.
The net out is that it reduces the meaningfulness of the application's design because the grasp on the principles of the language aren't there. When I inherit code with constants interfaces, I immediately second guess everything because who knows what other interesting hacks I'll find.
Creating a separate class for constants seems silly. It's more work than making an enum, and the only reason would be to do it would be to keep unrelated constants all in one place just because presumably they all happen to be referenced by the same chunks of code. Hopefully your Bad Smell alarm goes of when you think about slapping a bunch of unrelated stuff together and calling it a class.
As for interfaces, as long as you're not implementing the interface it's not the end of the world (and the JDK has a number of classes implementing SwingConstants for example), but there may be better ways depending on what exactly you're doing.
You can use enums to group related constants together, and even add methods to them
you can use Resource Bundles for UI text
use a Map<String,String> passed through Collections.unmodifiableMap for more general needs
you could also read constants from a file using java.util.Properties and wrap or subclass it to prevent changes
Also, with static imports there's no reason for lazy people to implement an interface to get its constants when you can be lazy by doing import static SomeInterface.*; instead.

Categories