Translate complex conditional logic inside a loop into streams and lambdas - loops

I'm looking for a clean way to translate complex logical conditions with if and else statements that lead to different actions, into lambdas and streams.
Suppose I have this code:
List<OuterData> result = new LinkedList<>();
for (Outer outer : getOutersFromSomewhere()) {
OuterData outerData = new OuterData();
if (outer.isImportant()) {
doImportantAction(outer, outerData);
} else if (outer.isTrivial()) {
doTrivialAction(outer, outerData);
} else {
doDefaultAction(outer, outerData);
}
for (Inner inner : outer.getInners()) {
if (inner.mustBeIncluded()) {
InnerData innerData = new InnerData();
if (inner.meetsCondition1()) {
doAction1(inner, innerData, outer, outerData);
} else if (inner.meetsCondition2()) {
doAction2(inner, innerData, outer, outerData);
} else {
doDefaultAction(inner, innerData, outer, outerData);
}
outerData.add(innerData);
}
}
result.add(outerData);
}
return result;
This is simplified from real code I have. I know it can be optimized and refactored, i.e. I could move inner for to a private method. I'd like to know how to translate the if, else if and else parts to streams and lambdas.
I know how to translate the skeleton of this example. I'd use List.stream(), Stream.map(), Stream.filter(), Stream.collect() and Stream.peek(). My problem is with conditional branches only. How can I do this translation?

One first obvious way is to stream your elements, filter them according to the needed criteria, and then applying the action on each remaining element. This also makes the code much cleaner:
List<Outer> outers = getOutersFromSomewhere();
outers.stream().filter(Outer::isImportant)
.forEach(outer -> doImportantAction(outer, outerDate));
outers.stream().filter(Outer::isTrivial)
.forEach(outer -> doTrivialAction(outer, outerDate));
// default action analog
Caution: This only works if the important, the trivial, and the default elements form a partition. Otherwise it is not equivalent to your if-else-structure. But maybe this is intended anyway ...
The main problem with this approach: It is not very good OOP. You are querying the objects in order to make a decision. But OOP should be "tell, don't ask" as much as possible.
So another solution is to provide a consuming method in your Outer class:
public class Outer {
...
public void act(OuterData data, Consumer<Outer> importantAction,
Consumer<Outer> trivialAction, Consumer<Outer> defaultAction) {
if (isImportant())
importantAction.accept(this, data);
else if (isTrivial())
trivialAction.accept(this, data);
else
defaultAction.accept(this, data);
}
}
Now you call it as simple as this:
List<Outer> outers = getOutersFromSomewhere();
outers.forEach(outer -> outer.act(...)); // place consumers here (lambdas)
This has a clear advantage: If you ever have to add a feature to your Outer class - let's say isComplex() - you have to only change the internals of that single class (and maybe resolve the compiler failure in other parts). Or maye you can add this feature in a backward compatible way.
The same rules can be applied to the Inner class and the iteration.

Related

I am trying to automate dropdown list in selenium web driver using Page object model. Below is my code explanation:

// Language Selection
public static void SelectLanguage() {
waitForElementToBeClickable(driver.findElement(By.xpath("//div[#class=\"lang-identifier\"]")));
driver.findElement(By.xpath("//div[#class=\"lang-identifier\"]")).click();
List<WebElement> elements = driver.findElements(By.xpath("//ul[#class=\"dropdown-menu pull-right\"]/li"));
for (WebElement e : elements) {
String text = e.getAttribute("value");
System.out.println(e.getText());
if (text.equalsIgnoreCase("English")) {
e.click();
break;
} else if (e.getText().equalsIgnoreCase("Español")) {
e.click();
break;
} else if (e.getText().equalsIgnoreCase("Italiano")) {
e.click();
break;
} else if (e.getText().equalsIgnoreCase("Pусский")) {
e.click();
break;
} else if (e.getText().equalsIgnoreCase("Français")) {
e.click();
break;
} else if (e.getText().equalsIgnoreCase("Português")) {
e.click();
break;
} else {
System.out.println("Please select appropriate language");
}
}
}
I would suggest a much simpler but more flexible version of your method.
Some suggestions:
I would change your method to take the desired language as a parameter to significantly simplify the code but also make it very flexible.
WebDriverWait, in most cases, will return the found element(s). Use that to simplify your code to a one-liner, e.g.
new WebDriverWait(...).until(ExpectedConditions.elementToBeClickable).click();
You didn't provide the code of your custom method, waitForElementToBeClickable, but if you really want to keep it, have it return the element(s) waited for to make it more useful and save having to write extra code.
If you have nested double quotes, I would suggest you use a combination of double and single quotes. It's a personal preference but I think it makes it easier to read than \", e.g.
"//div[#class=\"lang-identifier\"]"
would turn into
"//div[#class='lang-identifier']"
Instead of grabbing all options and then looping through them to compare the contained text to some desired string, use an XPath that contains the desired text instead, e.g. for "English" the XPath will look like
//ul[#class='dropdown-menu pull-right']/li[text()='English']
NOTE: .getAttribute("value") gets the value of an INPUT and will not work on other elements, e.g. the LI elements in your elements variable. .getText() returns the text contained in an element but will not work on INPUTs.
After implementing these suggestions, the code turns into a two-liner and is very flexible.
public static void SelectLanguage(String language) {
new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.lang-identifier"))).click();
driver.findElement(By.xpath("//ul[#class='dropdown-menu pull-right']/li[text()='" + language + "']")).click();
}

Would like to stop execution of code when a match is met

I created this service method in Angular JS which checks if an array of potential statuses(pendingApplications) match any of an array of set statuses(applicableStatuses). For this to work it meetsStatusCondition should return true after the first match occurs. Only 1 of the numbers in pendingApplications array needs to match and I'd like to end the execution of this function. Currently it's looping through every item in pendingApplications array
`containsApplicableStatus: function(pendingApplications, applicableStatuses) {
pendingApplications.forEach(function(status) {
if (applicableStatuses.includes(status)) {
return pendingApplications.meetsStatusCondition = true;
}
});
}`
This is a limitation with .forEach, you can't break out if it like you can with a for loop
Just a regular for loop will work
for (const status of applicableStatuses){
if (applicableStatuses.includes(status)) {
pendingApplications.meetsStatusCondition = true;
break //or return if you want to exit out of the enclosing function instead of just the loop
}
}
Often when you want to short-circuit a forEach like this, what you're really looking for is another method like find() or some().
containsApplicableStatus: function(pendingApplications, applicableStatuses) {
pendingApplications.meetsStatusCondition = pendingApplications.some(function(status) {
return applicableStatuses.includes(status)
});
}
There is no point in using forEach (which doesn't have a breaking option) if you could just use a regular for ... of loop instead:
containsApplicableStatus: function(pendingApplications, applicableStatuses) {
for (const status of pendingApplications) {
if (applicableStatuses.includes(status)) {
pendingApplications.meetsStatusCondition = true;
break;
}
}
}
However, even this seems a bit too complicated, you could just set meetsStatusCondition to the result of some:
containsApplicableStatus: function(pendingApplications, applicableStatuses) {
pendingApplications.meetsStatusCondition =
pendingApplications.some(status => applicableStatues.includes(status));
}
I do wonder if it makes sense to set a non-index property on your array though, maybe rethink that. This works but it's usually not something you'd expect on an array, and it will be lost if you convert that array to JSON for instance.

Mockito mock a method with infinite loop

I have a method as follows
public class ClientClass {
public void clientMethod() {
while(true){
doSomethings.....
}
}
}
I am trying to test using mockito. I am able to make the call to clientMethod, but since there is a while(true) inside clientMethod, the call never returns and I never reach to my assert statements which (of course) occur after clientMethod() invocation.
Is there a way to stop the loop after one loop iteration from my test case?
Technicaly you can't break the infinite loop in test without throwing an exception from inside it. If there is something inside the loop you can mock, then it may produce an exception for you.
When you're finding yourself in situation like this, when awkward workarounds are necessary for testing, then it's time to stop and think about the design. Non-testable code is generaly ill-maintainable and not very self-explanatory. So my advice would be to get rid of infinite loop and introduce an appropriate loop condition. After all, no application will live forever.
If you're still convinced that endless loop is the best way to go here, then you can perform a slight decomposition to make things more testable:
public class ClientClass {
// call me in production code
public void clientMethod() {
while(true){
doSomethings();
}
}
// call me in tests
void doSomethings(){
// loop logic
}
}
This was a source of a little frustration to me... because I like to start off the most sophisticated of GUI apps with a console handler.
The language I'm using here is Groovy, which is a sort of marvellous extension of Java, and which can be sort of mixed in with plain old Java.
class ConsoleHandler {
def loopCount = 0
def maxLoopCount = 100000
void loop() {
while( ! endConditionMet() ){
// ... do something
}
}
boolean endConditionMet() {
loopCount++
loopCount > maxLoopCount // NB no "return" needed!
}
static void main( args ) {
new ConsoleHandler().loop()
}
}
... in a testing class (also in Groovy) you can then go
import org.junit.contrib.java.lang.system.SystemOutRule
import org.junit.contrib.java.lang.system.
TextFromStandardInputStream.emptyStandardInputStream
import static org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import static org.mockito.Mockito.*
class XXTests {
#Rule
public SystemOutRule systemOutRule = new SystemOutRule().enableLog()
#Rule
public TextFromStandardInputStream systemInMock = emptyStandardInputStream()
ConsoleHandler spyConsoleHandler = spy(new ConsoleHandler())
#Test
void readInShouldFollowedByAnother() {
spyConsoleHandler.setMaxLoopCount 10
systemInMock.provideLines( 'blah', 'boggle')
spyConsoleHandler.loop()
assertThat( systemOutRule.getLog() ).containsIgnoringCase( 'blah' )
assertThat( systemOutRule.getLog() ).containsIgnoringCase( 'boggle' )
The beautiful thing that's happening here is that simply by declaring maxLoopCount the language automatically creates two methods: getMaxLoopCount and setMaxLoopCount (and you don't even have to bother with brackets).
Of course the next test would be "loop must exit if a user enters Q" or whatever... but the point about TDD is that you want this to FAIL initially!
The above can be replicated using plain old Java, if you must: you have to create your own setXXX method of course.
I got stuck in this because I was calling same method from inside the method by mistake.
public OrderEntity createNewOrder(NewDepositRequest request, String userId) {
return createNewOrder(request, userId);
}

how can i test a get method in my controller

I have a property in my controller that I would like to test:
public List<SelectOption> exampleProperty {
get {
//Do something;
}
}
I am not sure how to cover this code in my test class. Any ideas?
There is direct way, just invoke the property from test method
List<SelectOption> temp = obj.method;
You may need to directly test your properties, especially if you use lazy initialization - a smart pattern for making code efficient and readable.
Here's a list example of this pattern:
Integer[] lotteryNumbers {
get {
if (lotteryNumbers == null) {
lotteryNumbers = new Integer[]{};
}
return lotteryNumbers;
}
set;
}
If you wanted full coverage of the pattern (which may be a good idea while you're getting used to it), you would need to do something like the following:
static testMethod void lotteryNumberFactoryText() {
// test the null case
System.assert(lotteryNumbers.size() == 0);
Integer[] luckyNumbers = new Integer[]{33,8};
lotteryNumbers.addAll(luckyNumbers);
// test the not null case
System.assert(lotteryNumbers == luckyNumbers);
}
First off, do you really want to have an attribute named "method"? Seems a helluva confusing. Anyway, to cover the code, just call
someObject.get(method);
But code coverage should be a side effect of writing good tests - not the goal. You should think about what the code is supposed to do, and write tests to check (i.e. assert) that it is working.

Which is better practice - for loop with break or conditional loop? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm just curious what peoples' thoughts are on this topic. Let's say I have an Array of Objects, and I want to loop through them to see if the Objects contain certain values, and if so, I want to stop the loop. Which is better practice - a for loop with a break, or a conditional loop?
The pseudo-code in the example I have provided is for argument's sake only (it is also in ActionScript, since that is my primary language of late). Also, I am not looking for best practice ideas on syntax.
for loop with break:
var i:int;
var isBaxterInMilwaukee:Boolean;
for (i = 0; i < arrayLen; i++)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
break;
}
}
conditional loop:
var i:int;
var isBaxterInMilwaukee:Boolean;
while (!isBaxterInMilwaukee && i < arrayLen)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
i++;
}
In short, you should go with whichever version is the easiest to read and maintain.
In slightly older times, I know breaking out of a loop was considered to be a no-no (on par with a goto statement). Loops were supposed to break on the loop condition and nowhere else. Thus, the while-loop would have been the way to go.
(This is probably a holdover from assembly, where loops are basically a block of code with a go-to-the-beginning-if-true jump statement at the end. Multiple conditional-jump statements in the block make it exceedingly hard to debug; thus they were to be avoided and combined into one at the end.)
I feel this idea seems to be changing a bit today, especially with foreach loops and the managed world; it's really a matter of style now. Break-on-found for-loops have perhaps come to be acceptable to many, save some purists of course. Note that I would still avoid using break in a while-loop, however, as this can muddle the loop condition and make it confusing.
If you'll allow me to use a foreach loop, I consider the code below to be a lot easier to read than its while-loop brother:
bool isBaxterInMilwaukee;
foreach (var item in myArray)
{
if (item.name == "baxter" && item.location == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
break;
}
}
However, as the logic grows in complexity, you may want to consider a prominent comment near the break statement lest it become buried and hard to find.
Arguably, this whole thing should be refactored into its own function which doesn't break on found, but actually returns the result (feel free to use the for-loop version instead):
bool isBaxterInMilwaukee(Array myArray)
{
foreach (var item in myArray)
{
if (item.name == "baxter" && item.location == "milwaukee")
{
barkTwice();
return true;
}
}
return false;
}
As Esko Luontola pointed out, it would probably be best to move the call to barkTwice() outside of this function as the side-effect is not evident from the function's name, nor related to finding Baxter in every case. (Or add a boolean parameter BarkTwiceIfFound and change the line to read if(BarkTwiceIfFound) barkTwice(); to make the side-effect clear.)
For the record, you can also do the flag check in the for-loop without a break, but I feel this actually hurts readability because you don't expect an extra condition in a for-loop definition:
var i:int;
var isBaxterInMilwaukee:Boolean;
for (i = 0; !isBaxterInMilwaukee && i < arrayLen; i++)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
}
You can also simulate auto-incrementing mechanics with a while-loop. I don't like this for a few reasons - you have to initialize i to be one less than your real starting value, and depending on how your compiler short-circuits the loop-condition logic, your value of i on exiting the loop may vary. Nevertheless, it is possible and for some people, this can improve readability:
var i:int = -1;
var isBaxterInMilwaukee:Boolean;
while (!isBaxterInMilwaukee && ++i < arrayLen)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
}
I've always disliked the use of breaks in code... In this case it doesn't seem to matter but on more involved loops, it can be awfully confusing to another coder reading it. In general, it often results in not understanding how the loop may terminate until the coder spots the nested break deep in the loop. By specifying a flag condition that's checked each iteration of the loop, it makes this much clearer.
This problem would be similar to having return statements that are deep in the body of a method where they're not easily spotted (rather than setting a retVal variable and returning at the end of the method). With a small method, this seems fine, but the bigger it gets, the more confusing this will be.
It's not an efficiency of operation thing, it's a maintainability thing.
Ask your coworkers what's readable and understandable for a particular situation... That's what really matters.
I would say it depends. In this case the loop with the break seems clearer to me.
In a for loop you can also early exit by putting the early exit criteria in the for loop declaration. So for your example you could do it this way:
var i:int;
var isBaxterInMilwaukee:Boolean;
isBaxterInMilwaukee = false;
for (i = 0; i < arrayLen && !isBaxterInMilwaukee; i++)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
}
That way you don't need a break, and it's still more readable than a while loop.
There is a conceptual difference between the two. for loops are for iterating over discrete sets and while loops are for repeating statements based on a condition. Other languages add in finally clauses and looping constructs like foreach or until. They tend to have considerably fewer traditional for loops.
In any case, the rule that I use is that for loops iterate and while loops repeat. If you see something like:
while (counter <= end) {
// do really cool stuff
++counter;
}
Then you are probably better off with a for loop since you are iterating. However, loops like:
for (int tryCount=0; tryCount<2; ++tryCount) {
if (someOperation() == SUCCESS) {
break;
}
}
should be written as while loops since they are really repeating something until a condition is true.
The thought of not using break since it is just as evil as goto is pretty nonsensical. How can you justify throwing an exception then? That's just a non-local and non-deterministic goto! By the way, this isn't a rant against exception handling, just an observation.
The one that makes the most sense is going to be the one that conveys the idea to the human reading the code the best. Remember code readability first, and you'll usually make the correct choice. Usually, you do not want to use something like break unless you really need to, because it can make things hard to follow if done often or even just in a deeply-nested set of expressions. continue can serve the same purpose as a break sometimes, and the loop will then exit normally instead of because it was broken. In this case, there are a couple of different ways I might write this.
Probably the best thing you want here is a modification of your while loop:
while(!isBaxterInMilwaukee || i < arrayLen) {
if(myArray[i]["name"] == "baxter" && myArray[i]["location"] == "milwaukee") {
isBaxterInMilwaukee == true;
barkTwice()
} else {
i++;
}
}
That's clear and doesn't use break or continue, so you can tell at a glance that you'll always terminate as a result of one of the conditions specified in the while expression.
ETA: Probably should be i < arrayLen in the while loop otherwise it fails the first time through unless the input value is the same as the target value...
I see the break in both loops, is that correct?
Anyway:
I would choose FOR loop when there is known number (maximum number) of iterations before loop starts.
I would choose WHILE otherwise.
In FOR loop I use BREAK freely.
In WHILE loop I prefer to use complex condition instead of BREAK (if it is possible).
I would say break, clearer (even if you put in a comment why you break out of the loop)
Imho the while loop is not clear, i would go for break
I would definitely go with the for+break. The ‘for’ is an instantly-recognisable idiom for “iterate over sequence” and it's easier to understand “iterate over sequence; end early if value found” than the combined loop-and-stop condition.
There may be evidence for this in the way you seem to have made two mistakes in your conditional loop code!
the while condition (!isBaxterInMilwaukee || i == arrayLen) — did you mean “(!(isBaxterInMilwaukee || i == arrayLen))”?
break statement is unnecessary if you're using a terminate-loop variable.
Personally I find a simple ‘break’ much easier to read than trying to track a terminate-loop variable.
There are two aspects of the problem:
What to do (eg: find if one of the items contain the specified person in the location)
How to do it (eg: use an index, iterate etc)
Both of the examples mix the two and is hard to understand the what from the how. The best would be if we could express in code only the what part. Here is an example (c# 3.5) that does this using the specification pattern
// what we are looking for?
IsPersonInLocation condition = new IsPersonInLocation("baxter", "milwaukee");
// does the array contain what we are looking for?
bool found = myArray.Find(item => condition.IsSatifiedBy(item));
// do something if the condition is satisfied
if (found) {
barkTwice();
}
For completeness here is the class definition for the condition:
class IsPersonInLocation {
public string Person { get; set; }
public string Location { get; set; }
public IsPersonInLocation(string person, string location) {
this.Person = person;
this.Location = location;
}
bool IsSatifiedBy(item) {
return item["name"] == this.Person
&& item["location"] == this.Location;
}
}
It depends a lot on what the specific circumstances are. But in your example, you want to walk an array of bounded length, and using a for loop makes it easy to do that and guard against running off the end. In your while loop example you have to do your own incrementing--which can be problematic if you wanted to use a continue statement to skip into the next cycle--and make a more complex conditional expression (which, by the way, has a bug; I think you meant && i != arrayLen ). You're just having to do extra code to accomplish the effect that for loops help provide.
Of course, some purists will argue that break and continue should not be used and that you should use if-else and boolean variables if needed rather than continue or break out of a loop. But I think that can make the loop look much more ugly, especially if its relatively short and easy to grasp in general like this example. For a loop with much longer code where a break or continue could easily hide from notice, the purist approach might be more clear, since the loop is already complicated to grasp in that case. But you can always do this as part of the for loop, just add it as part of the conditional.
It's also better practice to test the array bound with i < arrayLen rather than for an exact equality, in case something caused i to skip over the exact value (I actually saw this happen in a Y2K bug, which could have been avoided by the better practice).
I have a C++ background and so I still have moments where I try to "think like the compiler". While loops tend to result in tighter code, and so for loops were only ever considered if you knew you were going to iterate over every element in the array, every time.
EDIT: I now believe this is overkill, if you're using .Net or whatever you aren't going to make up for the VM overhead with a couple of tight loops. I do think remembering the "why" of certain practices is a good thing though.
My theory is that there is a useful programming abstraction similar to "signal-to-noise ratio", which is "problem-to-tool ratio" - goodness can be measured in one dimension by how much time I spend thinking about the problem and its solution, compared to the time I spend thinking about how to use the tool (in this case language syntax).
By that measure, I try to use fewer constructs more frequently, because I (and hopefully those who follow) can grok the essence of my code structure more quickly and accurately. And since variations of "for loops" do a pretty good job of covering the cases where the others might be used (without distortion), I use them as a first preference, when they are interchangeable.
And it's nice to have everything you need to know (grokwise) about the loops rules in a single line at the top of the "for" loop. I also tend to put the "default" switch first in the tests for the same reason.
But consistency and clarity is the ovveriding consideration. YMMV, of course.
I guess neither is actually vary interesting. You should look for higher level constructs if it's readability you're after.
In JS:
if(myArray.some(function(o) { o.name == "baxter" && o.location == "milwaukee" }))
barkTwice();
or with some utils of your own
if(myArray.containsMatch({name:"baxter",location:"milwaukee"})
barkTwice();
Encapsulate the loop in its own method and use return to end processing when your match condition has succeeded.
Some example C# code:
class Program
{
static bool IsBaxterInMilwaukee(IList<WhoAndWhere> peopleAndPlaces)
{
foreach (WhoAndWhere personAndPlace in peopleAndPlaces)
{
if (personAndPlace.Name == "Baxter"
&& personAndPlace.Location == "Milwaukee")
{
return true;
}
}
return false;
}
static void Main(string[] args)
{
List<WhoAndWhere> somePeopleAndPlaces = new List<WhoAndWhere>();
somePeopleAndPlaces.Add(new WhoAndWhere("Fred", "Vancouver"));
somePeopleAndPlaces.Add(new WhoAndWhere("Baxter", "Milwaukee"));
somePeopleAndPlaces.Add(new WhoAndWhere("George", "London"));
if (IsBaxterInMilwaukee(somePeopleAndPlaces))
{
// BarkTwice()
Console.WriteLine("Bark twice");
}
}
public class WhoAndWhere
{
public WhoAndWhere(string name, string location)
{
this.Name = name;
this.Location = location;
}
public string Name { get; private set; }
public string Location { get; private set; }
}
}
My general stance is:
If it has a loop counter use for() (like while while loop does).
I vote while because breaks reduce grokability.
You may not realize the loop contains a break if the loop has grown too long and you insert code you expect to run and it does not.
But I subscribe to the don't make me think model of coding.
In ES6, it has been made very easy, no need to use the break keyword, We can use the find function, once the condition satisfies, we can return true.
let barkTwice = () => {
console.log('bark twice');
}
let arr = [{
location: "waukee",
name: "ter"
}, {
location: "milwaukee",
name: "baxter"
},
{
location: "sample",
name: "sampename"
}
];
Here we matching the condition and once the condition matches, we are calling the function, as per the question and then we are returning true. So that it does not go beyond.
arr.find(item => {
if (item.location == "milwaukee" && item.name == "baxter") {
barkTwice();
return true
}
});

Resources