Best way to create an object from a delimited string (hopefully not looped)

this question seems to have been asked, but I didn’t find anything, so here ...

I have a constructor to which a string that is limited is passed. From this line, I need to populate the instance variables of the object. I can easily split the string into a separator to give me an array of strings. I know that I can just iterate over the array and set the instance variables using ifs or a switch / case statement based on the current index of the array - however this is just a little annoying. Pseudocode:

String[] tokens = <from generic string tokenizer>;

for (int i = 0;i < tokens.length;i++) {
   switch(i) {
      case(0): instanceVariableA = tokens[i];
      case(1): instanceVarliableB = tokens[i];
      ...
   }
}

Does anyone have any ideas on how I am doing this better / better?

For what it's worth, I work in Java, but I think it is an independent language.

+3
5

Uhm... "nasty" , . , , .

for, ...

instanceVariableA = tokens[0];
instanceVariableB = tokens[1];

( readibilty):

instanceVariableA = tokens[VARIABLE_A_INDEX];
instanceVariableB = tokens[VARIABLE_B_INDEX];

: , , , :

String inputString = "instanceVariableA=some_stuff|instanceVariableB=some other stuff";
String[] tokens = inputString.split("|");
for (String token : tokens)
{
    String[] elements = token.split("=");
    String propertyName = tokens[0];
    String propertyValue = tokens[1];
    invokeSetter(this, propertyName, propertyValue); // TODO write method
}
+4

" ", ?

0

, , Manrico .

HashMap , , - . . , (, PHP, ) .

0

, Python:

params = ["instanceVariableA", "instanceVariableB"]. :

self.__dict__.update(dict(zip(params, tokens)))

;

for k,v in zip(params, tokens):
    setAttr(self, k, v)

/ .

, / - .

( , zip , - .)

0
source

just an unverified idea

save original token ...

String[] tokens = <from generic string tokenizer>;

then create

int instanceVariableA = 0;
int instanceVariableB = 1;

if you need to use it just

tokens[instanceVariableA];

therefore, no more cycles, no more VARIABLE_A_INDEX...

maybe JSON can help?

0
source

Source: https://habr.com/ru/post/1705643/


All Articles