Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use a concept similar to keyword args for python in Java to minimize the number of accessor methods?

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?

like image 747
Jain Avatar asked Apr 28 '15 00:04

Jain


2 Answers

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() };
        }

    }
like image 122
Haitham Adnan Mubarak Avatar answered Nov 10 '22 00:11

Haitham Adnan Mubarak


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.

like image 21
LMD Avatar answered Nov 10 '22 01:11

LMD