I have a design question: let me expalin in simple example:
Public class A()
{
public static HashMap map = new HashMap();
public static String url = "default";
static {
getJson();
}
//url getters and setters are defined
public static getJson() {
//code which uses url to get json and populate hashmap
}
public string getresult(String key) {
//uses hashmap to send result.
}
I am using static initialization block because i want to get json only once.
public class B {
//here I want to change url and call getJson method. If i call A.setUrl() then before setting url, A.getJson () method is called as it is in static initialization block.how can i set url first and then call getJson().
//is this a bad design?
}
Yes, it is bad design:
If you must access
Athrough a static field, I’d recommend:This separates the concern of using the data from the concern of obtaining it, allowing each to be replaced and tested independently.
Also consider getting rid of
static, as it enforces there is only ever one map in your entire application at the same time, which is quite inflexible. (See the second code sample in Ajay’s answer for how)