Let us say that I have a class in Kotlin like below
Also, let us define an infix function generateEmailWithDomain which generates the email address based on the name with the given domain
class Person(var name: String) {}
infix fun Person.generateEmailWithDomain(domain: String): String = "${this.name}#$domain.com"
Now, as it is said that Kotlin is 100% interoperable with Java, how can I make use of this infix function in a JAVA class?
The above usage of infix may be inappropriate but I would like to know how this can be used in Java.
Please correct my understanding if it is wrong.
Based on the docs (https://kotlinlang.org/docs/reference/functions.html#infix-notation), infix seems to be mere syntactic sugar to me, as even the example there shows two ways of calling such function:
class MyStringCollection {
infix fun add(s: String) { /*...*/ }
fun build() {
this add "abc" // Correct
add("abc") // Correct
//add "abc" // Incorrect: the receiver must be specified
}
}
So, from Java I would simply use the second one, tailored to your case that would be
String result = somePerson.generateEmailWithDomain(someString);
(as defining an extension function "outside" as Person.generateEmailWithDomain() is also just an optional possibility, when calling that will be a method of an actual Person object)
Ok, I was too optimistic. Based on https://stackoverflow.com/a/28364983/7916438, I would expect you to face a static method then, with two arguments, the first being the receiver, and the second one is the actual argument.
String result = Person.generateEmailWithDomain(somePerson, someString);
Related
Sorry, it seems to be very basic in functional programming but I am not getting this idea. Actually I have a method in my code which consumes a method and another param as a parameter.
private <R> CompletableFuture<R> retryRequest(Supplier<CompletableFuture<R>> supplier, int maxRetries)
I want to call this function and pass another method(anOtherMethod) which taking one integer parameter:
CompletableFuture<Boolean> retry = this.retryRequest(this:: anOtherMethod, 2);
Not getting this how I can call this retryRequest and give anOtherMethod(123)?
I know it can work like this:
CompletableFuture<Boolean> retry = this.retryRequest(()-> anOtherMethod(123), 2);
You cannot instantiate a lambda with a specific captured value like 123 in the pure method reference variant.. You need to write the explicit lambda version with arrow, if you want to pass captured values other than the instance to execute the method on. Read more on capturing values in lambdas in this answer: Enhanced 'for' loop and lambda expressions
The only exception is an object, which itself becomes the first parameter.
Assume a signature that expects a Consumer of a String:
public void something(Consumer<String> job) {
...
The above signature will enable you to write the following calls:
String myString = " Hey Jack ";
something(myString::trim);
something(s -> s.trim());
Both do the same, and this is maybe unintuitive, because one takes an argument (the instance reference myString) and one seem not to (but it actually does, too). This works, because the compiler tries two possible resolutions for a lambda method reference (the above version with ::). On one hand, the compiler can apply signatures, as if the called method did not have any parameters, and none need passing. This is the case for myString.trim. But the compiler will also check, whether there is a static method String.trim(myString) (which luckiely there is not). If you wanted to call a static method without any parameters, then you'd have to call the class identifier with the function reference like so:
something(String::trim); // this version of trim does not exist.
This is sometimes even a problem, because if a class offers a static version of a method and an instance-related one, you get ambiguity:
public void somethingElse(Function<Integer, String> transformation) {...}
// This will not compile:
somethingElse(Integer::toString);
The above example will not compile, because the toString method exists twice, once as static Integer.toString(someInt) and once as instance related someInteger.toString().
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
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
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]+;
Use Java built-in JavaScript engine to evaluate expressions. To match the spirit more closely, you can use JSON for properties.
If security is important, you need to provide the class filter. It can be very simple and restrictive as you only need to evaluate trivial expressions. The example on class filter can be found here.
You can use the strategy pattern putting the method/algorithm name in the property file:
public interface IFormula{
public int formula(int a, int b);
}
public class Sum implements IFormula{
public int formula(int a, int b){
return a+b;
}
}
Then you can select the method getting the name from a property file:
public static Strategy getStrategy(Name name) {
switch (name) {
case SUM:
return new Sum();
...
}
}
Another solution is to refactor your map so that the value type is a functional interface whose method accepts an arbitrary parameter. For example:
#FunctionalInterface
interface ValueType<R> {
R eval(Object param);
}
This solution (or a variant of it) would enable you to associate a lambda with your keys rather than a fixed value. The performance of a lambda ought to be much better than a run-time parser while still affording you the flexibility to make the associated value depend upon a run-time argument.
This solution should also be less vulnerable to injection attacks than a solution based on run-time parsing.
Since you seem to want a name for the pattern... the pattern is called: Domain Specific Language.
And again if you want to remain in the realms of abstract patterns and design you can peruse Martin Fowlers discussion on the topic at length.
Needless to say their are a metric ton of tools that solve the above pattern (including some of the answers here).
The other pattern which I highly recommend you NOT do is use a general purpose language that has an evaluator (ie Javascript, EL, Groovy, etc). This generally has security issues and performance issues (of course there are exceptions).
I vaguely remember from my days of Minecraft modding that in java, you can set multiple class variables in one line, like this:
SomeBlock.hardness(0.5).isOpaque(True).blastResistance(2).etc.etc
Well I was wondering if there was a way to do something similar in python. I have tried doing the same thing in python, but the second one ends up thinking it is supposed to modify the return of the first one instead of the original class.
Is there a way to do this?
Yes, you can, in fact it is done the same way it is done in Java: by returning the self reference.
class SomeBlock(object):
def hardness(self, blah):
self.hardness = blah
return self
def isOpaque(self, value):
self.isOpaque = value
return self
a = SomeBlock()
a.hardness(0.5).isOpaque(true)
This is just a fluent interface, which is desgined to be like that. It is mostly created by returning the same object:
class Test:
def setX(self, x):
self.x = x
return self
def setY(self, x):
self.y = y
return self
t = Test()
t.setX(12).setY(11)
the second one ends up thinking it is supposed to modify the return of the first one instead of the original class. Yes that is the normal Python syntax. Returning self does not create a special syntax. It just ensures the returned object is the correct one for chaining.
Your initialization task is more commonly coded as
class SomeBlock():
def __init__(self, hardness=None, opaque=False, blastResistance=None):
self.hardness = hardness
self.opaque = opaque
self.blastResistance = blastResistance
ablock = SomeBlock(hardness=0.5, opaque=True, blastResistance=2)
And because Python does not require methods for accessing attributes, you can also write
ablock = SomeBlock()
ablock.hardness = 0.5
...
So if a method does return self, it's usually to implement a more complex that setting attributes.
It's more common to have method return a new object of the same class. This is typical, for example, of many of the numpy array methods. A.dot(B) returns new array, the result of taking the dot product of A and B. A.dot(B).dot(C) may look like chaining, but is just a sequence of actions on successive arrays.
This question isn't specifically about performing tokenization with regular expressions, but more so about how an appropriate type of object (or appropriate constructor of an object) can be matched to handle the tokens output from a tokenizer.
To explain a bit more, my objective is to parse a text file containing lines of tokens into appropriate objects that describe the data. My parser is in fact already complete, but at present is a mess of switch...case statements and the focus of my question is how I can refactor this using a nice OO approach.
First, here's an example to illustrate what I'm doing overall. Imagine a text file that contains many entries like the following two:
cat 50 100 "abc"
dog 40 "foo" "bar" 90
When parsing those two particular lines of the file, I need to create instances of classes Cat and Dog respectively. In reality there are quite a large number of different object types being described, and sometimes different variations of numbers of arguments, with defaults often being assumed if the values aren't there to explicity state them (which means it's usually appropriate to use the builder pattern when creating the objects, or some classes have several constructors).
The initial tokenization of each line is being done using a Tokenizer class I created that uses groups of regular expressions that match each type of possible token (integer, string, and a few other special token types relevant to this application) along with Pattern and Matcher. The end result from this tokenizer class is that, for each line it parses, it provides back a list of Token objects, where each Token has a .type property (specifying integer, string, etc.) along with primitive value properties.
For each line parsed, I have to:
switch...case on the object type (first token);
switch on the number of arguments and choose an appropriate constructor
for that number of arguments;
Check that each token type is appropriate for the types of arguments needed to construct the object;
Log an error if the quantity or combination of argument types aren't appropriate for the type of object being called for.
The parser I have at the moment has a lot of switch/case or if/else all over the place to handle this and although it works, with a fairly large number of object types it's getting a bit unwieldy.
Can someone suggest an alternative, cleaner and more 'OO' way of pattern matching a list of tokens to an appropriate method call?
The answer was in the question; you want a Strategy, basically a Map where the key would be, e.g., "cat" and the value an instance of:
final class CatCreator implements Creator {
final Argument<Integer> length = intArgument("length");
final Argument<Integer> width = intArgument("width");
final Argument<String> name = stringArgument("length");
public List<Argument<?>> arguments() {
return asList(length, width, name);
}
public Cat create(Map<Argument<?>, String> arguments) {
return new Cat(length.get(arguments), width.get(arguments), name.get(arguments));
}
}
Supporting code that you would reuse between your various object types:
abstract class Argument<T> {
abstract T get(Map<Argument<?>, String> arguments);
private Argument() {
}
static Argument<Integer> intArgument(String name) {
return new Argument<Integer>() {
Integer get(Map<Argument<?>, String> arguments) {
return Integer.parseInt(arguments.get(this));
}
});
}
static Argument<String> stringArgument(String name) {
return new Argument<String>() {
String get(Map<Argument<?>, String> arguments) {
return arguments.get(this);
}
});
}
}
I'm sure someone will post a version that needs less code but uses reflection. Choose either but do bear in mind the extra possibilities for programming mistakes making it past compilation with reflection.
I have done something similar, where I have decoupled my parser from code emitter, which I consider anything else but the parsing itself. What I did, is introduce an interface which the parser uses to invoke methods on whenever it believes it has found a statement or a similar program element. In your case these may well be individual lines you have shown in the example in your question. So whenever you have a line parsed you invoke a method on the interface, an implementation of which will take care of the rest. That way you isolate the program generation from parsing, and both can do well on their own (well, at least the parser, as the program generation will implement an interface the parser will use). Some code to illustrate my line of thinking:
interface CodeGenerator
{
void onParseCat(int a, int b, String c); ///As per your line starting with "cat..."
void onParseDog(int a, String b, String c, int d); /// In same manner
}
class Parser
{
final CodeGenerator cg;
Parser(CodeGenerator cg)
{
this.cg = cg;
}
void parseCat() /// When you already know that the sequence of tokens matches a "cat" line
{
/// ...
cg.onParseCat(/* variable values you have obtained during parsing/tokenizing */);
}
}
This gives you several advantages, one of which being that you do not need a complicated switch logic as you have determined type of statement/expression/element already and invoke the correct method. You can even use something like onParse in CodeGenerator interface, relying on Java method overriding if you want to always use same method. Remember also that you can query methods at runtime with Java, which can aid you further in removing switch logic.
getClass().getMethod("onParse", Integer.class, Integer.class, String.class).invoke(this, catStmt, a, b, c);
Just make note that the above uses Integer class instead of the primitive type int, and that your methods must override based on parameter type and count - if you have two distinct statements using same parameter sequence, the above may fail because there will be at least two methods with the same signature. This is of course a limitation of method overriding in Java (and many other languages).
In any case, you have several methods to achieve what you want. The key to avoid switch is to implement some form of virtual method call, rely on built-in virtual method call facility, or invoke particular methods for particular program element types using static binding.
Of course, you will need at least one switch statement where you determine which method to actually call based on what string your line starts with. It's either that or introducing a Map<String,Method> which gives you a runtime switch facility, where the map will map a string to a proper method you can call invoke (part of Java) on. I prefer to keep switch where there is not substantial amount of cases, and reserve Java Maps for more complicated run-time scenarios.
But since you talk about "fairly large amount of object types", may I suggest you introduce a runtime map and use the Map class indeed. It depends on how complicated your language is, and whether the string that starts your line is a keyword, or a string in a far larger set.
Is there any such equivalent of Java
String myMethod (MyClass argument) {...}
in Python?
Thank you, Tomas
No. (And more stuff to round this up to 15 characters...)
No, there is not.
In fact, checking types is considered "un-Pythonic", because an object of any type that looks enough like the expected type should be treated equally.
Python 3.x has function annotations where you can declare argument and return types:
def myMethod(argument: MyClass) -> str:
...
But currently Python does nothing with them, they serve as documentation only.
I just want to say that I'm in full agreement that type checking is evil. But python is also incredibly flexible and I'm in the mood to be evil. This code will take effect at runtime and not compile time. You could do something similar for return type. Something like this could be useful for debugging and, because it's a decorator, it's easy enough to remove.
For it to be useful for debugging you would have to have a situation where two types had all the same attributes that were getting accessed but with different semantics. So that's a pretty limited case. Other than that, you're about to get a typerror anyways when this code runs. The good news is that this is almost never a problem. I really don't know why people from statically typed languages make such a big deal over it.
def types(*args, **kwargs):
arg_types = args
kwarg_types = kwargs
def decorator(f):
def func(*args, **kwargs):
for arg, arg_type in zip(args, arg_types):
if not isinstance(arg, arg_type):
raise TypeError("Wrong type suckah")
for kw, arg in kwargs.items():
if not isinstance(arg, kwarg_types[kw]):
raise TypeError("this is a bad error message")
return f(*args, **kwargs)
return func
return decorator
#types(int, str, bool, flag=bool)
def demo(i, strng, flag=False):
print i, strng, flag
demo(1, "foo", True)
try:
demo("foo", "bar", flag="foobar")
except TypeError:
print "busted on posargs"
try:
demo(1, "foo", flag=2)
except TypeError:
print "busted on keyargs"
try:
demo(1, "foo", 3)
except TypeError:
print "no use sneaking it through"
No.
In Python, it's the program's
responsibility to use built-in
functions like isinstance() and
issubclass() to test variable types
and correct usage. Python tries to
stay out of your way while giving you
all you need to implement strong type
checking.
from Why is Python a dynamic language and also a strongly typed language. Also
In a dynamically typed language, a
variable is simply a value bound to a
name; the value has a type -- like
"integer" or "string" or "list" -- but
the variable itself doesn't. You could
have a variable which, right now,
holds a number, and later assign a
string to it if you need it to change.
Further, isinstance() and issubclass() can be used to do type-checking. If you want to make sure that argument is of MyClass type, you can have a check inside the function. You can even type-cast the value of the argument (if you have a constructor accepting such value) and assign it to my_object.