### Calculation Errors and Mistakes in Java – How to calculate correctly

This is a real world example on which money was lost by client. This was not explicable, but I managed to analyze and reconstruct the problem.

The Code you are about to see is NOT the production code, but my own reconstruction of it, with a means to show the problem.

`````` @Test
public void testWrong() {

// GIVEN
final Integer price = -595;
final Integer someUnit = 90;

// WHEN
int multiplicationResult = price * someUnit;
// = -53550

Integer resultAmount = multiplicationResult / 100;
// = -535
// …Division failed,
// decimal places ignored...

// THEN
assertTrue(resultAmount == -535);
// Wrong. Correct: -536.
}``````

The specification on which the primitives and float are defined do not allow a correct calculation (mistake 1).

Although primitives cause the most trouble in calculation programming for many people, this example would have worked, if the return type of „multiplicationResult“ would be a double (mistake 2).

But experience shows that even these basics are quite often the main reason for calculation mistakes in Java, so I always recommend a certain way of calculating to avoid them, which I will show below.

``````@Test
public void testCorrect() {

// GIVEN
final Integer price = -595;
final Integer someUnit = 90;
// WHEN
BigDecimal priceBD = new BigDecimal(price);
BigDecimal someUnitBD = new BigDecimal(someUnit);
BigDecimal hundred = new BigDecimal(100);

BigDecimal multiplicationResult = priceBD.multiply(someUnitBD); // = -53550

// = -535.5 - looks great.
BigDecimal resultAmountBD = multiplicationResult.divide(hundred);

final int noDecimalPlaces = 0;
// rounding mode is vital to get a correct result
final RoundingMode roundingMode = RoundingMode.HALF_UP;

// do not forget to define the decimal places...0
BigDecimal result = resultAmountBD.setScale(noDecimalPlaces, roundingMode);

// THEN
assertThat(result.toBigInteger().intValue(), equalTo(-536)); // Correct!

}``````

The Big Decimal is calculated by using a String representation. Calculation is done piece by piece. Thus, the specification of float and primitives in general cannot interfere and cause calculation mistakes through number spaces, computing practices of the CPU etc..

Standard IEEE 754 defines Exception Handling and number spaces. It defines, how float and double is processed. Floating Points are meant to approach a certain precision, but without being 100% accurate. It is equivalent to Math/Analysis lambda, which is marking a barrier to come close to, which is never really reached (infinite lambda for instance).

In Summary:

• Division, multiplication must be done by using a wrapper like BigDecimal.
• Decimal Places have to be defined
• Rounding modes have to be defined
• In case that multiple systems are calculating together (e.g. bank or any other financial institution or software), a contract has to be agreed on. The contract must state how many decimal places are to be used (retail does often use 3 decimal places but only shows 2 on the displays in the shelves). Also the rounding mode plays a vital role in calculation.
• Never use primitives, even if you are sure that in ‚your specific case‘ it is sufficient
• Also experienced programmers make these mistakes, which is why I am posting this in my Blog.

### GHOST IN THE MACHINE – Thoughts on AI… Pt. I

GHOST IN THE MACHINE – Pt. I =>
The issue with Artificial Intelligence, AI, is, that it is in many cases not possible, to tell WHY a decision was made. If an autonomous car decides to collide with the young woman on the street instead of jamming into the bus, when a collision had become inevitable, it is not possible to tell WHY.

We have to move forward, strive to achieve and develop the AI further in order to bring humanity to the next level.
But as it is not possible to look up Code and see the „IF collisionInevitable THEN collideWithYoungWoman“ part anymore, we must be aware of the greater challenge which awaits.

We need to tackle questions of morale, ethics and responsibility. How much rights are granted to artificial minds?

There will be a moment in time on which we take the Turing Test and suddenly we will think that there are feelings inside the machine. Perhaps there are. How will we proceed from there?

### Java Mockito Argument Matcher examples

``````
//imports
import org.mockito.*;

//specified arguments
when(someMock.foo("fooString", barInstance).thenReturn(...)

//generic argument matchers
when(someMock.foo(any(), eq(Bar.class))).thenReturn(...)``````

### if else condition with Java Lamba – Howto

``````//lambda Predicate
private static Predicate<HttpStatus> isErrorCode = (HttpStatus statusCode) -> (statusCode.is5xxServerError() || statusCode.is4xxClientError());

public static Mono<ClientResponse> getResponse(ClientResponse clientResponse) {
if (isErrorCode.test(clientResponse.statusCode())) {``````

Do not forget to checkout the BiPredicate as well 😉

### Why Spring Webflux is better than HttpClient – HowTo in Java

A lot of Boilerplate Code can be avoided.

AND: it is reactive, non-blocking.

Example (really, an example) – the ‚old way‘:

``````        HttpPost request = new HttpPost("http://www.someurl.de");
ContentType.APPLICATION_JSON.getMimeType());

String json = someJsonConverter.toJson(someRequestDto);
HttpEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
request.setEntity(stringEntity);

try {
CloseableHttpResponse response2 = httpclient.execute(request);

if (HttpStatus.SC_CREATED != response2.getStatusLine().getStatusCode()) {
//TODO eventually handle http statuus additionally
return returnHandleAndDoNotThrow();
}
SomeResponseDto responseDto = (SomeResponseDto)
someJsonConverter.toDto(EntityUtils.toString(response.getEntity()),
SomerResponseDto.class);
return Optional.ofNullable(responseDto);
} catch (IOException e) {
return Optional.empty();;
}``````

The new way:

``````        Function<UriBuilder, URI> function = uriBuilder ->
uriBuilder.path("/somePath").build();
return client.post()
.uri(function)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.body(Mono.just(someDtoInstance), SomeDto.class)
.exchange()
.block()
.bodyToFlux(someResponseDto.class);
//any errors, status codes are handled by a filter which you can define as follows:``````

Howto:

I am using Spring Boot for this, so I do have a Config class.

``````import ...
import org.springframework.context.annotation.Bean;
import reactor.core.publisher.Mono;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WebClientConfig {

//Create the Bean for Autowiring
@Bean
public WebClient webClient() {
return WebClient.builder().filter(someStatusHandlingFilter()).build();
}

//Handle status codes
public static ExchangeFilterFunction someStatusHandlingFilter() {
return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
if ((clientResponse.statusCode().is4xxServerError()
|| clientResponse.statusCode().is5xxClientError())) {
return clientResponse
.bodyToMono(SomeException.class)
.flatMap(errorBody -> {
return Mono.error(someExceptionToLog);
});
} else {
return Mono.just(clientResponse);
}
});
}
}``````

Maven:

``````        <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>``````

### Java Stream Custom Collector – Howto

Sometimes the commonly available Collectors are not what we need.
Here is one example for a Singleton Custom Collector:

``````public static <T> Collector<T, ?, T> singleton() {
return Collectors.collectingAndThen(
Collectors.toList(), list -> {
if (list.size() != 1) {
// or log and return nil
throw new CustomException();
}
return list.get(0);
}
);
}

//and use it:
myObjectToStream.stream()
.filter(elem -> elem.getExampleAttribute() == 0).collect(singleton());``````

### Howto generate a new SSH key pair

``ssh-keygen -t ed25519 -C "email@example.com"``

Note that in this example we use an ed25519 key.

The -c is providing a comment to divide the key amongst others.

I alwas use the suggested path and just klick enter 😉

### How to run eslint in Terminal / Shell

``npm install && npm i -g eslint && npx eslint --ext .tsx --ext .ts ./``

Please heed that npm install is used here to start my React application, which uses it as a build tool. IMportant

npm i -g eslint will install eslint, if it does not exist yet (for example a CI with Jenkins).

The npx eventually executes eslint for all files with ending .tsx or .ts recursively in the current directory. Please adapt the endings according to your needs – when you do not use TypeScript but JavaScript change it to .js

### How to check Typescript Code with ESLint in IntelliJ or Webstorm

`````` "eslintConfig": {
"parserOptions": {
"parser": "babel-eslint",
"sourceType": "module"
},
"env": {
"browser": true,
"es6": true
},
"globals": {
"Vue": true
},
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint"
],
"extends": [
"plugin:@typescript-eslint/recommended"
],
"rules": {
"quotes": [
"error",
"double",
{
"avoidEscape": true
}
],
"comma-dangle": [
"error",
{
"arrays": "ignore",
"objects": "always-multiline",
"imports": "never",
"exports": "never",
"functions": "ignore"
}
],
"arrow-parens": 0,
"no-tabs": 0,
"indent": [
"error",
"tab",
{
"SwitchCase": 1
}
],
"no-console": 1,
"generator-star-spacing": 0
}
}``````

``npm install @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev``

From now on, when you open your .ts or .tsx files, the ESLint will detect the errors.

You can open the context menu then, by clicking the right mouse tab and click on „Fix ESlint Problems“.

IntelliJ will then automatically fix the problems.

### How to create an NPM Package

You want reusable components, elements? Flexible structure?
Separation of concerns, decoupling in your JS Code?

A good strategy is to create an NPM Package.

• Identify the code you would like to decouple.
• create a new project
• create an src folder
• paste the JS or TS files in that folder
• install the missing dependencies like Typescript, TSlint, Material UI
• Write UNIT Tests to test your code before publishing it

I use JEST and to include the relevant Code, add this to your tsconfig.json:

``````    "include": ["src/**/*"],
"exclude": ["node_modules", "**/__tests__/*"] ``````

Before the package is published, you can test it locally:

• In your terminal, run `npm link `
• This will compile and create a symbolic link, pointing to another directory/files on your development machine.
• Now include the new package as a dependency. In your terminal, run `npm link <module_name>`
• If everything can be imported and used, the test work and you are satisfied, perform `npm unlink --nosave <module_name>` on your main projects directory. This will remove the symbolic link.
• Then run `npm unlink` to also remove the global link.

Now you have extracted and published Code as NPM package.