We have some data in properties file. This data is used across many classes. So, we create a Properties class object in each and every class and then read data using getProperty() method. This is leading to duplication of code.
Can someone please suggest some best practices to avoid this?
One thing that came to my mind is:
Create a class
Have a public variable for each property in property file in this class
Have a method that assigns values to each and every property
In the class where property values are required, create an object for this class and access the public variables
But, things i don't like with this approach are public variables and if at all a new property is added to the property file, i need to add code to read that property in the class.
Any help is appreciated.
Thank you!
You can create a Singleton class, that loads the properties the first time it gets invoked.. and a public method that retrieves the property value, for a given property key..
This is assuming you're using a standart Properties file... But you can extrapolate this to any key-value pair, changing Properties type to a Map or something else.
Something like
public class PropertyHandler{
private static PropertyHandler instance = null;
private Properties props = null;
private PropertyHandler(){
// Here you could read the file into props object
this.props = .....
}
public static synchronized PropertyHandler getInstance(){
if (instance == null)
instance = new PropertyHandler();
return instance;
}
public String getValue(String propKey){
return this.props.getProperty(propKey);
}
}
Then you can invoke this as needed.. from any code.. like this.
String myValue = PropertyHandler.getInstance().getValue(propKey);
Hope this helps
for me static inner class is the best possible way to do it. It will do it with lazily, as class loading is synchronized so thread safe, plus performant also. So with this we are achieving three things:
good performance because with synchronizing the liveliness will suffer, but here we are using static inner class.
thread safety because when inner class will be loaded than only map will be initialized as the class loading is thread safe hence all total thread safe.
Inner class will be loaded when we will call Singleton.initialize().get(key) so the map gets initialized lazily.
Below is the code...
public class SingletonFactory
{
private static class Singleton
{
private static final Map<String, String> map = new HashMap<String, String>();
static
{
try
{
//here we can read properties files
map.put("KEY", "VALUE");
}
catch(Exception e)
{
//we can do the exception handling
System.out.println(e);
}
}
private static Map<String, String> initialize()
{
return map;
}
}
public static String getValue(String key)
{
return Singleton.initialize().get(key);
}
}
One out of the box option is to use system properties. You can add your own system properties to your execution environment.
You can do this with a dedicated class having a static Properties object. See here for an example.
I could be misunderstanding your data flow here, but this is what seems "normal" to me:
Create a readPropFile method.
This should read a file and appropriately parse the properties it finds.
These properties can be stored in a Map<String, Object>, hashed by property name.
Read property file once (presumably when the application starts, or whenever it's appropriate to load properties) --> Properties object (say, props).
Pass props around to anything that needs access to those properties.
Or if you don't want to pass it around explicitly, use a static accessor as illustrated here.
Access properties using props.get("PROPERTY_NAME") (which just looks up that property in the internal Map).
If you don't want to use String lookups, you can keep an enum of valid property names somewhere, and do storage/lookups using that, but then you have to update that enum every time you add a new property to the file.
I've had success using an Enum, and in the constructor using the name() method to read a property of the same name. Be sure to handle exceptions in a reasonable way or else the whole class will fail to load and you won't get a helpful error message.
Benefits of this approach are that each enum value automatically corresponds to a property without having to write individual mapping code for each property. You do of course need an enum value for each property (that's unavoidable if you want DRY prop references), but you avoid repetitive per-property initialization code using unchecked Strings.
Drawbacks are that enums don't allow generic types, so if you wanted certain properties to return Integer and others to return String, then you might be better served with a classic singleton class design.
If you want to go crazy with this you could also write a script to generate your Enum or singleton java source code from the properties file, to keep your code extra DRY.
Related
My question is the same as this one except it is for Java, specifically applied to properties. Ideally I would like to create one instance of Properties, and call the methods from all of the classes without creating new instances. I would also want to read from a single instance of properties so I only have a single source of the truth.
I have read the API for Properties and it doesn't answer my question.
This question indicates I need to include the reference in the class constructor. Is there a better way??
The fisrt link, "this one" is a link to the Oracle documentation...
If you want to load your properties only once, you should use the singleton pattern. But be carefull that this pattern can be an anti-pattern and may make your unit tests more complex.
To avoid those drawbacks it is better to pass the reference to your properties via a constructor.
/* This is your singleton. It takes care of loading the properties only once and can delegate access method to it */
public class Configuration {
private static Configuration instance; // created only once
public static getInstance() {
instance = // Read the Singelton pattern to create it only once
}
private Properties properties; // loaded only once
public String get(String key) {
return properties.getProperty(key);
}
}
public class Component {
private final Configuration cfg;
public Component (Configuration cfg) {
this.cfg = cfg;
}
}
public class StarterOrDiContainer {
// ..
Component component = new Component(cfg.getInstance());
}
Let's take the system properties as example. In this implementation http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/System.java#System.getProperty%28java.lang.String%29, the properties are just stored in a static class attribute. Either make this attribute public or create public accessor methods. Short answer: just make it static.
You can initialize static data with static initializers, if things get a little bit more complex. (https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html)
I have a bunch of constants throughout my code for various adjustable properties of my system. I'm moving all of them to a central .properties file. My current solution is to have a single Properties.java which statically loads the .properties file and exposes various getter methods like this:
public class Properties {
private static final String FILE_NAME = "myfile.properties";
private static final java.util.Properties props;
static {
InputStream in = Properties.class.getClassLoader().getResourceAsStream(
FILE_NAME);
props = new java.util.Properties();
try {
props.load(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String getString(Class<?> cls, String key) {
return props.getProperty(cls.getName() + '.' + key);
}
public static int getInteger(Class<?> cls, String key) {
return Integer.parseInt(getString(cls, key));
}
public static double getDouble(Class<?> cls, String key) {
return Double.parseDouble(getString(cls, key));
}
}
The only problem with that is that for every constant that I get from this file, I have some boilerplate:
private final static int MY_CONSTANT = Properties.getInteger(
ThisClass.class, "MY_CONSTANT");
I don't think I want to use Spring or the like as that seems like even more boilerplae. I was hoping to use a custom annotation to solve the issue. I found this tutorial, but I can't really sort out how to get the functionality that I want out of the annotation processing. The Java docs were even less helpful. This should be a thing I should be able to do at compile time, though. I know the names of the class and field.
What I'm thinking is something like this:
#MyAnnotation
private static final int MY_CONSTANT;
Anyone know how I would go about doing this or at least best practices for what I want to do?
First of all, you shouldn't do it. It's practical, but too hacky and if you ever want to write a test using different settings, you'll run into problems. Moreover, nobody's gonna understand how it works.
An annotation processor can probably do nothing for you. A Lombok-style-hacking processor can. You want to make
#MyAnnotation
private static final int MY_CONSTANT;
work like
private final static int MY_CONSTANT =
Properties.getInteger(ThisClass.class, "MY_CONSTANT");
The original expression doesn't compile (due to the uninitialized final variable), but it parses fine and Lombok can do its job. There's already something related there:
#Value changes the modifiers to final private
#UtilityClass makes all fields static
So actually, you could write just
#MyAnnotation
int MY_CONSTANT;
and let your annotation change also the modifiers. I'd look at the eclipse and javac handlers for #UtilityClass, I guess all you need is to generate the initializer (which is quite some work because it's all damn complicated).
I don't think Lombok itself will implement this anytime soon, since
all the static stuff is non-testable and mostly bad style
and not everyone wants this in their code
it's not that much boilerplate
it also magically refers to the class Properties, but this could be solved via configuration
but I guess a contribution might be accepted.
Actually not quite clear why and what do you want to archive.
As I correctly undestand, you want use special kind of annotations to automatically assign values for static final constants from some properties file. Unfortunatelly it is impossible without special hacks. And annotations have nothing to do with this.
The reason is that final fields must be initialized and it is compiler's request. There aren't special annotations in java which will provide such syntactic sugar which you want.
But if you insist on this there are two ways:
Extrim way. Init all properties field with default value. Then using this hack in some static init section initialize this value using reflection mechanism and you code via reading values from properties.
Less extrim way: refuse request of final modifiers for properties fields, and using only reflection fill these fields values.
And additionally, for these ways, yes you can use annotations. But you will have to solve following technical issues:
1) Find all fields in all classes in classpath, which are annotated with you special annotation. Look at:
Get all of the Classes in the Classpath and Get list of fields with annotation, by using reflection
2) Force your Properties class to be initialized in all possible enter points of your application. In static section in this class you will load your properties file, and then using (1) method with reflection and classloader, assign values to all constants.
I have a class that create rows in table layout. The row creation depend upon data and metadata. As metadata is same for each row like show/hide visibility properties etc. so I have created metadata property as a static and initialize once using initWidget of RowWidget.
just example:
class RowWidget extends FlexTable{
public static void initWidget(Form form,
HashMap<Long, ContractorPermissionEnum> formModePermissionMap,
GridMode gridMode,
boolean isApplied,
boolean isChildExist,
boolean isChildAttachment)
{
// ...
}
}
Then I called below constructor for each record data.
public RowWidget(DataRawType dataRawType, Data data, Data parentData) {
// ...
}
As I thought this is not right approach. because as pattern when anyone see this class then understand it will create one row. I don't want to call initially initWidget. I want to pass each required parameter in constructor only like
public RowWidget(DataRawType dataRawType,
Data data,
Data parentData,
Form form,
HashMap<Long, ContractorPermissionEnum> formModePermissionMap,
GridMode gridMode,
boolean isApplied,
boolean isChildExist,
boolean isChildAttachment) {
// ...
}
But due to this, constructor have no of arguments. and I think it's also bad pattern to have 5+ parameter in constructor.
Is Anyone suggest me:
How to construct class which have same property required in another
instance?
Note:I know this is possible through static only but don't want to use static.
What is best way to construct class with having some default fix
property for all instances?
Note: I don't want to create another class to achieve it. or any getter/setter method.
Thanks In advance.
I would suggest builder pattern. You would need one extra class to create RowWidget objects. So the call would look like that:
RowWidget widget = new RowWidget.Builder().withData(data).withParentData(parentData).withDataRawType(dataRawType).build();
Here is neat explanation of the pattern:https://stackoverflow.com/a/1953567/991164
Why not create method which will accept the newValues for the properties you want to change & return a new instance of the classes with all other properties copied from the instance on which you invoked this method.
You could separate/extract the parameters from the RowWidget-class fro example in a RowWidgetConfig-class.
class RowWidgetConfig {
// put here all your parameters that you need to initialize only once
// init using setters
}
Now create once instance of that class and pass it among the other parameters to RowWidget constructor.
Another alternative would be to have factory for creating RowWidget instances. The factory would also contain all the parameters you need for a row instance plus a factory method createNewRowWidget witch creates an instance base on the parameters contained in the factory.
class RowWidgetFactory {
// put here all your parameters that you need to initialize only once
// init using setters
public RowWidget createNewRowWidget() {
// create
return ...
}
}
How to construct class which have same property required in another instance?
To achive this you can have a super class with all the properties you want. So any class extending this super class will be have these properties. This way you don't need to use static keyword.
What is best way to construct class with having some default fix property for all instances?
For this one you can have an interface with some constant properties. This way any class implementing this interface will be having the fixed properties.
The static initWidget() thing just doesn't seem right for me. Though probably now you will only have one set of RowWidgets which share some properties, it is also reasonable to have 2 sets of RowWidgets, each set will have its own "shared" properties. Things will be much more fluent and you have much more choices in building more reasonable APIs if you refactor your code to make a more reasonable design
Assume now I introduce something like a RowGroup (which kind of represents the "shared" thing you mentioned)
(Honestly I don't quite get the meaning for your design, I am just making it up base on your code);
public class RowGroup {
public RowGroup(Form form,
HashMap<Long, ContractorPermissionEnum> formModePermissionMap,
GridMode gridMode,
boolean isApplied,
boolean isChildExist,
boolean isChildAttachment) { .... }
public void addRow(DataRawType dataRawType, Data data, Data parentData) {...}
}
When people use, it looks something like:
RowGroup rowGroup = new RowGroup(form, permissionMap, gridMode, isApplied, isChildExist, isChildAttach);
rowGroup.addRow(DataRawType.A, dataA, parentA);
rowGroup.addRow(DataRawType.B, dataB, parentB);
You may even provide builder-like syntax or a lot other choices.
RowGroup rowGroup
= new RowGroup(.....)
.addRow(DataRawType.A, dataA, parentA)
.addRow(DataRawType.B, dataB, parentB);
Even more important, the design now make more sense to me.
If you did not want to create another class, I'd suggest what A4L suggested.
Without creating another class, I would create constructor that takes all parameters and factory method that uses current instance as template and pass its own parameters to constructor parameter.
example (with obvious parts ommited)
class A{
public A(int p1, int p2){...}
public A create(int p2) {
return new A(this.p1,p2);
}
I am designing a complex Configuration class as part of an API design. The Configuration class roughly looks like this.. (I ignored generics/access modifiers etc)
class Configuration {
One obj1;
Two obj2;
}
class One {
List<Double> values;
}
class Two {
double value;
Map<String, Double> data;
}
This is what I want to accomplish:
I want users to be able to create this Configuration class the first time easily and submit to server.
Then they can change any part of this class and send the updated configuration to the server.
What design patterns to use and avoid?
Is it better to make this class Immutable and use builder pattern?
Or just provide all kinds of modification methods On Configuration class so they can modify the same Configuration class (at all levels) in-place without having to create a new Configuration class for every update. I think Builder pattern is good for Immutable classes only.
Questions:
Is there any way to exploit Builder pattern for this type of scenarios?
Or is it better to provide mutator methods on Configuration class like I mentioned above?
Or are there any other better patterns available?
I think you should use prototype pattern:
in your code you can add map that hold all types of configurations
the map will have a key called "currentConfiguration" and the value will be the configuration that should be loaded. the map can also contains other configurations that can be stored in the map and can replace the current configuration if needed.
once you fetch configuration from the map you simply clone the configuration object and the user can do what ever he pleased with that. after the changes he can save the configuration in the map with speicifc name. so the user can get configuration object that is quite close that what he needs and configure it accordingly.
the code should look like this:`public class CloudRepository {
private Map<String, Configuration> rep;
public CloudRepository(Configuration current){
rep = new HashMap<String, Configuration>();
rep.put("current", current);
}
public Configuration getConfiguration(String string){
return (Configuration) rep.get(string).clone();
}
public void addConfiguration(String name, Configuration conf){
rep.put(name, conf);
}
public void replaceCurrentConfiguration(Configuration conf){
rep.put("current", conf);
}
}
you can also write more code to handle history for your configurations.
you can also consider making this class singleton
I've created a class which holds a bunch of properties values.
In order to initialize that class, I have to call some static method "configure()" which configures it from an XML file.
That class was supposed to act to store some data such that I could just write
PropClass.GetMyProperty();
I call the configure() from a static block in the main so I can use it anywhere
BUT
If I set a static constant member of some other class to a value from my "PropClass", I get null,
class SomeClass {
static int myProp = PropClass.GetMyProperty();
}
That's probably because that expression is evaluated before the call to configure.
How can I solve this issue?
How can I enforce that the call to configure() will be executed first?
Thanks
you could use a static code block to do that
static {
configure();
}
the syntax of a static initializer block? All that is left is the keyword static and a pair of matching curly braces containing the code that is to be executed when the class is loaded. taken from here
I would do the following:
class SomeClass
{
// assumes myProp is assigned once, otherwise don't make it final
private final static int myProp;
static
{
// this is better if you ever need to deal with exceeption handling,
// you cannot put try/catch around a field declaration
myProp = PropClass.GetMyProperty();
}
}
then in PropClass do the same thing:
class PropClass
{
// again final if the field is assigned only once.
private static final int prop;
// this is the code that was inside configure.
static
{
myProp = 42;
}
public static int getMyProperty();
}
Also. if possible, don't make everything static - at the very least use a singleton.
Can you not make the GetMyProperty() method check whether configure() has been called already ? That way you can call GetMyProperty() without having to worry about wheher our object is configured. Your object will look after this for you.
e.g.
public String getMyProperty() {
if (!configured) {
configure();
}
// normal GetMyProperty() behaviour follows
}
(you should synchronise the above if you want to be thread-safe)
Dude, sounds like you should be using Spring Framework (or some other Dependency Injection framework). In Spring, you already get everything that you need:
An XML format for defining beans with configurable properties, no need to code the logic for reading the XML and initializing the beans yourself.
Beans are initialized when you need them (provided that you access them in the correct manner). The best way would be to inject the beans into the callers.
Don't invent the wheel... Spring is one of the most commonly used frameworks in Java. IMHO, no large Java application should be coded without it.