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

I recently learned that in Python 3, in order to minimize the number of accessor methods of a class, you can use the dictionary. Basically, there is only one set of accessor methods, as shown below:

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 very useful. I want to apply something similar in Java I've been working on applications that may have multiple properties, and creating and tracking all accessor methods can be painful Is there a similar strategy I can use for Java?

Solution

If it fits and is best suited to use this pattern, but it should really be an exception to Java rules - it may not fit

The best practice in Java is to use getter and setter methods for each variable Yes, it's more code - so - if you're lazy, let your ide generate them automatically There are good reasons for this Many good reasons Some are;

>Promote private variables > define external interfaces for other classes, allowing classes to control the contents and methods of setting or obtaining variables > promote good coding practices by establishing standard methods for dealing with object variables

By porting this mode, the problem you will encounter is typing Python is dynamically typed and Java is statically typed Therefore, in order to use the same pattern in Java, you must store values in contents similar to string / object arrays, and then return them as objects or strings Then you must convert them later Maybe if your 'attributes' are strings, it doesn't matter There are exceptions to this rule, but you need to know all the rules to break them If they are of different types (string, int, customobject, etc.), do not use the same pattern used in Python

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>