Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java design pattern to keep a method name in a property file

I have property file(key/value) pair from where I currently read a value against a key and display that value as it is in the UI .

The complexity have increased,Now the value is more dynamic based on some formula. The formula includes a variable parameter whose value I will get at run time.

Is there any java design pattern to design this scenario .

I was thinking to put a method name in the property file against a key.

Now I will read the key and fetch the method name . This method will calculate the value for that particular key.

Please let me know your suggestion

like image 528
Programmer Avatar asked Oct 18 '22 21:10

Programmer


2 Answers

Is there any java design pattern to design this scenario .

I don't know if there is a pattern.


If I understand your question right I can explain what I do usually.

  • Insert localizable strings in my properties values
    I usually use #number#
  • Replace it later when variables are resolved

Little example:

messages.properties

name.of.key = sum of #0# + #1# = #2#

Then I read the value from and replace the #num# with appropiated values (NOTE: here is in the same method for shortenes, but I use an external replace method):

public void printSum(int n1, int n2) {
    String myString = messageSource("name.of.key", Locale.getDefault(), null, null));
    myString.replace("#0#", String.valueOf(n1));
    myString.replace("#1#", String.valueOf(n2));
    myString.replace("#2#", String.valueOf(n1+n2));
    System.out.println(myString);
}

OUTPUT printSum(1,2);

sum of 1 + 2 = 3
like image 97
Jordi Castilla Avatar answered Oct 21 '22 16:10

Jordi Castilla


Looks like the ANTLR would make here a great fit.

It is a parser generator. You give it grammar as an input and in return it provides you with a parser.

You can use the parser to transform the textual formula into a parsed tree representation. After that, you can run a visitor to evaluate each of the nodes. You just write some simple function to implement the behavior, such as:

public Double visitAdd(AntlrNode left, AntlrNode right) {
    Double left = visit(left);
    Double right = viist(right);

    return left + right;
}

The grammar is very close to the familiar BNF notation. You just describe how your formula strings are. For example:

formula : left '+' right;
left: Number;
right: Number;
Number: [0-9]+;
like image 32
Rekin Avatar answered Oct 21 '22 15:10

Rekin