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.
Related
I'm looking for a way to add some methods into exists class like this:
String s = "";
s.doSomething();
In objective C, I can use category to do this.
#interface NSString( Stuff)
-(void)doSomething();
#end
Is android has something like that? Or another hack?
Update: Actually, I got this problem: I use a class (not final) from jar file (so, I can't touch its source code). Then I want to add methods( or something like that) into this class without using inheritance. For example:
public class Provider{
// many methods and fields go here...
public String getName(){}
}
All I want to do is:
provider.print(); //that call getName() method;
I also tried proxy pattern, it worked, but I don't like that way (because it like a wrapper class, I must store an object with many fields and methods to use only one method):
public class ProxyProvider{
Provider provider;
public ProxyProvider(Provider provider){
this.provider = provider;
}
public void print(){
String name = provider.getName();
//do something
}
}
Is there any way to solve that?
You could create a utility class with static methods:
public final class ProviderUtils {
private ProviderUtils() {} // not instantiable, it is a utility class
public static void print(Provider provider) {
String name = provider.getName();
// print the name
}
}
In your code, you can then call it:
Provider p = new Provider(...);
ProviderUtils.print(p);
And if that class only has one print method, you can maybe call it ProviderPrinter instead of ProviderUtils.
In the end you don't have thousands of possibilities - you can:
extend the class and whatever method you need in the sub class => you said you don't want that
modify the source code of the class and recompile your own version of the jar
wrap the class in a wrapper that adds the methods you need (your ProxyProvider example)
put the methods you need in a static utility class (what I proposed above)
modify the class at runtime and add a method, but that's a complicated path because you need to play with classloaders.
It is not possible, however, there is a java like DSL available called Xtend that can be used as a compelling replacement for JAVA that might be work looking at which supports extension methods like this.
http://www.eclipse.org/xtend/
DISCLAIMER: I am in no way associated to this I am just an avid user of the core technology that was used to create xtend called xtext. I have considered using xtend on an Android project
In Java, a class can be extended using regular inheritence unless it final. String is final, because Strings are immutable, and therefore are intentionally protected against subclassing.
Also, adding behaviour by subclassing is considered bad practice in many cases - the coupling is simply too strong and sticks with you for instances of your objects you are ever going to create. The rule of thumb is "favour composition over inheritance".
Having said this, there are many approaches / patterns to solve your special problem. Decorator might be the pattern you are looking for.
Please update your question or post a new one with more information.
Try to extend the class in question and add your methods to it. if that can't be done (like it's been said, String is final) then just write a wrapper around it with the methods you want and the object you want to extend.
Like
public class MyString
{
private String internal;
//your methods
}
try to further elaborate your problem so i can give a better answer. like whats the real object in question and what you really wanna do, if you can disclose it that is.
The following code illustrates the situation:
class Human {
private String heart = "default heart";
public void control(Human h) {
h.heart = "$%^&*##!#^";
}
public String getHeart() {
return heart;
}
}
public class HumanTest {
public static void main(String[] args) {
Human deb = new Human();
Human kate = new Human();
System.out.println(deb.getHeart());
kate.control(deb);
System.out.println(deb.getHeart());
}
}
Here heart [private variable] of deb got modified unfortunately. :)
Java allows the code to run without any error.But is it justified to give a object the privilege to access private member of other object even if the code is in the same class ?
Shouldn't Java disallow this?
As I know, private means restricting access beyond the class source code. But the same concept is applied in the source code above. and the result is disastrous since a person's heart can't be modified by any random person .
If the result is disastrous, you shouldn't code the class so that it allows it. The "bug" is not caused by code external to the class, but by code of the class itself. So it's simply a bug in your code.
If Java did not allow it, you could only compare objects of the same class by their public attributes, for example, which would either break encapsulation (by exposing private stuff), and/or be very slow (by forcing to make defensive copies of the private attributes to make them available to other objects.
Some languages have encapsulation at the object level, others (Java, C++) at the class level. It sounds like you're used to (or have just read about) encapsulation at the object level. Frankly, I find the class level much more natural, but perhaps that's just because C++ provided my introduction to programming with classes. Class-level encapsulation makes some idioms (factory methods, copy constructors, comparison operators) much easier to write. With object-level encapsulation, you end up exposing more than you really want to just to be able to implement these features.
In any case, neither way is "correct" -- they're just different.
Look into defensive copy to avoid this situation. It is because java objects operate more like references. The 'pointer' doesn't change, but once you know it you can change the value it contains.
http://www.informit.com/articles/article.aspx?p=31551&seqNum=2
This isn't breaking object orientation - it's about encapsulation of elements internal to a class.
It may seem silly that you can do this with this example but it's actually not a bad thing at all as far as I see it. The point of encapsulating elements of a class is so that other classes can't modify them - they can only see the public interface of class Human for instance to make changes. This means more than one person can work on the same project, writing different classes (or you can work on the same project at different times writing different classes) and they don't need to know the inner workings of the code.
However, the only place (bar reflection) you can access a private field directly in Human is from Human. When you're writing the Human class, if you choose to make modifications to private fields of other Human objects, that's up to you - but it's all contained within that one class, which is your design. If you do this in a way that's not appropriate, then it's a flaw in your design and not with Java - there's some cases where it makes perfect sense to do this!
Well, the way I see it and this is just my interpretation of the private keyword, a private is private to the class and can be accessed inside the class. It is not restricted to instances of the class. Therefore you can't do kate.heart="xpto" in the "humantest" class because that would try to breach it's privacy, but using kate's code to alter deb's heart is allowed because it is being handled inside the class.
Java language strictly following the Object oriented concept. Here also that's correct..ritght? Using the object of your class you are modifying your class's variables. But its upto the programmer who can have control over his objects.
Human's heart is private inside Human's class. But using the control method you are giving access to it from outside. That's why it gets modified..What's the problem in that.?
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.
Most of the time I define constants in the same class where i want to use them.
But now i have to define all common constants in a separate class. I have seen two version of constants defining classes:
a. It will give compile time error, if you try to create object of Consts.
final class Consts {
private Consts(){}
public static final String TAG = "something";
}
b. If will throw a run time exception, if you try to create a object of Consts.
final class Consts {
public Consts(){
throw new RuntimeException();
}
public static final String TAG = "something";
}
check this class of android http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/Manifest.java
Why they have used second version?
Which one should I use and why should I go for second version?
I don't see any reason for the second version, as the first one (private constructor) does exactly what you want.
Another common idom is to make the constant-holder an interface. However, this is not universally appreciated and can lead to people implement-ing that interface, which is often considered a code smell.
From my point of view, there is no reason to use the second approach. It is misleading from the API since the class exposes a visible constructor that will throw an exception in any case. Clients may fall into that trap.
However, there are other options, too, e.g. you could make Consts an interface
interface Consts {
String TAG = "somthing"
}
This would allow for classes that implement the interface and thereby have "easier" access to the constants (without static imports). Another advantage would be, that you could use find references even if you only have the compiled classes in your IDE. Since the compiler will inline the constants into the using classes, references to TAG are hard to find. If the clients implement that interface, they can be easily lookup up. However, some coding guidline forbid that.
The next option that is possible, would be an enum. The JVM will ensure that there is only one instance for each constant in an enum class:
enum Consts {
TAG, OTHER, ..
}
You can use both, first is simpler and better because causes 'compile' errors, not runtime, i.e. you catch the problem before.
You can also make the class private in the package (not using the public modifier) and write the other classes in the package (if it's always you writing them) so that they don't instantiate that class. Yes, java is OOP, but you don't need to be pedantic. :) I've never seen anybody instantiating a class of static fields by mistake, and if he/she does, than it makes no harm.
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.