Am trying to increase security to my request payload, one of the measures is encrypting or blurring the member key of my json this way it's more ambiguous...
Here is what am trying to do,
public class LoginRequest {
private static final String SERIALIZED_NO = BuildConfig.DEBUG ? "no": "xyz";
private LoginRequest() {
// This class is not publicly instantiable
}
public static class ServerLoginRequest extends ParentRequest {
#Expose
#SerializedName(SERIALIZED_NO)
private String no;
Here is an image of my code...
Now the error is that this, #SerializedName(SERIALIZED_NO) must be a constant
i read some articles but no luck so far i think there is no way of conditional annotation like in C#, btw, of course, i can handle this with my back end since its not java, in some smart way.
This looks like a duplicate of How to supply value to an annotation from a Constant java to me however there is solution but I don't think you'l like it :)
Here is what you can do:
Create two new source code hierarchies, one starting with debug and the other starting with release - at the same level as your main hierarchy.
Place one copy of your model under debug/java/...your package structure to model..., with #SerializedName("no")
Place another copy of your model under release/java/...your package structure to model..., with #SerializedName("xyz")
Remove your data model from main/...your package structure to model... hierarchy
You will now be able to use your model under main but it will always be one or another, depending on build type you are using.
SERIALIZED_NO is obviously not constant. Its value is dependent to BuildConfig.DEBUG. It sounds however a bit unnecessary to use a constant as condition to make another constant which won't be a constant anymore. Try to move definition of SERIALIZED_NO to interface and see what happens otherwise you can use Dependency Injection that is equivalent to compiler directives in C++.
Related
So I am writing a program right now and am conflicted about how I should program it. I have two options:
public class Translator {
private Translator(){}; //prevents instantation
/****
***Stuff
***/
public static String translate(String oldLanguage, String newLanguage, String text){
//METHOD Code
}
}
or
public class Translator {
private String oldLanguage;
private String newLanguage;
public Translator(String oldLanguage, String newLanguage){
this.oldLanguage = oldLanguage;
this.newLanguage = newLanguage;
};
/****
***Stuff
***/
public String translate(String text){
//METHOD Code
}
}
Which should I use and why? This will be the API end of my program.
Also, as programmer which do you find more convenient when dealing with APIs and why?
I would prefer to use the stateless version of translator, but I would prefer a state-full version of translated. The reason is, if you get rid of state then you can often get rid of an entire class of synchronization bugs while moving some of the important information closer to where it is actually used. Imagine, for example, if the two language variables were part of a 1000 line class. Would you want to look up how they are set every time they are used?
The reason I like state for translated is whereas a general translator can exist without knowing what languages it is going to be used for, if you lose what languages are used in a translated, you don't know as well what to do with it anymore (similar to losing your units in a math problem).
For the stateful option, a version I like better is, instead of:
...
private String oldLanguage;
private String newLanguage;
use:
...
private final String oldLanguage;
private final String newLanguage;
... and instead of something like:
myTranslator.setLanguages("spanish", "english")
Translated myTranslated = myTranslator.translate(original)
you can use:
Translator spanishEnglish = new Translator("spanish", "english")
Translated myTranslated = spanishEnglish.translate(original)
That's quite an interesting question, which doesn't have a single best answer. The criteria to choose, out of the top of my head, are mainly:
do you intend to instantiate a translator and reuse it several times with the same old and new languages?
does your translator need to keep some state in memory to be able to translate, without having to reload this state every time a translation is needed?
does your translator have other methods that also use the old and new languages?
is there somewhere in the application where the translator would have to be called without even caring/knowing about what the old and new language are, taking a pre-configured translator as argument?
do you need to be able to mock a translator and inject it in various other components of your code to unit-test them?
If the answers to these questions are yes, then a stateful translator (i.e. your second option) should be used. If the answers are no, then you could go with the first option.
As per the Object Oriented Programming standard, class is a representation of an entity. So you should define something as an attribute of class only if those are the properties of the entity represented by class. Having said that, add oldLanguage and newLanguage to your Translator class only if Translator entity has these attributes.
I would prefer to use the first one
public class Translator {
private Translator(){}; //prevents instantation
/****
***Stuff
***/
public static String translate(String oldLanguage, String newLanguage, String text){
//METHOD Code
}
}
why ?
the answer why should I instantiate an object to translate some thing if I can just do it directly .
Translator.translate(S,S,S);
A method of a class can (should?) be static when it does not access any non-static members or methods of this class.
Now this leads us to the question, when a member (field) of a class should be static or not:
A member (field) of a class must be non-static if it is relevant for defining the state of an instance (= object) of this very class.
So in summary, if something is relevant for the state of an object, then make it instance data, if not (only relevant for the calculation), then pass it as parameter into the method.
In addition to that, it becomes now clear, that it only makes sense to create an instance of a class, if you wish to represent a state. If zero non-static members exist, then you don't need to be able to create an instance of your class.
I'm attempting to write a framework to handle an interface with an external library and its API. As part of that, I need to populate a header field that exists with the same name and type in each of many (70ish) possible message classes. Unfortunately, instead of having each message class derive from a common base class that would contain the header field, each one is entirely separate.
As as toy example:
public class A
{
public Header header;
public Integer aData;
}
public class B
{
public Header header;
public Long bData;
}
If they had designed them sanely where A and B derived from some base class containing the header, I could just do:
public boolean sendMessage(BaseType b)
{
b.header = populateHeader();
stuffNecessaryToSendMessage();
}
But as it stands, Object is the only common class. The various options I've thought of would be:
A separate method for each type. This would work, and be fast, but the code duplication would be depressingly wasteful.
I could subclass each of the types and have them implement a common Interface. While this would work, creating 70+ subclasses and then modifying the code to use them instead of the original messaging classes is a bridge too far.
Reflection. Workable, but I'd expect it to be too slow (performance is a concern here)
Given these, the separate method for each seems like my best bet, but I'd love to have a better option.
I'd suggest you the following. Create a set of interfaces you'd like to have. For example
public interface HeaderHolder {
public void setHeader(Header header);
public Header getHeader();
}
I'd like your classes to implement them, i.e you's like that your class B is defined as
class B implements HeaderHolder {...}
Unfortunately it is not. Now problem!
Create facade:
public class InterfaceWrapper {
public <T> T wrap(Object obj, Class<T> api) {...}
}
You can implement it at this phase using dynamic proxy. Yes, dynamic proxy uses reflection, but forget about this right now.
Once you are done you can use your InterfaceWrapper as following:
B b = new B();
new IntefaceWrapper().wrap(b, HeaderHolder.class).setHeader("my header");
As you can see now you can set headers to any class you want (if it has appropriate property). Once you are done you can check your performance. If and only if usage of reflection in dynamic proxy is a bottleneck change the implementation to code generation (e.g. based on custom annotation, package name etc). There are a lot of tools that can help you to do this or alternatively you can implement such logic yourself. The point is that you can always change implementation of IntefaceWrapper without changing other code.
But avoid premature optimization. Reflection works very efficiently these days. Sun/Oracle worked hard to achieve this. They for example create classes on the fly and cache them to make reflection faster. So probably taking in consideration the full flow the reflective call does not take too much time.
How about dynamically generating those 70+ subclasses in the build time of your project ? That way you won't need to maintain 70+ source files while keeping the benefits of the approach from your second bullet.
The only library I know of that can do this Dozer. It does use reflection, but the good news is that it'll be easier to test if it's slow than to write your own reflection code to discover that it's slow.
By default, dozer will call the same getter/setters on two objects even if they are completely different. You can configure it in much more complex ways though. For example, you can also tell it to access the fields directly. You can give it a custom converter to convert a Map to a List, things like that.
You can just take one populated instance, or perhaps even your own BaseType and say, dozer.map(baseType, SubType.class);
I theoretically understand the point why there is no abstract static in Java, as explained for instance in Why can't static methods be abstract in Java .
But how do I solve such a problem then?
My application uses files of a few types, which I want to assign static properties like a description of that file type (like "data file", the other being "config file", etc.).
Obviously, I would put that into a static String so that the description is accessible without instancing a file (useful for the GUI f.i.).
On the other hand, obviously all file types should have some common methods like getStatus(), which obviously I want to inherit from a common superclass MyFileType.
getDescription() would of course be abstract in the superclass.
Tried using a combination of a superclass and an interface, but similar problem: A static implementation of an abstract method is not allowed.
How would a Java guru solve this?
Is it really such a bad implementation that I want to create?
Many thanks,
Philipp
To restate the problem: you want your per-file-type classes to have statically available information on the type (e.g., name and description).
We can easily get part-way there: create a separate class for your type info, and have a static instance of this (appropriately instantiated) in each per-file-type class.
package myFileAPI;
public class TypeInfo {
public final String name;
public final String description;
public TypeInfo(String name, String description) {
this.name = name;
this.description = description;
}
}
and, say:
package myFileAPI;
public class TextFile {
public static final TypeInfo typeInfo
= new TypeInfo("Text", "Contains text.");
}
Then you can do stuff like:
System.out.println(TextFile.typeInfo.name);
(Of course, you could also use getters in TypeInfo to encapsulate the underlying strings.)
However, as you said, what we really want is to enforce the existence of a particular signature static method in all your per-file-type classes at compile time, but the 'obvious' design path leads to requiring an abstract static method in a common superclass which isn't allowed.
We can enforce this at run-time though, which may be good enough to ensure it is coded correctly. We introduce a File superclass:
package myFileAPI;
public abstract class File {
public static TypeInfo getTypeInfo() {
throw new IllegalStateException(
"Type info hasn't been set up in the subclass");
}
}
If TextFile now extends File, we will get this exception when calling TextFile.getTypeInfo() at runtime, unless TextFile has a same-signature method.
This is quite subtle: code with TextFile.getTypeInfo() in still compiles, even when there is no such method in TextFile. Even though static methods are bound at compile time, the compiler can still look through the class hierarchy to determine the compile-time static call target.
So, we need code like:
package myFileAPI;
public class TextFile extends File {
private static final TypeInfo typeInfo
= new TypeInfo("Text", "Contains text.");
// Shadow the superclass static method
public static TypeInfo getTypeInfo() {
return typeInfo;
}
}
Note that we are still shadowing the superclass method, and so File.getTypeInfo() can still be 'meaninglessly' called.
This sounds like a great time to pull out the Fundamental Theorem of Software Engineering:
Any problem can be solved by adding another layer of indirection.
The problem you have right here is that a file carries around multiple pieces of information - what the type of the file is, a description of the file, the file contents, etc. I'd suggest splitting this into two classes - one class representing a concrete file on disk and its contents, and a second that is an abstract description of some file type. This would allow you to treat the file type class polymorphically. For example:
public interface FileType {
String getExtension();
String getDescription();
/* ... etc. ... */
}
Now, you can make subclasses for each of the file types you use:
public class TextFileType implements FileType {
public String getExtension() {
return ".txt";
}
public String getDescription() {
return "A plain ol' text file.";
}
/* ... */
}
You can then have some large repository of these sorts of objects, which would allow you to query their properties without having an open file of that type. You could also associate a type with each actual file you use by just having it store a FileType reference.
annotations could be fine for your purpose.
#FileProperties(desc="data file")
public class DataFile extends XFile { ... }
FileProperties props = DataFile.class.getAnnotation(FileProperties.class);
String desc = props.desc();
Accessing the info still requires reflection, however it's a little better than using static field/method.
Java compiler does not enforce that all subclasses are annotated as such. You can add your logic to the compiler (using annotation processing) but that's too complicated. It's ok to check it at runtime.
Update:
This is also possible:
#FileInfoClass ( DataFileInfo.class )
#public class DataFile
The question is not clear enough to provide an objective answer. Since I cannot give you a fish, this answer is more on the lines of "Teach you to fish" :)
When faced with design issues like these, where you think "duh..now sure why such a simple thing is so hard" more often than not, you are either designing it just incorrectly, or you are overcomplicating things. If I am empathizing correctly, your design issue seems like a "common requirement" yet the language is not allowing for any elegant solutions.
Trace back your design steps/decisions
question all the "obvious" and "of course" you are basing your design on (you are using quite a few above)
see if things can be simplified (don't take any of the OO concepts to their logical extreme. Make compromises based on ROI)
...and you will most likely arrive at an acceptable answer.
If you still don't, post back the classes and interfaces you think you want (with compile errors since language is not allowing certain things), and maybe we can help you tune your design.
I basically had the exact same problem.
You may want to look at the
solutions suggested to me in my question
I liked Bozho's idea, but according to himself it was a bad idea. :) I suppose better programmers can explain why it is so. Ralph's and Jon Skeet's solution also works.
Sounds like you need to use a singleton. Basically, you call a static method like MyFileTypes.getDataFileInstance() which creates a single instance (or reuses if already created) of an object and when you first create it setup the 'constants' as needed. I'll see if I can find you a good example but your post isn't very clear about how you want to use it.
You could create a FileMetadata class that has all the info you need. When your app starts up, you could create instances of FileMetadata, and keep static pointers to them so you can access them from anywhere in the JVM.
This way you put the abstract stuff in the actual instances; anything the stuff that does not call for abstract semantics can be static...
I don't know how a java guru would solve it, but I'd probably create a resource bundle with all the descriptions in a properties file like this:
com.bigcompany.smallapp.files.DataFile=Data file
com.bigcompany.smallapp.files.ConfigFile=Config file
Handling the bundle can conveniently be placed in the superclass or elsewhere.
Another option is to use reflection to access the static fields in each subclass, but then you need to make sure that all the subclasses have a static field with the same name.
There could be other options too, even refactoring the code so that the subtypes aren't represented by a separate class each, but in general there's no watertight solution.
Instead of putting your static properties actually in static properties, put a reference to MyFileTypeDescription as a static property.
i.e.
class MyFileType {
static MyFileTypeDescription description;
...
<your regular attributes>
}
abstract class MyFileTypeDescription {
String name;
abstract String getDescription();
}
Something along this way, if I understood your problem correctly.
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.
We are in the process of refactoring some code. There is a feature that we have developed in one project that we would like to now use in other projects. We are extracting the foundation of this feature and making it a full-fledged project which can then be imported by its current project and others. This effort has been relatively straight-forward but we have one headache.
When the framework in question was originally developed, we chose to keep a variety of constant values defined as static fields in a single class. Over time this list of static members grew. The class is used in very many places in our code. In our current refactoring, we will be elevating some of the members of this class to our new framework, but leaving others in place. Our headache is in extracting the foundation members of this class to be used in our new project, and more specifically, how we should address those extracted members in our existing code.
We know that we can have our existing Constants class subclass this new project's Constants class and it would inherit all of the parent's static members. This would allow us to effect the change without touching the code that uses these members to change the class name on the static reference. However, the tight coupling inherent in this choice doesn't feel right.
before:
public class ConstantsA {
public static final String CONSTANT1 = "constant.1";
public static final String CONSTANT2 = "constant.2";
public static final String CONSTANT3 = "constant.3";
}
after:
public class ConstantsA extends ConstantsB {
public static final String CONSTANT1 = "constant.1";
}
public class ConstantsB {
public static final String CONSTANT2 = "constant.2";
public static final String CONSTANT3 = "constant.3";
}
In our existing code branch, all of the above would be accessible in this manner:
ConstantsA.CONSTANT2
I would like to solicit arguments about whether this is 'acceptable' and/or what the best practices are.
A class with only static fields is a code smell. It's not a class.
Some people use interfaces, so they can implement it to use the constants more easily. But an interface should be used only to model a behaviour of a class. (http://pmd.sourceforge.net/rules/design.html#AvoidConstantsInterface) Using static imports from Java 5 removes the need for simple constant usage at all.
Are your constants really Strings, or just used as Strings. If they are different options for some type (so called enumerations), you should used typesafe enumerations, using enum in Java 5 or the Enum provided by Commons Lang. Of course, converting your code to use enums might be a little work.
You should at least split the constants to groups of related constants in files with proper business name. Moving the final members is easy in IDE and will update all usages.
If you can afford it, convert them to enums then. (Think about using about a script to do that, often it's possible.) Class hierarchies are only usefull, if there is a relation between the constants/enums. You can keep the Strings if you have to but still think about them as entities, then extends might make sense for some (describing is-a relation). First enums can be simple classes made by yourself if serializing is not a problem. Enums are always favourable due to their type safe nature and the extra name showing intend or business/domain specific things.
If the constants are really String constants use a Properies or ResourceBundle, which can be configured by plain text files. Again you can script the refactoring using the constant names as resource bundle keys and generate both files automatically.
I don't like it, but it's probably the best you can do right now.
The right answer would be to break up the constants into coherent groups, fixing the code breaks as you go along. In C#, I'd use enums.
Peter Kofler has already discussed how you might wish to better organize constants. I'll share how to automate the transition:
The eclipse "Inline" refactoring can automatically replace constants by their defintion, saving you from having to hunt down and change each usage manually. So you'd simply change the code to:
public class ConstantsA {
public static final String CONSTANT1 = "constant.1";
public static final String CONSTANT2 = ConstantsB.CONSTANTFOO;
public static final String CONSTANT3 = ConstantsB.CONSTANTBAR;
}
public class ConstantsB {
public static final String CONSTANTFOO = "constant.2";
public static final String CONSTANTBAR = "constant.3";
}
... and then have eclipse inline COONSTANT2 and CONSTANT3 (while all affected projects are checked out, if you can't do that, look into refactoring scripts), and you're done.
I've seen this done by putting the static final String on an interface, so that you can 'implement' it and not have to worry about what to do when you need a different base class. It's just as accessible that way.
In general though, enums are pretty good at what you are trying to do, and may get rid of the "I'm not sure" feeling you are experiencing, as that's the intention of enums.
I think what you are doing is fine. Yes, the classes are tightly-coupled, but that is kind of the point -- you want to be able to reference only a single class to see all of your project-wide constants.
You do have to be diligent to ensure that ConstantsB contains only constants that are generalizable amongst all your projects, and ConstantsA contains only project-specific constants. If, later on, you realize that there is a constant in ConstantsB that you seem to be overriding in your subclasses a lot, then that's an indication it should've never been put in ConstantsB in the first place.
I think what you've got is a good first step. The next step is to gradually replace all references to ConstantsA.CONSTANT2 and ConstantsA.CONSTANT3 with ConstantsB.CONSTANT2 and ConstantsB.CONSTANT3 until you can remove the extends.
Most IDEs can be configured to show a warning if you refer to a superclass constant via a subclass, and I'd guess static analysis tools like FindBugs can do it, too.
One idea that might be slightly cleaner:
make all the constants classes interfaces
move all the constants out of ConstantsA and call it something like LegacyConstants
have LegacyConstants extend all the other, modular Constants interfaces
deprecate LegacyConstants
The goal would be not to have any inheritance between the Constants interfaces. LegacyConstants would be the only place there's any inheritance, it wouldn't declare any constants of its own, and when it's no longer used -- when every class that did use it instead refers to the proper Constants interface -- you've finished refactoring.
When you extract your constants, have the old class reference the constant defined in the new class. There's really no need to create an inheritance relationship here.
I could be wrong, but I don't think we need constants at all. It just means that you can't change the value of the constants and you probably should.