calling java method one after each other with "dots" in between - java

I see the following code syntax. Calling
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("x11")
.setOAuthConsumerSecret("x33")
.setOAuthAccessToken("x55")
.setOAuthAccessTokenSecret("x66");
All the methods after each other without using the object instance.
How does this work in programming my own class when i want to use this kind of calling methods?

make each of those methods return the same object which they are called on:
class MyClass{
public MyClass f(){
//do stuff
return this;
}
}
It's a pretty common pattern. Have you ever seen this in C++?
int number=654;
cout<<"this string and a number: "<<number<<endl;
each call of the operator << returns the same ostream that is passed as its argument, so in this case cout, and since this operation is done left to right, it correctly prints the number after the string.

That style of writing code is called 'fluent' and it is equivalent to this:
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("x11");
cb.setOAuthConsumerSecret("x33");
cb.setOAuthAccessToken("x55");
cb.setOAuthAccessTokenSecret("x66");
Each method returns 'this' in order to accommodate this style.
If you use this style, be prepared to encounter some inconvenience while debugging your code, because if you want to single-step into only one of those methods instead of each and every single one of them, the debugger might not necessarily give you the option to do that.

This is simmilar to a Builder design pattern.
Here you can find a excellent example of it inspired by Josh Bloch's code from Effective Java 2nd ed.

Related

How to inspect the value of a Runnable?

Suppose I have code that assigns a method to a Runnable, for example:
class C1{
Runnable r;
}
class C2{
void f(){}
}
var c1 = new C1();
var c2 = new C2();
c1.r = c2::f;
I want to write a unit test to assert that r is indeed assigned f, perhaps like this:
assertThat(c1.r).isEqualTo(c2::f); // Error: object is not a functional interface
Casting to Runnable does not help:
expected: ...$$Lambda$302/0x0000000800cd3518#1fe20588
but was : ...$$Lambda$301/0x0000000800c9fac0#77167fb7
In C# I can assign a method to an Action variable this assertion works. What's the equivalent in Java?
I am open to switching from Runnable to some other type, if that helps.
To give some more context: I'm trying to implement event-based decopuling like Arlo Belshee describes here: https://arlobelshee.com/decoupled-design/. Here's my C# implementation for comparison: https://jay.bazuzi.com/Decoupled-Design/
You're out of luck trying to compare lambdas in any sane way. The code may work in C# and other languages, but it's not worth trying to shoehorn it into Java.
I don't know the purpose of this exercise (as in is it just to test the viability of this in Java or if this is a pattern you regularly use), but generally translating from one language to another doesn't make sense unless there's an obvious compatibility. C# may look like Java (for some weird reason, hello J#), but there's a world of difference making many things completely distinct (e.g. async/await, only superficial similarity between LINQ and Java streams, methods not being truly first class objects in Java, and most likely many more as my C# knowledge is very limited).
IMHO the testing in the example was the weirdest part. It gives a low ROI to test microimplementation like that. I'm not sure if that is useful in GUI testing, but just as if you had a solution that involved metaprogramming, you couldn't just implement it in Java.
The thing is that you create a new method reference each time with ::.
Thus
var c1 = new C1();
var c2 = new C2();
Runnable r = c2::F;
c1.R = r;
System.out.println(c1.R == r);
will print true, because you assign and compare with the same runnable.

How to Test Void Method With No Arguments That Prints Line to Console

For a homework assignment, I have created a Class called Bird, that contains a method:
public void launch()
{
System.out.println("Flapping the wings until take-off");
}
I need to run jUnit tests on all contained methods, including ones like these. However, when I use:
#Test
void testLaunch()
{
Bird myBird = new Bird("Macaw");
assertEquals("Flapping the wings to take-off", myBird.launch());
}
I'm given this error in Eclipse: "The method assertEquals(short, short) in the type Assertions is not applicable for the arguments (String, void)"
I'm becoming frustrated because our teacher has not taught us how to test these kinds of methods, and he never answers my emails for assistance. Even if this is considered an overall weak question, any help would be greatly appreciated.
You can use System.setOut(PrintStream) to temporarily replace standard out with an in memory PrintStream backed by a ByteArrayOutputStream and use that to get the output. Something like,
#Test
void testLaunch() {
PrintStream original = System.out;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream tps = new PrintStream(baos);
Bird myBird = new Bird("Macaw");
System.setOut(tps);
myBird.launch();
System.setOut(original);
tps.flush();
assertEquals("Flapping the wings to take-off", baos.toString());
}
Usually you only test methods that have some kind of logic in them. Calling System.out.println is not considered logic.
From a a test driven point of view it's easier to work with methods that are side-effect-free, as in they take some parameters and return a result, your method is quite the opposite and thus very hard to test.
The only viable approach in your case (beside stating that your method isn't complicated egnough to be tested) is to split your method into one that creates the String (that method can be tested) and one that calls the other method and prints the result (calling anouther method (in another class called a service) is testable with a variety of frameworks (Mockito for example). Calling System.out.println is very hard to test, you could extract a Supplier for the Stream (System.out) and verify it returns indeed System.out and again verify that println is called on the supplied Stream.
Looking at this test structure points out the fact, that the base method is not only relying on side effects but it's also doing three things at once (whereas ideal methods do only one thing). it creates an Object (here a String), it acquires and OutStream (here System.out) and it uses both together (println).
Yes, this might seem overly complicated but from a learning point of view it shows that even hidden in something as simple as this, there is a lot of complexity and if done right can teach a lot about object oriented design and clean and S.O.L.I.D. code

Call void on possible null object, in one line

I use Java8 in my project but i cannot solve this issue with a nice implementation.
UIInput textInput = ...;
if (textInput != null)
{
textInput.setValid(false);
}
Is there a solution to check if the object is null, and if not, then call the function on it, in one line ?!
Don't.
What you have is easily readable for anyone with some Java knowledge. Any one-liner misusing a construct intended for something else will take most people way more time to read and understand than this will. And likely some people will misread it and have to read it again later when it does not behave like they expect during a debugging session.
Brevity / Number of lines of code is not an ultimate measure for readability or quality.
What you can do, if this is at the wrong level of detail compared with the rest of your method, is abstract it away with a single speaking method call. Say, create a method 'ensureTextInputIsSet' that just contains this code and returns the potentially modified object.
Optional.ofNullable(textInput).ifPresent(x -> x.setValid(false));
But this is not what Optional was designed for...
If a variable may be null, an object is optional, then:
Optional<UIInput> textInput = ...;
With a circumstantial, but always safe usage:
textInput.ifPresent(ti -> ti.setValid(false));
And nice chaining, for instance for Optional<UIInput> to Optional<String> calling a method on the UIInput.
String s = textInput.map(UIInput::getText).orElse("");

Regarding two lines of java code

I am trying to learn a java-based program, but I am pretty new to java. I am quite confusing on the following two lines of java code. I think my confusion comes from the concepts including “class” and “cast”, but just do not know how to analyze.
For this one
XValidatingObjectCorpus<Classified<CharSequence>> corpus
= new XValidatingObjectCorpus<Classified<CharSequence>>(numFolds);
What is <Classified<CharSequence>> used for in terms of Java programming? How to understand its relationships with XValidatingObjectCorpusand corpus
For the second one
LogisticRegressionClassifier<CharSequence> classifier
= LogisticRegressionClassifier.<CharSequence>train(para1, para2, para3)
How to understand the right side of LogisticRegressionClassifier.<CharSequence>train? What is the difference between LogisticRegressionClassifier.<CharSequence>train and LogisticRegressionClassifier<CharSequence> classifier
?
These are called generics. They tell Java to make an instance of the outer class - either XValidatingObjectCorpus or LogisticRegressionClassifier - using the type of the inner object.
Normally, these are used for lists and arrays, such as ArrayList or HashMap.
What is the relationship between XValidatingObjectCorpus and corpus?
corpus is just a name given to the new XValidatingObjectCorpus object that you make with that statement (hence the = new... part).
What does LogisticRegressionClassifier.<CharSequence>train mean?
I have no idea, really. I suggest looking at the API for that (I think this is the right class).
What is the difference between LogisticRegressionClassifier.<CharSequence>train and LogisticRegressionClassifier<CharSequence> classifier?
You can't really compare these two. The one on the left of the = is the object identifier, and the one on the right is the allocator (probably the wrong word, but it is what it does, kind of).
Together, the two define an instance of LogisticRegressionClassifier, saying to create that type of object, call it classifier, and then give it the value returned by the train() method. Again, look at the API to understand it more.
By the way, these look like wretched examples to be learning Java with. Start with something simple, or at least an easier part of the code. It looks like someone had way too much fun with long names (the API has even longer names). Seriously though, I only just got to fully understanding this, and Java was my main language for quite a while (It gets really confusing when you try and do simple things). Anyways, good luck!
public class Sample<T> { // T implies Generic implementation, T can be substituted with any object.
static <T> Sample<T> train(int par1, int par2, int par3){
return new Sample<T>(); // you are calling the Generic method to return Sample object which works with a particular type of generic object, may it be an Integer or a CharSequence. --> see the main method.
}
public static void main(String ... a)
{
int par1 = 0, par2 = 0, par3 = 1;
// Here you are returning Sample object which works with a sequence of characters.
Sample<CharSequence> sample = Sample.<CharSequence>train(par1, par2, par3);
// Here you are returning Sample object which works with Integer values.
Sample<CharSequence> sample1 = Sample.<Integer>train(par1, par2, par3);
}
}
<Classified<CharSequence>> is a generic parameter.
LogisticRegressionClassifier<CharSequence> is a generic type.
LogisticRegresstionClassifier.<CharSequence>train is a generic method.
Java Generics Tutorial

Tree Transformations Using Visitor Pattern

(Disclaimer: these examples are given in the context of building a compiler, but this question is all about the Visitor pattern and does not require any knowledge of compiler theory.) I'm going through Andrew Appel's Modern Compiler Implementation in Java to try to teach myself compiler theory (so no, this isn't homework) and I'm having trouble understanding how he wants to use the Visitor pattern to transform an AST to an IR tree. (Note: I'm doing this in Python so I can learn Python also, which is why the upcoming examples are not in Java.) As I understand it, the visit and accept methods in the Visitor pattern are void-typed by design, so if I have something like
class PlusExp(Exp):
def __init__(self, exp_left, exp_right):
self.exp_left = exp_left
self.exp_right = exp_right
def accept(self, v):
v.visit_plus_exp(self)
then I would like to be able to write a visitor method like
def visit_plus_exp(self, plus_exp):
return BINOP(BinOp.PLUS,
plus_exp.exp_left.accept(self),
plus_exp.exp_right.accept(self))
which would translate the two child expressions into IR and then link them up with the BINOP representing the plus expression. Of course, this isn't possible unless I modify all the accept functions to return extra info, and that is also messy because sometimes you just want a print visitor that doesn't return anything. Yet, this text insists that a visitor is the right way to go, and in Java at that, which means it can be done without the flexibility of Python. I can't think of any solutions that aren't incredibly hacky - can anyone enlighten me as to the intended design?
A SAX parser is a kind of visitor. To avoid adding a return value to the method, you can use a stack:
class Visitor {
Stack<Node> stack = new Stack<Node>();
// . . .
void visitPlus(PlusExp pe) {
pe.left.accept(this);
pe.right.accept(this);
Node b = stack.pop();
Node a = stack.pop();
stack.push(new BinOp(BinOp.PLUS, a, b));
}
Look at source code of THIS compiler. I think that the guy has used Visitor pattern.
Caveat: I haven't read that book.
The method may be void-typed, but in Java (which the book was written for) it is also part of an object. So, the visitor method can build up the structure in a local member variable, thus maintaining the necessary context between calls.
So, for instance, your print visitor would be appending to a StringBuilder that is held as a member variable (or as a final local variable in a method that created the visitor object -- this is fairly common in Java, where creating small anonymous-inner-class objects is a common habit).
In python, you could similarly let the visitor method access a non-method-local variable to maintain context and build the structure. Eg, closure, or a small object.
Update -- small bit of code added as example from comment below
result = new Node();
result.left.add(n1.accept(this));
result.right.add(n2.accept(this));
return result;
or
result = new Node();
this.nextLoc.add(result);
this.nextLoc = result.left;
n1.accept(this);
this.nextLoc = result.right;
n2.accept(this);
The first is prettier (though still crappy comment example code), but the second would let you keep the void return type if you really needed to.

Categories