Java 8 - Nested if inside a loop - java-8

So I have a list and for each item in the list I have to "do something" based on each list element.
The list consists of codes and there are a total of 5 codes. The list may contain any or all codes.
So far I've used the forEach and i've written the if conditions inside it as below -
List<Category> categories = getCategories();
categories.stream().forEach(category -> {
if(category.equals(Category.A)) {
// do something
} else if(category.equals(Category.B)) {
// do something
} else if(category.equals(Category.C)) {
// do something
} else if(category.equals(Category.D)) {
// do something
} else if(category.equals(Category.E)) {
// do something
}
});
I'm looking at refactoring this. Can someone please look at how better this can be done?

The only thing I would improve is to use a switch-statement:
switch(category){
case Category.A:
// do Something
break;
}
As mentionend by luk2302 this will only work if Category is an enum.

You can add a doSomething method to the Category class and simply call it in the .forEach.
For example:
public class Category {
// any other methods/variable/constructors
public void doSomething() {
//do something
}
}
Then you can call it like this:
categories.stream().forEach(Category::doSomething);
If the // do something has not a common behaviour, you can move the if part inside the doSomething method.

At first, do not use multiline lambdas and create new method (with switch):
private void doSomethingBasedOnCategory(Category category) {
switch(category) {
case A: // do something
break;
case B: // do something
break;
case C: // do something
break;
case D: // do something
break;
case E: // do something
break;
}
}
Then use it in your lambda:
getCategories()
.stream()
.forEach(category -> doSomethingBasedOnCategory(category);
Another way is to create static map prefilled with keys (which will be Category.X) and values (which will be functions ready to use)

Related

Ussing enum in processing switch case statment

I am trying to use "enum" in processing, in order to use it inside an "switch case" statment.
I am working on Processing 3.3.6.
I placed the "enum" statment in a new tab, names "Status.java".
I declared on the enum iteslf in the main tab.
I cant inicialize the enum that was creted with a value.
here is my code:
"Satus.java" tab:
enum State {A,B,C};
"Main" tab:
State state1=A;
void setup()
{
}
void draw()
{
println(state1);
switch (state1)
{
case A:
println("A");
case B:
println("B");
case C:
println("C");
}
}
You might want to explicitly access State.A when assigning the variable.
E.g.
State state1=State.A;
instead of
State state1=A;
and remember to use the break statement, otherwise you'll hit all cased.
Here's a basic version of you code above in a single sketch file:
enum State {A,B,C};
State state1=State.A;
void setup()
{
}
void draw()
{
println("state1",state1);
switch (state1)
{
case A:
println("A");
break;
case B:
println("B");
break;
case C:
println("C");
break;
default:
println("default: undefined state");
break;
}
}
First, you need to tell the status tab that it is a class:
static class status {
enum State {A,B,C};
}
In processing you'll need to use static class token, rather than public class, as you would in Java.
At the moment, the main class does not know what a State object is. This is why Processing cannot resolve / initialise your variable state1.
Tell it to look for the type in the status class like so:
Status.State state1 = Status.State.A;
Finally, don't forget to add break; after each case in the switch statement otherwise a match for A will also print B and C (switch statements fall through).
switch (state1) {
case A :
println("A");
break;
case B :
println("B");
break;
case C :
println("C");
break;
}

How to refactor cascade if statements

I found this question on https://github.com/arialdomartini/Back-End-Developer-Interview-Questions#snippets
And I am curious about your opinion, I just can't find an decent solution of this refactor, and what pattern would apply in this very common case.
function()
{
HRESULT error = S_OK;
if(SUCCEEDED(Operation1()))
{
if(SUCCEEDED(Operation2()))
{
if(SUCCEEDED(Operation3()))
{
if(SUCCEEDED(Operation4()))
{
}
else
{
error = OPERATION4FAILED;
}
}
else
{
error = OPERATION3FAILED;
}
}
else
{
error = OPERATION2FAILED;
}
}
else
{
error = OPERATION1FAILED;
}
return error;
}
Do you have any idea of how to refactor this?
Actually, I feel there is way more space for refactoring than what suggested by Sergio Tulentsev.
The questions in the repo you linked are more about starting a conversation on code than closed-ended questions. So, I think it is worth to discuss the smells and design flaws of that code, to set up the refactoring goals.
Smells
I see these problems:
The code violates some of the SOLID principles. It surely violates the Open Closed Principle, as it is not possible to extend it without changing its code. E.g., adding a new operation would require adding a new if/else branch;
It also violate the Single Responsibility Principle. It just does too much. It performs error checks, it's responsible to execute all the 4 operations, it contains their implementations, it's responsible to check their results and to chain their execution in the right order;
It violates the Dependency Inversion Principle, because there are dependencies between high-level and low-level components;
It has a horrible Cyclomatic complexity
It exhibits high coupling and low cohesion, which is exactly the opposite of what is recommended;
It contains a lot of code duplication: the function Succeeded() is repeated in each branch; the structure of if/elses is replicated over and over; the assignment of error is duplicated.
It could have a pure functional nature, but it relies instead on state mutation, which makes reasoning about it not easy.
There's an empty if statement body, which might be confusing.
Refactoring
Let's see what could be done.
Here I'm using a C# implementation, but similar steps can be performed with whatever language.
I renamed some of the elements, as I believe honoring a naming convention is part of the refactoring.
internal class TestClass
{
HResult SomeFunction()
{
var error = HResult.Ok;
if(Succeeded(Operation1()))
{
if(Succeeded(Operation2()))
{
if(Succeeded(Operation3()))
{
if(Succeeded(Operation4()))
{
}
else
{
error = HResult.Operation4Failed;
}
}
else
{
error = HResult.Operation3Failed;
}
}
else
{
error = HResult.Operation2Failed;
}
}
else
{
error = HResult.Operation1Failed;
}
return error;
}
private string Operation1()
{
// some operations
return "operation1 result";
}
private string Operation2()
{
// some operations
return "operation2 result";
}
private string Operation3()
{
// some operations
return "operation3 result";
}
private string Operation4()
{
// some operations
return "operation4 result";
}
private bool Succeeded(string operationResult) =>
operationResult == "some condition";
}
internal enum HResult
{
Ok,
Operation1Failed,
Operation2Failed,
Operation3Failed,
Operation4Failed,
}
}
For the sake of simplicity, I supposed each operation returns a string, and that the success or failure is based on an equality check on the string, but of course it could be whatever. In the next steps, it would be nice if the code is independent from the result validation logic.
Step 1
It would be nice to start the refactoring with the support of some test harness.
public class TestCase
{
[Theory]
[InlineData("operation1 result", HResult.Operation1Failed)]
[InlineData("operation2 result", HResult.Operation2Failed)]
[InlineData("operation3 result", HResult.Operation3Failed)]
[InlineData("operation4 result", HResult.Operation4Failed)]
[InlineData("never", HResult.Ok)]
void acceptance_test(string failWhen, HResult expectedResult)
{
var sut = new SomeClass {FailWhen = failWhen};
var result = sut.SomeFunction();
result.Should().Be(expectedResult);
}
}
Our case is a trivial one, but being the quiz supposed to be a job interview question, I would not ignore it.
Step 2
The first refactoring could be getting rid of the mutable state: each if branch could just return the value, instead of mutating the variable error. Also, the name error is misleading, as it includes the success case. Let's just get rid of it:
HResult SomeFunction()
{
if(Succeeded(Operation1()))
{
if(Succeeded(Operation2()))
{
if(Succeeded(Operation3()))
{
if(Succeeded(Operation4()))
return HResult.Ok;
else
return HResult.Operation4Failed;
}
else
return HResult.Operation3Failed;
}
else
return HResult.Operation2Failed;
}
else
return HResult.Operation1Failed;
}
We got rid of the empty if body, making in the meanwhile the code slightly easier to reason about.
Step 3
If now we invert each if statement (the step suggested by Sergio)
internal HResult SomeFunction()
{
if (!Succeeded(Operation1()))
return HResult.Operation1Failed;
if (!Succeeded(Operation2()))
return HResult.Operation2Failed;
if (!Succeeded(Operation3()))
return HResult.Operation3Failed;
if (!Succeeded(Operation4()))
return HResult.Operation4Failed;
return HResult.Ok;
}
we make it apparent that the code performs a chain of executions: if an operation succeeds, the next operation is invoked; otherwise, the chain is interrupted, with an error. The GOF Chain of Responsibility Pattern comes to mind.
Step 4
We could move each operation to a separate class, and let our function receive a chain of operations to execute in a single shot. Each class would deal with its specific operation logic (honoring the Single Responsibility Principle).
internal HResult SomeFunction()
{
var operations = new List<IOperation>
{
new Operation1(),
new Operation2(),
new Operation3(),
new Operation4()
};
foreach (var operation in operations)
{
if (!_check.Succeeded(operation.DoJob()))
return operation.ErrorCode;
}
return HResult.Ok;
}
We got rid of the ifs altogether (but one).
Notice how:
The interface IOperation has been introduced, which is a preliminary move to decouple the function from the operations, complying the with the Dependency Inversion Principle;
The list of operations can easily be injected into the class, using the Dependency Injection.
The result validation logic has been moved to a separate class Check, injected into the main class (Dependency Inversion and Single Responsibility are satisfied).
internal class SimpleStringCheck : IResultCheck
{
private readonly string _failWhen;
public Check(string failWhen)
{
_failWhen = failWhen;
}
internal bool Succeeded(string operationResult) =>
operationResult != _failWhen;
}
We gained the ability to switch the check logic without modifying the main class (Open-Closed Principle).
Each operation has been moved to a separate class, like:
internal class Operation1 : IOperation {
public string DoJob()
{
return "operation1 result";
}
public HResult ErrorCode => HResult.Operation1Failed;
}
Each operation knows its own error code. The function itself became independent from it.
Step 5
There is something more to refactor on the code
foreach (var operation in operations)
{
if (!_check.Succeeded(operation.DoJob()))
return operation.ErrorCode;
}
return HResult.Ok;
}
First, it's not clear why the case return HResult.Ok; is handled as a special case: the chain could contain a terminating operation never failing and returning that value. This would allow us to get rid of that last if.
Second, our function still has 2 responsibility: to visit the chain, and to check the result.
An idea could be to encapsulate the operations into a real chain, so our function could reduce to something like:
return operations.ChainTogether(_check).Execute();
We have 2 options:
Each operation knows the next operation, so starting from operation1 we could execute the whole chain with a single call;
Operations are kept unaware of being part of a chain; a separate, encapsulating structure adds to operations the ability to be executed in sequence.
I'm going on with the latter, but that's absolutely debatable. I'm introducing a class modelling a ring in a chain, moving the code away from our class:
internal class OperationRing : IRing
{
private readonly Check _check;
private readonly IOperation _operation;
internal IRing Next { private get; set; }
public OperationRing(Check check, IOperation operation)
{
_check = check;
_operation = operation;
}
public HResult Execute()
{
var operationResult = _operation.DoJob();
if (_check.Succeeded(operationResult))
return Next.Execute();
return _operation.ErrorCode;
}
}
This class is responsible to execute an operation and to handle the execution to the next ring if it succeeded, or to interrupt the chain returning the right error code.
The chain will be terminated by a never-failing element:
internal class AlwaysSucceeds : IRing
{
public HResult Execute() => HResult.Ok;
}
Our original class reduces to:
internal class SomeClass
{
private readonly Check _check;
private readonly List<IOperation> _operations;
public SomeClass(Check check, List<IOperation> operations)
{
_check = check;
_operations = operations;
}
internal HResult SomeFunction()
{
return _operations.ChainTogether(_check).Execute();
}
}
In this case, ChainTogether() is a function implemented as an extension of List<IOperation>, as I don't believe that the chaining logic is responsibility of our class.
That's not the right answer
It's absolutely debatable that the responsibilities have been separated to the most appropriate classes. For example:
is chaining operations a task of our function? Or should it directly receive the chained structure?
why the use of an enumerable? As Robert Martin wrote in "Refactoring: Improving the Design of Existing Code": enums are code smells and should be refactored to polymorphic classes;
how much is too much? Is the resulting design too complex? Does the complexity of the whole application need this level of modularisation?
Therefore, I'm sure there are several other ways to refactor the original function. In a job interview, or in a pair programming session, I expect a lot of discussions and evaluations to occur.
You could use early returns here.
function() {
if(!SUCCEEDED(Operation1())) {
return OPERATION1FAILED;
}
if(!SUCCEEDED(Operation2())) {
return OPERATION2FAILED;
}
if(!SUCCEEDED(Operation3())) {
return OPERATION3FAILED;
}
if(!SUCCEEDED(Operation4())) {
return OPERATION4FAILED;
}
# everything succeeded, do your thing
return S_OK;
}

Is there a way to let Apollo Client globally insert empty strings during loading?

I'm using Apollo Client to receive the GraphQL data for my application. Over time, I see a pattern emerging where for every value I'm querying, I have to include a conditional statement to handle the moment where my data is still loading.
Assume a query looks like this:
query TestQuery($userId: Int!) {
getUser(id: $userId) {
name
}
}
Then, in every place where I want to display the user name, I have to write something like:
{ !this.props.data.loading && this.props.data.getUser.name }
or
{ this.props.data.getUser && this.props.data.getUser.name }
I don't want to display "Loading..." or a rotating spinner in any of these places. Is there a way to avoid this conditional statement by globally replacing all this.props.data.x.y.z values with null or an empty String during loading?
If so, how? Would this be considered an antipattern or bad practice?
If not, which of the above two forms is preferred?
Thanks.
How about this approach?
class GraphqlComponent extends React.Component {
renderError(){
// ...
}
renderLoading(){
// ...
}
renderLoaded(){
}
render(){
const { loading, error } = this.props;
if(error){
return renderError();
}
if(loading){
return renderLoading();
}
return renderLoaded();
}
}
class MyComponent extends GraphqlComponent{
renderLoaded(){
// your logic goes here
}
}

Using FormFlow Bots Framework Quiz Program

Our bot build does a ‘personality quiz’ for the user. Think Buzzfeed.
I have a variety of attributes I want to increase, just integers, based on the user’s selections on a form, then return an end result.
Using Sandwichbot as a template, this is asking something like (paraphrased):
Do you like to help other people? Yes No
Code is like:
.Confirm(async (state) =>
{
switch (state.HelpYesNo)
{
case true: HelpfulValue++; break;
case false: HurtfulValue++; break;
}
return new PromptAttribute("Thanks, choose OK to continue.");
It works fine, but I hate that I have to make the user ‘Confirm’ by typing OK. It’s an extra step, especially if they have to do it after each question.
I tried writing this with a validate instead, eg validate: async (state, response) =>
Which gives a better user experience, but doesn’t actually run the switch-case. I think the formatting of the switch is in the wrong place for a validate? I'm not sure of the syntax here to get 'validate' to process the case.
What’s the right way to do something like this in FormFlow?
Try something like this. Boolean fields also result in a Yes/No question.
[Serializable]
public class QuizForm
{
public int HelpfulValue;
public int HurtfulValue;
[Prompt("Do you like to help people? {||}")]
public bool HelpPeople;
public static IForm<QuizForm> BuildForm()
{
return new FormBuilder<QuizForm>()
.Message("Let the quiz begin...")
.Field(nameof(HelpPeople), validate: ValidateBool)
// other fields
.Build();
}
private static async Task<ValidateResult> ValidateBool(QuizForm state, object value)
{
var TrueOrFalse = (bool) value;
switch (TrueOrFalse)
{
case true: state.HelpfulValue++; break;
case false: state.HurtfulValue++; break;
}
return new ValidateResult{IsValid = true, Value = value};
}
}

Elastica: Best way to check if document with Id x exists?

Using the PHP Elastica library, I'm wondering what is the best way to check whether a document with Id=1 exists?
I was doing as follows:
$docPre = $elasticaType->getDocument(1);
if ($docPre) {
//do some stuff...
} else {
//do something else...
}
However, the above code does not work because a NotFoundException is thrown by the getDocument() method if the document does not exist.
Alternatively, I could do a type "search" using something like this:
$elasticaQueryString = new \Elastica\Query\QueryString();
$elasticaQueryString->setParam('id', 1);
$elasticaQuery = new \Elastica\Query();
$elasticaQuery->setQuery($elasticaQueryString);
$resultSet = $elasticaType->search($elasticaQuery);
$count = $resultSet->count();
if ($count > 0) {
//do some stuff...
} else {
//do something else...
}
However, the above seems quite cumbersome... What's the better way?
This other question applies to ElasticSearch, and one of the answers suggests my first approach (the equivalent to using getDocument). However, I do not want an Exception to be thrown, as it would be the case using Elastica...
Rather than preventing the Exception from being thrown, one way would be to simply deal with it with a "Try, throw and catch" block like this:
try {
$docPre = $elasticaType->getDocument(1);
} catch (Exception $e) {
$docPre = NULL;
}
if ($docPre != NULL) {
//do some stuff...
} else {
//do something else...
}

Resources