JavaRush /Java Blog /Random EN /Coffee break #109. The most in-demand skills in Java deve...

Coffee break #109. The most in-demand skills in Java development right now. 7 Java Optional Tips to Get Rid of Code Clutter

Published in the Random EN group

The most in-demand skills in Java development right now

Source: Medium Java remains one of the most popular and in-demand programming languages, despite the fact that it is almost a quarter of a century old. Therefore, it is reasonable to assume that Java's popularity will continue to grow and Java developers will see even greater demand from employers in the future. Coffee break #109.  The most in-demand skills in Java development right now.  7 Java Optional Tips to Get Rid of Code Clutter - 1To create quality products, developers need to keep up with the latest Java tools and improve their technical skills and knowledge. Below we present six essential skills required for Java developers.

1. Excellent knowledge of Java 8

Even though newer versions of Java are already widely used, all aspiring Java developers need in-depth knowledge and experience with Java 8. Some of the most useful features of Java 8 include:
  • Standard and static methods for creating interfaces with method implementations.
  • A functional interface that has only one abstract method and helps developers avoid adding other abstract methods.
  • Lambda expressions that help create functional interfaces.
  • Java Stream API to enable parallel and sequential execution.
  • New methods in the Collection API.
All these features make Java 8 indispensable for functional programming. Functional programming provides concurrency and code brevity, and helps create high-load applications with optimized code. Java 8 also became the basis for native code optimization, allowing for optimization of development in other languages ​​such as Scala, Kotlin, and Grails.

2. Experience with testing

Unit testing in Java is a rather controversial topic. Some developers argue that writing unit tests is a waste of time, but we firmly believe that unit testing skills are a must for any professional Java developer. Unit testing allows you to test individual blocks of code and ensures that the final product works without errors. Therefore, if a developer wants to improve his skills and knowledge, he needs to learn how to use the most popular and effective testing tools. The main testing framework you need to become familiar with is the JUnit 5 library. Other tools include:
  • Robot Framework
  • Mockito
  • PowerMock
Apart from unit testing, a Java developer should not forget about other testing methods (system testing, acceptance testing and integration testing). This allows you to perform comprehensive testing of the software and make sure there are no errors, bugs or critical failures. The main thing to remember about testing is that small changes lead to big results. If you don't hesitate to put the time and effort into unit testing, you will be amazed at the improvement in the quality of your work.

3. DevOps

Although not required, learning about DevOps and its principles can be beneficial for you as a developer and for the company you work for. The flexibility and organization of DevOps processes allows companies to optimize the quality of their product and streamline operations. and also increase the transparency of processes. DevOps in Java is essentially the application of DevOps to Java development. This includes:
  • Continuous delivery and integration.
  • Working with microservices instead of monoliths.
  • Infrastructure as code.
  • Automated testing.
DevOps is a vast field and requires a significant amount of time and resources to study it. But if you are a Java developer, learning DevOps will be beneficial as it will enable you to become a DevOps engineer in the future. If you don't want to become a DevOps engineer or your company isn't interested in it, then that's okay too. Just keep in mind that DevOps is becoming more and more popular in the Java community.

4. Knowledge of Java libraries and APIs.

Since Java is one of the leading programming languages ​​in the world, it is no surprise that it has a huge number of available APIs and libraries to work with. These tools greatly simplify the development process and allow developers to quickly create reliable software. Below we have listed a basic set of tools that any good Java developer knows and can confidently use. These tools help you quickly build an application and effectively manage data and its storage:
  • Gradle (a tool for building applications);
  • Maven (a little outdated but still popular, also used to build applications);
  • Java 8 Standard Packages;
  • Spring Frameworks;
  • JPA ORM (Hibernate, TopLink);
  • NoSQL databases (MongoDB, Cassandra).
As for the API, to work with the core Java API, a developer needs to have a good knowledge of OpenJDK, Android, Oracle and IS2T. The big advantage of these tools is that they all come with detailed and informative documentation. Moreover, developers can always get community support, which is also a big advantage.

5. Confident knowledge of Spring and Spring Boot

The Spring Framework is the most commonly used framework for developing Java-based applications, so it is important that a developer knows how to work with it. One of the key benefits of Spring is dependency injection, which allows you to create loosely coupled applications and gives developers more flexibility. Spring is also very lightweight, supporting XML configurations, annotations, and declarative programming. So if you want to master Java development skills, you should also master Spring deployment. Spring Boot is an iteration of Spring that provides a convenient tool for quickly deploying applications. It's safe to say that Spring Boot uses Spring as a base and builds its own features on top of it. While Spring is focused on flexibility, Spring Boot helps reduce code and simplify the development process. It offers developers out-of-the-box features, helps build standalone apps, and is overall easier to launch and manage. Spring Boot is great for microservices and applications that need to be built quickly, as it makes it quick and easy to set up and run applications for a variety of environments (production, test, quality, CI/CD). Both Spring and Spring Boot have expanded with React programming capabilities, which is another hot trend in the developer community. Spring 5, for example, now has WebFlux to implement a reactive approach to programming and resolving complex distributed systems.

6. Experience with Big Data

Big Data is a growing trend that developers must follow and adopt to meet market demands. The main tools that professional Java developers can become familiar with are:
  • Apache Spark
  • Apache Kafka
  • Hadoop (for batch processing)
Apache Spark is a distributed Big Data processing platform that provides native bindings for Java. This framework has become extremely popular due to its features and performance and is currently the most preferred big data tool in the Java community. Apache Spark can run in cluster standalone mode and for this you only need an Apache Spark environment and a JVM (for each machine in the cluster). Spark is also incredibly fast and has a very user-friendly Spark API. Hadoop is a data storage platform that is also well known to Java developers. Although Hadoop is not as fast as Spark, it remains one of the most popular tools for working with big data. This is also due to the fact that Hadoop (and similar solutions) have a large number of plugins that allow you to efficiently solve Big Data processing problems and generally optimize Hadoop performance (including support for real-time stream processing).

7 Java Optional Tips to Get Rid of Code Clutter

Source: Medium “I have colleagues who don’t know about the existence of Optional,” writes one Java developer on Reddit. Can we consider that Optional improves the “readability” of the code? Is it worth using it all the time? Where is the use of Optional completely unnecessary? Since many developers still don't know how to use Optional correctly, I will give 7 examples of Optional abuses and what to do about them. Coffee break #109.  The most in-demand skills in Java development right now.  7 Java Optional Tips to Get Rid of Code Clutter - 2

1. Don't use Optional for null check

Using Optional instead of null check just adds clutter. There is no benefit from this. It is also a mistake to use Optional and the isPresent and get methods . The developers believe that get should work as expected. They then add isPresent and return to null check. Remember that Optional does not fix your null checks. Next time you see isPresent and get (or ElseThrow ) change this piece of code. Use mapping and orElse to remove standard null checks, and use Optional more selectively. Here's one good example:
var user = userService.getCurrentUser();
if(user == null) {
    return "(unknown)";
}
var username = user.getUsername();
if (username == null) {
    return "(unknown)";
}
return username;
vs

var user = userService.getCurrentUser();
if(user.isEmpty()) {
    return "(unknown)";
}
var username = user.orElseThrow().getUsername();
if (username == null) {
    return "(unknown)";
}
return username;
vs

return userService.getCurrentUser()
                  .map(User::getUsername)
                  .orElse("(unknown)");
You can start with the Optional target. The purpose of Optional is to represent optional, missing values. Then go back to your problem and see if it works for you. Another way to deal with null check is to use annotations. Nullable or NotNull should work fine. True, they can pollute your code, and they only protect at compile time. To check runtime use Objects.requireNonNull .

2. Do proper error handling

Sometimes null represents exceptions. And this is the wrong way to signal errors and exceptions. “Something went wrong, and here it is null” is an anti-pattern that should be avoided. Also, you shouldn't use Optional to cover exceptions. Here's an example.
public Optional<MyObject> getMyObject(final String jql) {
    try {
        return Optional.ofNullable(get(sql));
    } catch (final JqlParseException e) {
        return Optional.empty();
    }
}
Why is myObject empty? This is either an error or an empty value. So you would again get an ambiguous result and erase the benefits of Optional as a result. This code exists because people are trying to use Optional for control flow. Optional will remove some zeros from your codebase. But you still need to use try-catch construct to handle exceptions. Use try-catch to handle exceptions correctly. Don't remove Optional when handling errors, just wait and it will work perfectly. But there is one exception here - empty catch . When you don't know what to return in an empty catch, an empty Optional should work fine.
private int readExpirationAsInt(Milk milk)
{
  String expiration = milk.getExpiration();
  try {
    return Integer.parseInt(expiration);
  }
  catch(NumberFormatException ignored) {}

  return 0;
}


private OptionalInt readExpirationAsInt(Milk milk)
{
  String expiration = milk.getExpiration();

  try {
    return Optional.of(Integer.parseInt(expiration));
  }
  catch(NumberFormatException e) {
    return OptionalInt.empty();
  }
}

3. Don't return null from Optional methods

public static Optional<POSType> getPOSType(String posName) {
    if (StringUtils.isNotBlank(posName)) {
        return Arrays.stream(POSType.values())
                .filter(type -> type.toString().equalsIgnoreCase(posName))
                .findFirst();
    }
    return null;
}
This defeats the purpose of Optional. This is another example of poor testing. Since the input is empty, this means we need an IllegalArgumentException file . Also, this is a mistake. Nobody needs to check Optional call methods. Return an empty Optional element and never check an Optional element for null.

4. Don't use Optional with collections.

There is no need to wrap collections in Optional. Moreover, don't put Optionals in collections. This only complicates things by adding pointless boxing and extra unwrapping. Don't add Optionals to collections. There is no visible benefit from this. Keep it simple and use Optional for missing values.

5. Don't chain for the sake of chaining

Optional.ofNullable(foo).ifPresent(value -> {
  //do something
})
Optional has detailed methods that can help with this. Instead of chain, a simple null check will suffice. I know Optional has good methods and good IDE support. You can use them.

6. Use primitive value wrappers

It's not a big problem, but you can use OptionalInt or OptionalLong . Simply by removing unnecessary generics, you will improve performance and write more concise code.

7. You should know about ofNullable

if (a==null){
  return Optional.empty();
} else {
  return Optional.of(a);
}
This type of code is usually written by developers who don't know about Optional#ofNullable . Most developers don't even understand the difference between ofNullable and of . They don't understand how Optional#of can backfire. Most would resort to ofNullable for fear of throwing a NullPointerException in Optional#of . Again, this defeats the purpose of these two methods. If we only use ofNullable , why do we need Optional#of at all ? Optional#of throws an NPE when you pass to null. This happens for a reason. This method should be used when you expect the value to be present. If it is not there, it will quickly fail. Optional#ofNullable converts null to an empty Optional. This method takes null as an argument, which matches an empty Optional.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION