I recently learn that in Python 3, to minimize the number of accessor methods for a class, you can use a dictionaries to essentially just have one set of accessor methods as follows:
def __init__(self, **kwargs):
self.properties = kwargs
def get_properties(self):
return self.properties
def get_property(self, key):
return self.properties.get(key, None)
This seems really useful and I want to apply something similar in Java. I have been working on applications that may have multiple attributes, and creating and keeping track of all the accessor methods can be a pain. Is there a similar strategy that I could use for Java?
No there is no kwargs in java. Instead you can something similar to your function by using java varargs to save them as java properties.
You do you can something like this:
useKwargs("param1=value1","param2=value2");
Example code:
public void useKwargs(String... parameters) {
Properties properties = new Properties();
for (String param : parameters) {
String[] pair = parseKeyValue(param);
if (pair != null) {
properties.setProperty(pair[0], pair[1]);
}
}
doSomething(properties);
}
public void doSomething(Properties properties) {
/**
* Do something using using parameters specified in the properties
*/
}
private static String[] parseKeyValue(String token) {
if (token == null || token.equals("")) {
return null;
}
token = token.trim();
int index = token.indexOf("=");
if (index == -1) {
return new String[] { token.trim(), "" };
} else {
return new String[] { token.substring(0, index).trim(),
token.substring(index + 1).trim() };
}
}
Im not sure if this is helpful to you, but Ill try to answer anyway. I'd first make a class Variable. Then I'd make a class Dictionary with one lists:Variables. Then I'd make the function take a Dictionary as argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With