<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nir Shafrir on Medium]]></title>
        <description><![CDATA[Stories by Nir Shafrir on Medium]]></description>
        <link>https://medium.com/@nir.shafrir?source=rss-478417ae25e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2ewDxjttYxHDC0TRy6gXNg.jpeg</url>
            <title>Stories by Nir Shafrir on Medium</title>
            <link>https://medium.com/@nir.shafrir?source=rss-478417ae25e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 20:09:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nir.shafrir/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Pre-Production Observability vs. Traditional APMs]]></title>
            <link>https://medium.com/javarevisited/pre-production-observability-vs-traditional-apms-6de761cc5690?source=rss-478417ae25e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6de761cc5690</guid>
            <dc:creator><![CDATA[Nir Shafrir]]></dc:creator>
            <pubDate>Tue, 10 Dec 2024 12:41:51 GMT</pubDate>
            <atom:updated>2024-12-11T15:05:26.004Z</atom:updated>
            <content:encoded><![CDATA[<p>The traditional approach to observability has focused heavily on production environments, emphasizing real-time monitoring to detect and resolve issues affecting live users. However, there’s a growing recognition that observability in pre-production environments offers a new and promising path to improve software quality and accelerate delivery.</p><p>By shifting the focus on finding issues earlier in the SDLC, teams can prevent problems rather than deal with their impact, validate system behavior more holistically, and address areas that are often overlooked in production-only observability.</p><p>Pre-Production Monitoring: Reducing the High Cost of Production Bugs.</p><h3>Cost of fixing Production Issues:</h3><p><strong>1. Teams spend 20–40% of their time on fixing production issues</strong>:</p><p>Preventing issues before they reach production is key to saving time and resources. Studies show teams spend <strong>20–40% of their time</strong> resolving production issues. Every issue prevented frees up team capacity and improves velocity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n9bBasmlMCr7RG-F.png" /><figcaption>Cost of fixing production</figcaption></figure><p><strong>2. Example of a 10% reduction in production issues</strong>:</p><ul><li>A 100-developer team spends 40% of its time on issue resolution.</li><li>Reducing production issues by 10% reclaims <strong>4% capacity</strong>, with an additional <strong>1.6% from reduced context-switching penalties</strong>.</li><li>Total reclaimed capacity: <strong>5.6%</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9MVGdqJPLCQs4pyS.png" /><figcaption>This chart illustrates the impact of a 10% reduction in production issues for a 100-developer team.</figcaption></figure><p>3. <strong>Direct team productivity gains for every 1% reduction in production issues</strong>:</p><ul><li>A team spending 25% of its time on production issues saves <strong>0.25% capacity per 1% improvement</strong>.</li><li>Preventing 20% of production issues equates to <strong>5% of reclaimed team capacity</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RDWs0iyUOo-w2Of0.png" /><figcaption>This line chart visualizes team productivity gains from reducing production issues. It shows:</figcaption></figure><h3>3 Ways Pre-Production Observability Improves Software Delivery, Quality, and Reduces Costs</h3><ol><li><strong>Reducing costs by detecting issues earlier</strong>:</li></ol><p>Fixing production bugs costs 6 times more than addressing them in pre-production, according to IBM. Higher costs of fixing bugs in production are due to several factors:</p><ul><li>Reduced team productivity</li><li>Operational Disruption</li><li>End user Impact</li><li>Revenue Loss from Production Issues</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gErtvRuD-iMDZt2i.png" /></figure><p>Source: IBM *The Systems Sciences Institute at IBM reported that it costs 6x more to fix a bug found during implementation than to fix one identified during design. Furthermore, according to IBM, the cost to fix bugs found during the testing phase could be 15x more than the cost of fixing those found during design.</p><p><strong>2. Making integration and e2e testing in pre-production more useful with tracing</strong></p><p>With pre-production observability R&amp;D teams can:</p><ul><li>Detect latency spikes, resource overloads, or hidden dependencies that might not break tests but cause issues later.</li><li>Ensure component interactions work as expected under realistic conditions.</li><li><a href="https://digma.ai/how-to-improve-test-coverage-with-tracing/">Increase test coverage with tracing:</a> by identifying gaps and creating more complete test <strong>cases.</strong></li></ul><p><strong>3. Assessing issues in application performance that traditional tests often miss but impact user experience.</strong></p><p>With pre-production observability R&amp;D teams can:</p><ul><li>Track latency, throughput, resource usage, and error rates during test runs, and detect deviations from expected performance levels.</li><li>Identify the root cause and origin of regressions, enabling faster resolution.</li><li>Simulate real-world conditions by validating performance under realistic or stress-test conditions.</li></ul><p>Here’s a comparison table highlighting the differences between Digma/Pre-Production Observability and Traditional APMs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*oNFuq6ED4a9dWjH_aW2brw.png" /></figure><h3>What is the Right Solution for Pre-Production Observability</h3><p>Digma was designed to address the unique challenges of pre-production observability by focusing on pre-production environments. It prioritizes developers, simplifies problem-solving, reduces costs, and helps teams confidently deliver high-quality software.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kWhCQ4n6ve-AaYWP" /></figure><p>With Digma, R&amp;D Teams Can:</p><h4>1. Get Predictive insights in pre-production environments</h4><p>Digma uses intelligent algorithms to analyze partial telemetry data and extrapolate how issues might manifest in production. It is designed to work effectively with the fragmented and incomplete data typical of testing, staging, and development phases.</p><ul><li>Proactive Issue Prediction: Digma identifies potential failure points and provides actionable insights during integration or performance testing.</li><li>Faster Feedback Loops: Developers can validate code changes in near real-time.</li></ul><h4>2. Focus on the root cause: Eliminate the noise</h4><p>Traditional observability tools overwhelm teams with raw telemetry data, creating cognitive and operational burdens. This delays resolution and diverts resources.</p><p>Digma eliminates this overhead by focusing on the following:</p><ul><li>Digma maps anomalies to specific code, commits, or functions for actionable fixes.</li><li>Digma automates debugging with curated insights to replace manual data analysis.</li><li>Digma filters irrelevant metrics, letting teams focus on solving problems instead of searching for them.</li></ul><h4>3. Reduce observability direct costs</h4><p>By specializing in pre-production observability, focusing on root causes, and avoiding the high infrastructure costs of traditional APMs, Digma directly reduces production issue costs in several ways:</p><p>Efficient data processing:</p><ul><li>Reduction in Telemetry Overhead:<strong> </strong>Digma processes telemetry on-the-fly, reducing infrastructure and operational costs. Unlike traditional APMs, Digma uses aggregated, relevant data to minimize costs.</li></ul><p>Preventing production issues:</p><ul><li>By identifying and addressing potential issues in pre-production, Digma reduces the number of costly production incidents.</li><li>Example: Preventing 10% of production issues in a 100-developer team can reclaim 5.6% of team capacity, allowing developers to focus on planned tasks rather than firefighting.</li></ul><p>Reducing (MTTR):</p><ul><li>Faster Debugging: Digma streamlines debugging by mapping issues to specific code, commits, or functions, cutting down investigation time.</li><li>Example: A 40% reduction in investigation time for a team spending 25% on production issues can reclaim 4% productivity.</li></ul><ol><li>Lowering Context-Switching Costs:</li></ol><ul><li>Digma decreases context-switching penalties, which can add 20–70% extra effort to planned tasks.</li></ul><h3>Conclusion</h3><p>Digma redefines what observability means for pre-production environments, addressing the core challenges of early issue detection, actionable insights, and cost-efficiency.<br>Digma enables R&amp;D teams to:</p><ul><li>Proactively prevent production issues before they occur.</li><li>Reduce the cognitive and operational burden of analyzing raw telemetry data.</li><li>Lower operational costs by avoiding expensive telemetry storage and data pipelines.</li><li>Deliver high-quality, production-ready software faster and more efficiently.</li></ul><p><a href="https://digma.ai/contact-us/">Start Now</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6de761cc5690" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/pre-production-observability-vs-traditional-apms-6de761cc5690">Pre-Production Observability vs. Traditional APMs</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ktor vs. Spring Boot: 5 Key Differences for Kotlin Devs]]></title>
            <link>https://medium.com/javarevisited/ktor-vs-spring-boot-5-key-differences-for-kotlin-devs-9c4406a4026f?source=rss-478417ae25e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c4406a4026f</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[ktor]]></category>
            <dc:creator><![CDATA[Nir Shafrir]]></dc:creator>
            <pubDate>Thu, 25 Jul 2024 09:18:58 GMT</pubDate>
            <atom:updated>2024-07-29T15:08:28.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*JdRKLv5sBju5SYFRK09Bdg.png" /><figcaption>Ktor, Spring and Digma</figcaption></figure><p>Hypothetically speaking, why would a Kotlin developer need Ktor if they could use Spring Boot, which is popular worldwide and they are very used to it? Although Ktor is flexible and lightweight for building asynchronous server-side web apps with fast start-up times and other cool features, they are accustomed to Spring Boot. So why should they make the move?</p><p>What I realized is that <strong>Comparisons against an established tool in the market are not entirely fair. And still, I can ask the same question: why should I choose Kotlin over Java?</strong></p><p>Still, I decided to ask experienced Java/Kotlin developer<a href="https://www.reddit.com/r/Kotlin/comments/19crdfa/in_a_good_way_as_a_kotlin_dev_asking_seriously/">s</a> about the benefits of using Ktor with Kotlin applications and create some sort of comparison.</p><p>In this article, we will explore the key differences between Ktor and Spring Boot for Kotlin developers based on the experience of various developers.</p><p>Disclaimer: If you feel there is some bias towards one framework or another, it wasn’t the intention.</p><p>The comparison in this blog criteria is based on the following 5 parameters:</p><ul><li>Performance</li><li>Async work/threading</li><li>Ecosystem</li><li>Developer Experience</li><li>Observability Capabilities</li></ul><h3>1. Performance</h3><h3>Snapiness</h3><p><strong>Ktor</strong> is built purely using Kotlin, which has a more concise syntax than Java. This design is simple, making it easier to write and maintain code.</p><pre>fun Application.module() {<br>  routing {<br>    get(&quot;/greet&quot;) {<br>      call.respondText(&quot;Hello, Ktor!&quot;)<br>    }<br>  }<br>}</pre><p>Ktor is built to be asynchronous from the ground up, all thanks to Kotlin’s coroutines. These features will make Ktor a good developer experience for developers looking for a lightweight framework that is modern and suited for modern architecture.</p><p><strong>Spring Boot </strong>might present a steep learning curve due to its “bloated” ecosystem, which can be overwhelming for beginners; this problem can be mitigated by its extensive documentation and community support.</p><pre>@SpringBootApplication<br>public class MySpringBootApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(MySpringBootApplication.class, args);<br>    }<br>}<br>@RestController<br>@RequestMapping(&quot;/greet&quot;)<br>public class GreetingController {<br>    @GetMapping<br>    public String greet() {<br>        return &quot;Hello, Spring Boot!&quot;;<br>    }<br>}</pre><p>Due to Spring Boot’s strong community support, it is a go-to for enterprise-level applications that need extensive integrations. Ktor, while boasting of its simplicity, may not offer the same level of integration due to its smaller ecosystem.</p><h3>Dependency injection</h3><p>I recommend Kolin for Dependency Injection. Works well with Ktor.</p><p><strong>Koin</strong> (for DI) is great to use with Ktor and can be used even for small projects or microservices.</p><p>My team moved from spring to targeted libraries about five years ago and hasn’t looked back. We don’t use Ktor, but other teams do, and the reasoning is the same.</p><ul><li>Easier upgrades since there aren’t interdependencies</li><li>There is no “magic”; the code you write is the code that is run.</li><li>The dependency tree is about 1/3rd the size of the same functionality</li><li>Startup time is instantaneous</li><li>Reasoning about any complex application is significantly easier as all the code being run is right there.</li></ul><pre>fun main() {<br>    startKoin {<br>        modules(appModule)<br>    }<br>    embeddedServer(Netty, port = 8080) {<br>        routing {<br>            get(&quot;/do-something&quot;) {<br>                val myService = get&lt;MyService&gt;()<br>                myService.doSomething()<br>                call.respond(HttpStatusCode.OK)<br>            }<br>        }<br>    }.start(wait = true)<br>}</pre><p>Spring Boot’s DI implementation is quite different and opinionated. Yes, the magic of auto-wiring in Spring Boot is cool; however, I have discovered that it has the potential to increase application loading times due to unnecessary dependencies.</p><h3>GraalVM</h3><p>Given that Ktor is a lightweight framework for developing asynchronous servers and microservices, it’s reasonable to assume that it could see improvements from GraalVM’s native-image tool, like Spring Boot, resulting in quicker startup times and possibly smaller deployment sizes.</p><p>Spring Boot’s memory footprint and startup time can be reduced to an extent because of GraalVM. However, your memory footprint using GraalVM on a Spring Boot project can not be compared to what you’ll get with Ktor. Memory footprint is something that is inconsequential when it is not a cloud-native project.</p><h3>2. Async work/threading</h3><h3>Coroutines / Virtual Threads</h3><p>Ktor fully uses Coroutines, which is good for highly concurrent code, event-based systems, and structured concurrency and cancellations.</p><p>Coroutines address the issues surrounding:</p><ul><li>Effortlessly writing parallel, non-blocking code without errors (structured concurrency)</li><li>Nesting callbacks to switch between threads can be replaced with synchronous code, resulting in code that is easier to read, write, and understand. A frequent scenario involves code needing to switch between performing UI tasks on a main thread, which cannot be interrupted, and carrying out blocking tasks on IO threads.</li></ul><pre>fun main() {<br>    embeddedServer(CIO, port = 8080, host = &quot;0.0.0.0&quot;, module = Application::module)<br>        .start(wait = true)<br>}<br>fun Application.module() {<br>    routing {<br>        get(&quot;/greet&quot;) {<br>            call.respondText(&quot;Hello, World!&quot;, ContentType.Text.Plain)<br>        }<br>        get(&quot;/async-greet&quot;) {<br>            // Launch a coroutine to simulate an asynchronous operation<br>            val greeting = asyncGreet()<br>            call.respondText(greeting, ContentType.Text.Plain)<br>        }<br>    }<br>}<br>suspend fun asyncGreet(): String = withContext(Dispatchers.Default) {<br>    delay(1000) // Simulate a long-running task<br>    &quot;Hello from Coroutine!&quot;<br>}</pre><p>Since Ktor has coroutines, which takes care of asynchronous task at the language level, virtual threads is an added advantage at the JVM level.</p><p>Spring Boot can leverage Virtual threads to tackle the problem of IO tasks, which typically block an OS thread throughout its execution. This approach fundamentally reduces the resources required for handling blocking, synchronous tasks, especially when dealing with extensive operations. Virtual threads operate at the JVM level, so they can be integrated seamlessly into a Spring Boot project.</p><pre>server:<br> port: 8080<br>spring:<br> application:<br>   name: digma-demo<br> threads:<br>   virtual:<br>     enabled: true<br>@RestController<br>@RequestMapping(&quot;api/v1/&quot;)<br>public class AppController {<br>   @Value(&quot;${spring.application.name}&quot;)<br>   private String appName;<br>   private final Logger LOGGER = LoggerFactory.getLogger(AppController.class);<br>   @GetMapping(&quot;hello&quot;)<br>   public String getValue(){<br>       LOGGER.info(&quot;Thread Info: {}&quot;, Thread.currentThread());<br>       String response = &quot;Hello World from : &quot;+ appName;<br>       LOGGER.info(&quot;Response: {}&quot;, response);<br>       return response;<br>   }<br>}</pre><h3>Request Response Handling</h3><p>Ktor enables you to manage incoming requests and send back responses within route handlers. Different actions can be carried out while managing requests:</p><p>Get request details, like headers, cookies, etc.</p><pre>routing {<br>    get(&quot;/&quot;) {<br>        val uri = call.request.uri<br>        call.respondText(&quot;Request uri: $uri&quot;)<br>    }<br>}</pre><p>Get values from the path parameters.</p><pre>get(&quot;/user/{login}&quot;) {<br>    if (call.parameters[&quot;login&quot;] == &quot;admin&quot;) {<br>        // ...<br>    }<br>}</pre><p>Retrieve body content such as data objects, form parameters, and files.</p><pre>post(&quot;/text&quot;) {<br>    val text = call.receiveText()<br>    call.respondText(text)<br>}</pre><p>Spring Boot handles request response in a way that is not seamless, i.e, you’ll have to write your own custom request response handler and then write a custom <em>ControllerAdvice</em> to really fine tune what you want.</p><pre>// ServiceResponse.java<br>@Data<br>public class ServiceResponse&lt;T&gt; {<br>    private T data;<br>    private boolean success = false;<br>    public ServiceResponse() {<br>    }<br>    public ServiceResponse(T data, boolean success) {<br>        this.data = data;<br>        this.success = success;<br>    }<br>    public void setData(T data, boolean success) {<br>        this.data = data;<br>        this.success = success;<br>    }<br>}</pre><pre>// ControllerAdvice<br>@Slf4j<br>@RestControllerAdvice<br>public class ControllerAdvice {<br>    private final MessageSource messageSource;<br>    public ControllerAdvice(MessageSource messageSource) {<br>        this.messageSource = messageSource;<br>    }<br>    @ResponseBody<br>    @ResponseStatus(HttpStatus.BAD_REQUEST)<br>    @ExceptionHandler(IllegalArgumentException.class)<br>    public ResponseEntity&lt;ServiceResponse&lt;String&gt;&gt; handleIllegalArgumentException(IllegalArgumentException ex) {<br>        return ResponseEntity.badRequest().body(new ServiceResponse&lt;&gt;(ex.getMessage(), false));<br>    }<br>    @ResponseBody<br>    @ResponseStatus(HttpStatus.BAD_REQUEST)<br>    @ExceptionHandler(HttpMessageNotReadableException.class)<br>    public ResponseEntity&lt;ServiceResponse&lt;String&gt;&gt; handleHttpMessageNotReadable(HttpMessageNotReadableException ex) {<br>        return ResponseEntity.badRequest().body(new ServiceResponse&lt;&gt;(ex.getMessage(), false));<br>    }<br>}</pre><h3>3. Ecosystem</h3><h3>Multiplatform</h3><p>Ktor, in conjunction with <a href="https://ktor.io/docs/client-supported-platforms.html">Kotlin Multiplatform</a> (KMP), is a library that allows you to share much of your networking code and business logic with other platforms such as Kotlin/JVM, Kotlin/Js, Android, iOS, watchOS, tvOS, macOS, Linus and Windows.</p><p>Spring Boot allows for the same functionality, but you’ll have to separate a lot of code and likely have a complex Gradle configuration.</p><h3>Maintenance — dependencies and configuration</h3><p>Ktor requires extensive manual configuration and setup because it does not rely on auto-configuration or component scanning. Developers must explicitly define and configure their application components, which can help them understand the application’s behavior and require more upfront effort. The lack of autoconfiguration or component scanning comes in handy when you don’t like the “magic” that takes place in Spring Boot.</p><p>Spring Boot, on the other hand, is known for auto-configuration and component scanning abilities, which significantly reduces the amount of manual configuration needed to set up a project. Developers who like a simpler project setup will find this functionality helpful.</p><h3>4. Developer Experience</h3><h3>Boilerplate</h3><p>Ktor boasts of being lightweight and not bringing any “magic” that comes with Spring Boot. Hence, to set up a project in Ktor, you’ll have to do a lot of manual configuration, leading to boilerplate code. That’s the trade-off you’ll have to deal with when working with Ktor.</p><pre>fun main() {<br>    embeddedServer(Netty, port = 8080) {<br>        routing {<br>            get(&quot;/&quot;) {<br>                call.respondText(&quot;Hello, world!&quot;, ContentType.Text.Plain)<br>            }<br>        }<br>    }.start(wait = true)<br>}</pre><p>Spring Boot provides numerous autoconfiguration classes that generate beans with default configurations, which come with a lot of <em>magic</em>, but this does not give the developer desired control from the onset.</p><pre>@SpringBootApplication<br>public class Application {<br>    public static void main(String[] args) {<br>        SpringApplication.run(Application.class, args);<br>    }<br>    @RestController<br>    public class HelloController {<br>        @GetMapping(&quot;/&quot;)<br>        public String helloWorld() {<br>            return &quot;Hello, world!&quot;;<br>        }<br>    }<br>}</pre><h3>Documentation</h3><p>Ktor is relatively new, so it has a smaller ecosystem and community, resulting in fewer resources and documentation than Spring Boot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OGE5ZujiPnjD87ek" /><figcaption>ktor docs</figcaption></figure><h3>Community</h3><p>Ktor is relatively new and has a smaller community than Spring Boot. However, it is growing rapidly, especially among developers who prefer Kotlin and seek a lightweight, asynchronous solution for modern web development. Ktor’s community is active and supportive, with many online resources, including forums, blogs, and GitHub repositories.</p><p>Spring Boot has a large and robust community because it has been around for over a decade. This means there are many third-party libraries, thorough documentation, and plenty of tutorials and guides. This large support system greatly benefits developers working on enterprise applications.</p><h3>5. Observability Capabilities</h3><p>Ktor has a plugin called the MicrometerMetrics plugin that integrates Micrometer metrics into your Ktor server app. This allows you to select your preferred monitoring platform, such as Prometheus, JMX, Elastic, etc. Ktor has built-in metrics to track HTTP requests and JVM performance by default. You can personalise these measures or create new ones.</p><p><a href="https://digma.ai/the-spring-way-of-doing-things-9-ways-to-improve-your-spring-boot-skills/">Spring Boot</a> has a starter called <em>spring-boot-starter-actuator; </em>this dependency gives important information about application internals through endpoints such as /actuator/health, /actuator/metrics, and /actuator/env. These endpoints provide detailed metrics, health status, and environmental properties of your application.</p><p><a href="https://digma.ai/the-spring-way-of-doing-things-9-ways-to-improve-your-spring-boot-skills/">Spring Boot</a> integrates well with OpenTelemetry. It supports agent instrumentation and Micrometer Tracing. you can check out this blog post: <a href="https://digma.ai/couch-to-fully-observed-code-with-spring-boot-3-2-micrometer-tracing-and-digma/">https://digma.ai/couch-to-fully-observed-code-with-spring-boot-3-2-micrometer-tracing-and-digma/</a></p><p>I have realized that no matter the web framework of choice, it is important to have observability. Digma with Ktor or Spring Boot will help you analyze your application runtime data. It detects issues as they appear, highlights potential issues in code and helps with code change <a href="https://digma.ai/why-static-analysis-cant-fix-performance-problems/">dynamic analysis</a> and context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FaxNlgd5zdk8D7qT" /><figcaption>Digma Dashboard</figcaption></figure><p>Digma not only collects observability data from your personal computer but also from production — the source of truth. Digma can leverage <a href="https://digma.ai/couch-to-fully-observed-code-with-spring-boot-3-2-micrometer-tracing-and-digma/">Micrometer’s</a> small footprint and the fact that it does not use reflection to collect observability data in production.</p><p>No matter the framework you choose, you will likely encounter errors that are difficult to trace or reproduce in a test environment. Using Digma with Ktor or Spring Boot will help you deal with database query issues and bottlenecks buried deep in your code and fix any scaling issues that you might encounter.</p><p>Observability plays an important role in the software development lifecycle across development, test, staging, and production stages. It can reveal crucial elements of your application’s behavior, pinpoint problems, and enhance your code. Enabling observability with Digma for your Ktor or Spring Boot application will give you helpful insights.</p><h3>Conclusion</h3><p>To round up, both frameworks offer significant benefits and are best suited for different use cases. Ktor offers a fresh take on web development akin to Spring Boot, and it appeals to those who want a web framework that is lightweight (not bloated), explicit, fast, and has a fast startup time. Meanwhile, Spring Boot remains the tried-and-tested framework for Java developers, as it appeals to those who want a robust and established ecosystem.</p><p>Choose your web framework carefully and it should be based on the needs of your project and embrace the enjoyable experience of building robust web applications! Digma not only collects observability data from your personal computer but also from production — the source of truth. Digma can leverage <a href="https://digma.ai/couch-to-fully-observed-code-with-spring-boot-3-2-micrometer-tracing-and-digma/">Micrometer’s</a> small footprint and the fact that it does not use reflection to collect observability data in production.</p><p>No matter the framework you choose, you will likely encounter errors that are difficult to trace or reproduce in a test environment. Using Digma with Ktor or Spring Boot will help you deal with database query issues and bottlenecks buried deep in your code and fix any scaling issues that you might encounter.</p><p>Observability plays an important role in the software development lifecycle across development, test, staging, and production stages. It can reveal crucial elements of your application’s behavior, pinpoint problems, and enhance your code. Enabling observability with Digma for your Ktor or Spring Boot application will give you helpful insights.</p><h3>Conclusion</h3><p>To round up, both frameworks offer significant benefits and are best suited for different use cases. Ktor offers a fresh take on web development akin to Spring Boot, and it appeals to those who want a web framework that is lightweight (not bloated), explicit, fast, and has a fast startup time. Meanwhile, Spring Boot remains the tried-and-tested framework for Java developers, as it appeals to those who want a robust and established ecosystem.</p><p>Choose your web framework carefully and it should be based on the needs of your project and embrace the enjoyable experience of building robust web applications! Digma not only collects observability data from your personal computer but also from production — the source of truth. Digma can leverage <a href="https://digma.ai/couch-to-fully-observed-code-with-spring-boot-3-2-micrometer-tracing-and-digma/">Micrometer’s</a> small footprint and the fact that it does not use reflection to collect observability data in production.</p><p>No matter the framework you choose, you will likely encounter errors that are difficult to trace or reproduce in a test environment. Using Digma with Ktor or Spring Boot will help you deal with database query issues and bottlenecks buried deep in your code and fix any scaling issues that you might encounter.</p><p>Observability plays an important role in the software development lifecycle across development, test, staging, and production stages. It can reveal crucial elements of your application’s behavior, pinpoint problems, and enhance your code. Enabling observability with Digma for your Ktor or Spring Boot application will give you helpful insights.</p><h3>Conclusion</h3><p>To round up, both frameworks offer significant benefits and are best suited for different use cases. Ktor offers a fresh take on web development akin to Spring Boot, and it appeals to those who want a web framework that is lightweight (not bloated), explicit, fast, and has a fast startup time. Meanwhile, Spring Boot remains the tried-and-tested framework for Java developers, as it appeals to those who want a robust and established ecosystem.</p><p>Choose your web framework carefully and it should be based on the needs of your project and embrace the enjoyable experience of building robust web applications! <a href="https://plugins.jetbrains.com/plugin/19470-digma-continuous-feedback">Digma</a> supports both Ktor and Spring Boot and we love both. Try it for yourself:</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c4406a4026f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/ktor-vs-spring-boot-5-key-differences-for-kotlin-devs-9c4406a4026f">Ktor vs. Spring Boot: 5 Key Differences for Kotlin Devs</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices for Integration Testing In Java]]></title>
            <link>https://medium.com/javarevisited/best-practices-for-integration-testing-in-java-287715448355?source=rss-478417ae25e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/287715448355</guid>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Nir Shafrir]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 06:52:45 GMT</pubDate>
            <atom:updated>2024-04-23T06:52:45.789Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*j2MYJvjnrFZoSMtl-vuANQ.png" /></figure><p>Recently, I was looking to introduce robust integration testing to my company. Specifically working in Java with an SQL environment, I started exploring frameworks, tools, and approaches for integration tests and I wanted to share my journey around Java Integration testing.</p><p>So, I started researching features and characteristics to help me efficiently build out scalable integration testing env. I realized it depends on what kind of <a href="https://www.atomicjar.com/2023/10/beyond-pass-fail-a-modern-approach-to-java-integration-testing/">integration tests </a>I want to run.</p><p>In Java, there are narrow integration tests, which basically are unit tests that touch classes that communicate with the application’s I/O in some way. For these tests, I use TestContainers combined with the normal unit test framework.</p><p>The other, and more complicated, approach is wide integration testing. When you have multiple systems passing calls and messages to each other. Some sort of E2E kind of solution, just not necessarily the entire solution. What is appropriate here highly depends on the specific solution.</p><p>If I have a lot of services/systems I’d also question whether wide integration testing is the appropriate way to go. These kinds of tests require a lot of maintenance and are generally only used for the most critical of flows. What is more common, especially in a microservice environment, is the combination of narrow integration tests, system tests, and contract tests — and the combination of these three levels of testing provides you with a high degree of certainty when making changes.</p><p>For unit, narrow integration tests, and system tests, I usually <a href="https://www.docker.com/blog/shorter-feedback-loops-developing-java-apps-with-digmas-free-docker-extension/">containerize</a> everything and make it all executable during build on local machines and in pipelines. Shorter the feedback loop the better (also, debugging is easier when you can run it locally).</p><p>If you’re aiming for readability by technical people, consider using frameworks like <a href="https://cucumber.io/">Cucumber </a>or Fitnesse. These tools provide a high-level overview of test functionality, making it accessible to non-developers as well. If the tests are meant for developers, consider using the regular <strong>unit test framework</strong>. This approach allows developers to write tests like they are used to.</p><p>As far as I know, there’s no silver bullet framework and no specific approach. There’s so much depending on the specific system at hand: but there are some cool tools and habits you could adopt to better succeed in integration testing.</p><h3>So, what is Integration Testing in simple words?</h3><p>Integration is a very loaded term. By definition, it’s how two independent things work together.</p><p>Unit testing tests code in isolation, meaning any API call, database call, and any call to a different module are all mocked out. Integration is testing that code without the mocks to see how they work together.</p><p>Integration testing is testing how two service classes interact.</p><p>Integration testing is testing how a service interacts with a datastore.</p><p>Integration testing is testing how the UI responds to the back end.</p><p>There are several more examples, just know it’s how two things work together. Essentially any test that’s not a unit test is an integration test by pure definition. We use other terms to specify what type of integration test it is, like contract test, API test, acceptance test, etc.</p><p>You can check out this talk by Naresh Jain. He talks about every layer in the test pyramid (including integration) and gives examples.</p><p>I’ve timestamped it for when he talks specifically about integration:</p><p><a href="https://youtu.be/ApQgaqafdR8">https://youtu.be/ApQgaqafdR8</a></p><p>So as you can see, the Integration test is a broad term and it will depend on the context of your project. I really like Martin’s post about the test pyramid that includes different types of integration test scenarios. You folks probably know it: <a href="https://martinfowler.com/articles/practical-test-pyramid.html">https://martinfowler.com/articles/practical-test-pyramid.html</a></p><h3>When planning Integration Testing, consider:</h3><ul><li>When should the test run? During build? Pipeline? In its own environment? All of the above?</li><li>Should developers be able to run these tests locally?</li><li>Does the business need to understand the tests?</li><li>What will the developers be comfortable writing? Will they accept something like Cucumber or are they more prone to embrace something they already know?</li></ul><h3>Best Practices for Integration Testing in Java</h3><ol><li>Separation of concerns</li><li>Use Insightful Names for Test Package</li><li>Use Insightful Names for Test Cases</li><li>Expected vs Actual</li><li>Write Simple Test Cases</li><li>Use Appropriate Assertions</li><li>Test Production Scenarios</li><li>Avoid Code Redundancy</li><li>Make use of Annotations</li><li>Make Use of Continuous Feedback</li><li>Test behavior and not implementation</li></ol><h3>1. Separation of concerns</h3><p><a href="https://www.baeldung.com/java-unit-testing-best-practices">It is good practice</a> to keep the test classes separate from the main source code. This way, tests can be written, executed, and managed independently of the code that runs in production.</p><p>Additionally, keeping your test and source codes separate helps prevent the chance of executing test codes in the production environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Ohr240L0g9ACt9HS" /></figure><p>You also have the option to mimic the actions of build tools like Maven and Gradle, which search for test implementations in the src/main/test directory.</p><h3>2. Use Insightful Names for Test Packages</h3><p>It is important to use an insightful package naming strategy in the src/main/test directory for test classes to enhance the test code’s readability and maintainability.</p><p>In other words, the names used for the test class package should align with the source class’s package that it will be testing.</p><p>If the Todo class is located in the com.digma.task package, then the TodoTest class should also be in the com.digma.task package within the src/main/test directory structure.</p><h3>3. Use Insightful Names for Test Cases</h3><p>Test names should provide clear insight into the test’s behavior and expectations for users when they look at the name of the test.</p><p>For instance, an integration test named testCreate is vague as it provides little insight into the test scenario or expectation.</p><p>Hence, it is important to give test names based on the action and expected outcome, like<br>testPersonWithCreationRequestThatReturnsCreated, and<br>testPersonWithUpdateRequestThatReturnsUpdated</p><p>You can still improve on the way we name our test cases; for better readability, you can name them using the <strong>given_when_then</strong> convention.</p><p>givenValidPersonRequest_whenCreatePerson_thenPersonIsCreated()<br>givenValidPersonRequest_whenUpdatePerson_thenPersonIsUpdated()</p><pre>@MicronautTest<br>public class IntegrationTests {<br><br>    @Inject<br>     private PersonClient client;<br><br>    @Test<br>    public void givenValidPersonRequest_whenCreatePerson_thenPersonIsCreated() {<br>        // given<br>        var requestDto = new PersonRequestDto(&quot;John&quot;,&quot;Smith&quot;,&quot;jsmith@codaholic.com&quot;);<br><br>        // when<br>        var response = client.create(requestDto);<br>        var person = response.body();<br><br>        // then<br>        Assertions.assertEquals(HttpStatus.CREATED, response.getStatus());<br>    }<br>}</pre><p>From the code snippet above, our code blocks are described in the Given, When, and Then format. This will help divide the test into three segments: input, action, and output.</p><p>The code block for the specified section initializes the test objects, simulates the data, and organizes the input.</p><p>Following this, the code block within the when section denotes a particular action or test case.</p><p>Similarly, the following section demonstrates the code’s results and compares them with the expected outcome using assertions.</p><h3>4. Expected vs Actual</h3><p>A test case requires having a statement that compares the expected and actual values.</p><p>In order to confirm the concept of anticipated versus real values, we can examine the definition of the assertEquals method in JUnit 5’s Assert class.</p><p>public static void assertEquals(Object expected, Object actual)</p><p>Let us utilize the assertion within one of our test cases.</p><pre>@MicronautTest<br>public class IntegrationTests {<br>    @Inject<br>     private PersonClient client;<br>    @Test<br>    public void testCreate() {<br>        var requestDto = new PersonRequestDto(&quot;John&quot;, &quot;Smith&quot;, &quot;jsmith@codaholic.com&quot;);<br>        var response = client.create(requestDto);<br>        var person = response.body();<br>        Assertions.assertEquals(HttpStatus.CREATED,  response.getStatus());<br>    }<br>}</pre><h3>5. Write Simple Test Cases</h3><p>Write test cases that are very transparent and straightforward. They need to be precise and succinct.</p><p>The main objective of every software project is to develop test cases that align with customer needs and are user-friendly and simple to operate. As a software engineer, you must consider the perspective of the end-user when writing test cases.</p><p>It is necessary to write a simple test scenario that validates an expected value against the actual one.</p><p>While it may be necessary to include logic in a test case, it’s important not to go overboard. Furthermore, you should avoid incorporating production logic in a test case in order to successfully pass the assertions.</p><h3>6. Use Appropriate Assertions</h3><p>Make sure to always use appropriate assertions to confirm the accuracy of the actual results compared to the expected results. You need to use different techniques provided in the Assert class of JUnit 5 or comparable frameworks like AssertJ.</p><p>For example, we have utilized the Assert.assertEquals method for asserting values already. In the same way, you can utilize assertNotEquals to verify that the anticipated and real values are not the same.</p><p>Other techniques like assertNotNull, assertTrue, and assertNotSame come in handy for various assertions.</p><p>7. Test Production Scenarios</p><p>Writing tests while keeping real-world scenarios in mind makes unit testing more rewarding.</p><p>Mainly, it assists in making your integration tests easier to understand. Additionally, it is crucial for comprehending the code’s behavior in <a href="https://blog.codepipes.com/testing/software-testing-antipatterns.html">specific production scenarios</a>.</p><p>One major way to test production scenarios is to test behavior rather than implementation. This particular concept is discussed at length in point 11 below.</p><p>8. Avoid Code Redundancy</p><p>Develop additional helper functions to produce frequently used objects and simulate data or external services for comparable unit testing.</p><p>Similar to other best practices, this improves the readability and manageability of the test code.</p><h3>9. Make Use of Annotations</h3><p>Frequently, testing frameworks offer annotations for different reasons like setting up, running code beforehand and cleaning up after a test has been executed.</p><p>Different annotations like JUnit 5’s @Before, @BeforeClass, @After, and @Order, as well as those from other testing frameworks like TestNG, can be used.</p><p>You need to utilize annotations to set up the system for testing by generating data, organizing objects, and deleting everything after each test in order to maintain isolation between test cases.</p><h3>10. Make use of Continuous Feedback</h3><p>Sadly, test passes can be deceptive. When we only focus on whether tests pass or fail, we disregard the complete insights they provide about our code and the system being tested.</p><p>One tool that takes you beyond the<a href="https://digma.ai/java-integration-testing/"> pass/fail results</a> of your tests is Digma. It is a free tool that analyzes code by examining observability data of this kind. This basic IDE plugin operates on your computer, handles all the complexities of OTEL, and gathers and analyzes metrics and traces. Digma can be configured by adding it to the IDE through the<a href="https://plugins.jetbrains.com/plugin/19470-digma-continuous-feedback"> plugin marketplace</a>.</p><p>Now, when you execute your integration or end-to-end tests within the IDE, Digma will detect this automatically to enhance observability for every test scenario. If the Observability Toggle is activated, Digma will enclose every test in a tracing mechanism and start evaluating the assets that were accessed and their performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/0*53FeeWxZO6MXz_Z2" /></figure><p>If you are interested in learning more about exactly what is going on, the tracing integration allows you to drill into the anatomy of the requests simulated by the tests to understand exactly what is going on and what could be wrong:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*UGVu515L8aLRvk9x" /></figure><p>Below is a typical test that passed; however, when you examine the code, you’ll see that the test result analysis has already uncovered some problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/0*s39wKb-dLGsI4EkJ" /></figure><p>Executing your integration tests only will not allow you to see potential <a href="https://digma.ai/how-to-optimize-slow-sql-queries/">SQL query issues</a>. However, running your integration tests with Digma comes with the benefit of seeing a score for the performance impact of every query. This allows you to consider your SQL query optimization choices not only based on the seriousness of the issue but also taking into account their usage and impact on your system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/0*_f4HetJjzJiQZBHt" /></figure><p>Continuous Feedback does not collect new data; it simply monitors the observability data stream (generated from your integration tests) to identify any critical information that should be noticed early.</p><p>One of Digma’s great points is that it establishes a two-way connection for every test asset, linking it with a database query, endpoint, code location, or consumer. At the testing stage, you can pinpoint problems and analyze system data within the testing environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*fm6-2Nc2KkRpoY2J" /></figure><h3>11. Test behavior and not implementation</h3><p>In practice, testing behavior is preferred over testing implementation. For what reason? The key is to ensure that your tests remain robust, flexible, and maintainable. Focusing on the “what” rather than the “how” ensures that these tests stay unchanged even when the code is altered, serving as a reliable safety measure.</p><p>Tests written to test code behavior are simpler to understand as they serve as code samples showcasing the various ways your class’s methods can be utilized, making it possible for even those unfamiliar with the implementation to understand how to use the class by reading through the tests.</p><p>Testing behavior will also help you consider how to hide implementation details and only reveal necessary information for users to utilize your services efficiently. This enables you to develop robust contracts and tight interfaces.</p><p>One way to ensure that you are testing behavior and not implementation is to</p><ul><li>Test the public API of a package, not classes, methods, or technical details.</li><li>Make sure that your test is focused on use cases or user stories.</li><li>When refactoring an implementation, use tests to ensure the expected results are still produced. Tests guarantee the anticipated outcome or behavior.</li></ul><p>There are numerous instances in which testing implementation specifics is necessary (such as verifying that your code reads from a cache and not a datastore), but this practice should be minimized as tests ideally should not rely on implementation details in most cases.</p><h3>Final Thought</h3><p>Integration testing in Java is a broad term and it will depend on the context of your project. It is not really about frameworks but more about processes, approaches, and your great habits.</p><p>Get Digma: <a href="https://plugins.jetbrains.com/plugin/19470-digma-continuous-feedback">Here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=287715448355" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/best-practices-for-integration-testing-in-java-287715448355">Best Practices for Integration Testing In Java</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6 Tips for Resolving Common Java Performance Problems]]></title>
            <link>https://medium.com/javarevisited/6-tips-for-resolving-common-java-performance-problems-b88f42dc6118?source=rss-478417ae25e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b88f42dc6118</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Nir Shafrir]]></dc:creator>
            <pubDate>Wed, 06 Mar 2024 15:48:09 GMT</pubDate>
            <atom:updated>2024-03-06T15:48:09.742Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*KGKa1rvbttCidH5xVRGugw.png" /></figure><p>Over the past year, one of our projects has experienced remarkable growth tt. I’m not complaining scaling is a good thing, but along the scaling process, as with any software product, we’ve encountered challenges, particularly in terms of performance, as we’ve scaled up.</p><p>Scaling this project can be exhilarating, but has also come with a set of performance issues that demanded our attention. Some of these challenges included resource utilization bottlenecks, occasional memory leaks, and inefficient database access, among others.</p><p>In an effort to share our experiences and contribute to the collective knowledge of the Java community. I’ve put together an article outlining some valuable tips and insights. I used <a href="https://digma.ai/">Digma</a> (CF) to instrument and resolve the performance issues we faced during our scaling process. You can also use tools like JMH, and profilers, to measure performance and find hotspots, respectively, to find where you need to optimize. I believe that by sharing these learnings, we can help others navigate similar challenges more smoothly.</p><h3>A brief overview of Java performance problems</h3><p>Don’t get me wrong, Java is a great programming language, but just like any other language, there are inherent challenges that you may encounter as a Java developer. It’s important to note that these challenges don’t diminish the value of Java but underscore the need for you, as a developer, to be aware of potential pitfalls.</p><p>These challenges, often manifested as performance issues, require careful consideration and proactive strategies for optimization. While Java’s strengths lie in its platform independence, robust libraries, and extensive ecosystem, addressing performance concerns is key to fully harnessing its capabilities.</p><p>While these challenges highlight the need for careful consideration, they also emphasize</p><p>some of the benefits that you can get from optimizing your Java applications. It is also important to note that performance optimization is not a one-off process but rather a process that begins during development, continues through testing and deployment, and remains throughout the application’s lifecycle.</p><p>Here’s a short list of considerations from a Reddit post by <a href="https://www.reddit.com/user/karianna/">Martijn Verburg</a>, Principal Engineering Group Manager (Java &amp; Golang) at Microsoft. You should keep in mind when trying to optimize your Java applications.</p><ol><li>Methodology.</li></ol><p>Choose a performance diagnostic model such as Kirk Pepperdine’s Java Performance Diagnostic Model, Brendan Gregg’s USE, or Monica Beckwith’s Top-Down. Without a structured approach, optimization efforts may lack direction.</p><ol><li>Performance Goals (SLA/SLO).</li></ol><p>Clearly define performance goals, such as achieving a minimum of 1000 transactions per second with a latency of less than or equal to 500 milliseconds at P999 on a Standard_DS_v4 VM.</p><ol><li>App Architecture.</li></ol><p>Develop a comprehensive understanding of both logical and physical application architecture.</p><ol><li>Timeboxing / Time Budgeting / Observability.</li></ol><p>Implement timeboxing or time budgeting strategies. For example, understand the breakdown of round-trip times, such as ~200ms in JavaScript, 400ms in the JVM, and 300ms in the database. Incorporate observability for insights.</p><ol><li>Math and statistical techniques:</li></ol><p>Apply mathematical and statistical techniques, including P99 latency curves, baselining, sampling, and smoothing, to gain a nuanced understanding of performance metrics.</p><ol><li>Understanding of technology stack.</li></ol><p>Familiarize yourself with how each layer of the technology stack (JVM, CPU, Memory, O/S, Hypervisors, Docker, K8s) interacts. Understand how each layer surfaces key performance metrics to the next.</p><p>JVM Understanding.</p><p>Deepen your knowledge of JVM internals, including garbage collection (GC), Just-In-Time (JIT) compilation, Java Memory Model (JMM), and related concepts.</p><p>Tools and Tactics.</p><p>Stay updated on tools and tactics, as this landscape evolves. Explore load testing, observability tooling for timeboxing, resource monitoring, and diagnostic tooling. Utilize tools like JFR/JMC, GCToolkit, and others for effective performance analysis.”</p><h3>6 Common Java performance problems</h3><h3>1. Memory leaks</h3><p>One would ask how this is possible when Java has automatic memory management through its garbage collector. Indeed, Java’s garbage collector is a powerful tool designed to handle memory allocation and deallocation automatically, relieving us from the burden of manual memory allocation and deallocation. However, relying solely on automatic memory management does not guarantee immunity from performance challenges.</p><p>The garbage collector (GC) in Java automatically identifies and reclaims memory that is no longer in use, which is an essential aspect of the language’s robust memory management system.</p><p>However, even with these advanced mechanisms, it’s still possible for even the most skilled programmers to encounter and inadvertently introduce Java memory leaks. A memory leak occurs when objects are unintentionally retained in memory, preventing the garbage collector from reclaiming the associated memory. Over time, this can lead to increased memory consumption and degrade the application’s performance.</p><p>Memory leaks can be tricky to detect and resolve mostly because of their overlapping symptoms. In our case, it was the most obvious of the symptoms: the <strong>OutOfMemoryError</strong> heap error, which was followed by performance degradation over a period of time.</p><p>There are many issues that can cause a memory leak in Java. Our first approach was to establish whether this was normal memory exhaustion(due to poor design) or a leak by analyzing the out-of-memory error message.</p><p>We started off by checking the most likely culprits, static fields, collections, and large objects declared as static and potentially blocking vital memory throughout the application’s lifetime.</p><p>For instance, in the code example below, removing the static keyword when initializing the list drastically reduces memory usage.</p><pre>public class StaticFieldsMemoryTestExample {<br>    public static List&lt;Double&gt; list = new ArrayList&lt;&gt;();<br>    public void addToList() {<br>        for (int i = 0; i &lt; 10000000; i++) {<br>            list.add(Math.random());<br>        }<br>        Log.info(&quot;Debug Point 2&quot;);<br>    }<br>    public static void main(String[] args) {<br>        new StaticFieldsDemo().addToList();<br>    }<br>}</pre><p>Other measures we took include checking for open resources or connections that may block the memory, thus keeping them out of the reach of the garbage collector. Improper implementations of the equals() and hashCode() methods by writing proper overridden methods for the equals() and hashCode() methods, especially in HashMaps and HashSets. Here is an example of properly implementing equals() and hashCode() methods.</p><pre>public class Person {<br>    public String name;<br>    <br>    public Person(String name) {<br>        this.name = name;<br>    }<br>    <br>    @Override<br>    public boolean equals(Object o) {<br>        if (o == this) return true;<br>        if (!(o instanceof Person)) {<br>            return false;<br>        }<br>        Person person = (Person) o;<br>        return person.name.equals(name);<br>    }<br>    <br>    @Override<br>    public int hashCode() {<br>        int result = 17;<br>        result = 31 * result + name.hashCode();<br>        return result;<br>    }<br>}</pre><h4>Tips to Prevent Memory Leaks</h4><ul><li>If your code uses external resources such as file handles, database connections, or network sockets, make sure to release them explicitly when they are no longer needed.</li><li>Employ memory profiling tools, such as VisualVM or YourKit, to analyze and identify potential memory leaks in your application.</li><li>When using singletons use lazy loading instead of eager loading to avoid unnecessary resource allocation until the singleton is actually needed.</li><li>If your code uses external resources such as file handles, database connections, or network sockets, make sure to release them explicitly when they are no longer needed.</li></ul><h3>2. Thread deadlocks</h3><p>Java is a multithreaded language. This is one of the features that make Java a suitable programming language, especially for developing enterprise applications that handle multiple tasks concurrently.</p><p>As the name multithreaded suggests, multiple threads are involved, and each is the smallest execution unit. Threads are independent and have a separate path of execution such that an exception in one of the threads does not affect the other thread.</p><p>But what happens when threads try to access the same resources(locks) all at once? This is when a deadlock occurs. I have had this experience collaborating on a real-time financial data processing system. In this project, we had multiple threads responsible for fetching data from external APIs, performing complex calculations, and updating a shared in-memory database.</p><p>As the usage of this tool grew, we started experiencing occasional reports of occasional freezes. The thread dumps revealed that certain threads were stuck in a waiting state, forming a circular dependency on locks.</p><p>In this example, we have two threads (thread1 and thread2) that attempt to acquire two locks (lock1 and lock2) in a different order. This introduces circular waiting, increasing the possibility of a deadlock.</p><pre>public class DeadlockExample {<br>    private static final Object lock1 = new Object();<br>    private static final Object lock2 = new Object();<br>    public static void main(String[] args) {<br>        Thread thread1 = new Thread(() -&gt; {<br>            synchronized (lock1) {<br>                System.out.println(&quot;Thread 1: Holding lock 1&quot;);<br>                // Introducing a delay to increase the likelihood of deadlock<br>                try {<br>                    Thread.sleep(100);<br>                } catch (InterruptedException e) {<br>                    e.printStackTrace();<br>                }<br>                synchronized (lock2) {<br>                    System.out.println(&quot;Thread 1: Holding lock 1 and lock 2&quot;);<br>                }<br>            }<br>        });<br>        Thread thread2 = new Thread(() -&gt; {<br>            synchronized (lock2) {<br>                System.out.println(&quot;Thread 2: Holding lock 2&quot;);<br>                // Introducing a delay to increase the likelihood of deadlock<br>                try {<br>                    Thread.sleep(100);<br>                } catch (InterruptedException e) {<br>                    e.printStackTrace();<br>                }<br>                synchronized (lock1) {<br>                    System.out.println(&quot;Thread 2: Holding lock 2 and lock 1&quot;);<br>                }<br>            }<br>        });<br>        thread1.start();<br>        thread2.start();<br>    }<br>}</pre><p>To solve this problem, we can refactor the code to ensure that threads always acquire locks in a consistent order. We can achieve this by introducing a global ordering of locks and ensuring that all threads follow the same order.</p><pre>public class DeadlockSolution {<br>    private static final Object lock1 = new Object();<br>    private static final Object lock2 = new Object();<br>    public static void main(String[] args) {<br>        Thread thread1 = new Thread(() -&gt; {<br>            synchronized (lock1) {<br>                System.out.println(&quot;Thread 1: Holding lock 1&quot;);<br>                // Introducing a delay to increase the likelihood of deadlock<br>                try {<br>                    Thread.sleep(100);<br>                } catch (InterruptedException e) {<br>                    e.printStackTrace();<br>                }<br>                synchronized (lock2) {<br>                    System.out.println(&quot;Thread 1: Holding lock 2&quot;);<br>                }<br>            }<br>        });<br>        Thread thread2 = new Thread(() -&gt; {<br>            synchronized (lock1) {<br>                System.out.println(&quot;Thread 2: Holding lock 1&quot;);<br>                // Introducing a delay to increase the likelihood of deadlock<br>                try {<br>                    Thread.sleep(100);<br>                } catch (InterruptedException e) {<br>                    e.printStackTrace();<br>                }<br>                synchronized (lock2) {<br>                    System.out.println(&quot;Thread 2: Holding lock 2&quot;);<br>                }<br>            }<br>        });<br>        thread1.start();<br>        thread2.start();<br>    }<br>}</pre><h4>Tips to prevent thread deadlocking</h4><ul><li>Lock ordering — Ensure that all threads follow the same order when acquiring locks to prevent circular waiting.</li><li>Implement a lock timeout — If a thread cannot acquire a lock within a specified time, release all acquired locks and retry.</li><li>Avoid nested locking — Avoid acquiring locks within critical sections</li><li><strong>Tips to prevent thread deadlocking.</strong></li><li>Lock ordering — Ensure that all threads follow the same order when acquiring locks to prevent circular waiting.</li><li>Implement a lock timeout — If a thread cannot acquire a lock within a specified time, release all acquired locks and retry.</li><li>Avoid nested locking — Avoid acquiring locks within critical sections where other locks are already held. Nested locking increases the risk of deadlocks.</li></ul><h3>3. Excessive garbage collection</h3><p>Garbage collection in Java is like the behind-the-scenes hero that manages memory for us. It automatically cleans up objects that are no longer needed, making our lives as developers a lot easier. While this automatic garbage collection provides convenience to developers, it can come at the cost of CPU cycles devoted to garbage collection which can affect application performance.</p><p>Apart from the typical out-of-memory error, you may experience occasional application freezes, lags, or application crashes. And if you’re using the cloud optimizing your garbage collection process could save you lots of computing costs. A case example is a company called <a href="https://www.uber.com/en-KE/blog/how-we-saved-70k-cores-across-30-mission-critical-services/">Uber that was able to save 70K Cores Across 30 Mission-Critical Services</a> by using a highly effective, low-risk, large-scale, semi-automated Go garbage collection tuning mechanism.</p><h4>Tips to prevent excessive garbage collection</h4><ul><li>Log Analysis &amp; Tuning — Identify patterns such as full garbage collection cycles or long pause times.</li><li>Evaluate and switch between different garbage collection algorithms. Consider JDK algorithms like Serial, Parallel, G1, Z GC, etc.</li><li>Choose an algorithm based on your application’s workload and performance characteristics. Switching to a more suitable GC algorithm can reduce CPU consumption.</li><li>Optimize code to reduce excessive object creation. You can use memory profiling tools like HeapHero or YourKit to identify areas generating excessive objects. Implement object pooling to reuse objects and reduce allocation overhead.</li><li>Modify heap size to impact CPU consumption during garbage collection. Consider Increasing heap size to reduce the frequency of collection cycles or decreasing the heap size for applications with a low memory footprint.</li><li>If you are running on the cloud, consider distributing the workload across multiple instances. You can increase the number of container instances or EC2 instances to better utilize resources and reduce strain on individual instances.</li></ul><h3>4. Bloated Libraries and Dependencies</h3><p>Build tools like Maven and Gradle have revolutionized the way we manage dependencies in Java projects. These tools provide a streamlined way to include external libraries and simplify the process of project configuration. However, with this convenience comes the risk of bloated libraries and dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BEicQyBoUDS7wP3X" /></figure><p>There is even a whole study published back in 2021 revealing that there are dependencies packaged with the application’s compiled code that are actually not necessary to build and run the application. You can find the paper <a href="https://link.springer.com/article/10.1007/s10664-020-09914-8#:~:text=Bloated%20dependencies%20are%20libraries%20that,build%20and%20run%20the%20application.">here</a>.</p><p>Software projects have a tendency to grow quickly as a result of bug fixes, new features, and new dependencies. Sometimes, projects can grow out of proportion and exceed our ability as developers to effectively maintain them. They can also introduce security vulnerabilities and additional performance overhead.</p><p>If you’re in this situation, I’d advocate looking into ways that you can debloat your application of unused dependencies and libraries as one of the remedies.</p><p>There are several tools within the Java ecosystem that I have found used for managing dependencies. Some of the most common ones include the <a href="https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-dependency-plugin">Maven dependency plugin</a> and the <a href="https://github.com/gradle-dependency-analyze/gradle-dependency-analyze">Gradle dependency analysis plugin</a>, which are pretty good at detecting unused dependencies, used transitive dependencies (which you may want to declare directly), and dependencies declared on the wrong configuration (API vs implementation vs compileOnly, etc.).</p><p>You can also leverage other tools like Sonarqube and JArchitect. Some modern IDEAS such as Intellij, also have decent dependency analysis capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/0*_sPst868ZKukLWeb" /></figure><h4>Tips to prevent bloated dependencies in Java</h4><ul><li>Dependency auditing — Perform regular audits to identify unused or obsolete libraries. Tools like the Maven Dependency Plugin or Gradle’s dependencyInsight can assist in dependency analysis.</li><li>Version control — Keep dependencies up-to-date. Utilize version control systems to track changes in dependencies and manage updates systematically.</li><li>Dependency scopes — Leverage dependency scopes (compile, runtime, test, etc.) effectively. Minimize the number of dependencies in the compile scope to reduce the size of the final artifact.</li></ul><h3>5. Inefficient Code</h3><p>No developer sets out to write inefficient or suboptimal code intentionally. However, despite the best intentions, inefficient code can find its way into production for various reasons. It might result from tight project deadlines, limited understanding of the underlying technologies, or evolving requirements that force developers to prioritize functionality over optimization.</p><p>Inefficient example</p><pre>String result = &quot;&quot;;<br>for (int i = 0; i &lt; 1000; i++) {<br>   result += &quot;example&quot;;<br>}</pre><p>Improved example</p><pre>StringBuilder sb = new StringBuilder();<br>for (int i = 0; i &lt; 1000; i++) {<br>   sb.append(&quot;example&quot;);<br>}<br>String result = sb.toString();</pre><p>Inefficient code can lead to increased memory consumption, longer response times, and decreased overall system efficiency. Ultimately, inefficient code can degrade user experience, increase operational costs, and limit application scaling to handle increased loads.</p><p>Getting rid of inefficient code starts with identifying patterns that indicate inefficiency. Some of the patterns I’m always on the lookout for include nested loops without proper exit conditions, unnecessary object creation and instantiation, excessive synchronization, inefficient database queries, and many more.</p><h4>Tips to help you write efficient Java code</h4><ul><li>Refactor and modularize your code to avoid unnecessary duplication</li><li>Optimize I/O Operations <strong>— </strong>Use asynchronous or parallel I/O operations to prevent blocking the main thread.</li><li>Avoid unnecessary object creation, especially in performance-critical sections of your code. Reuse objects where possible and consider using object pooling techniques.</li><li>When building strings, use StringBuilder instead of concatenating strings with the + operator. This avoids unnecessary object creation.</li><li>Use Efficient Algorithms and Data Structures — Choose algorithms and data structures appropriate for the task to ensure optimal performance.</li></ul><h3>6. Concurrency problems</h3><p>Concurrency issues emerge when multiple threads access shared resources concurrently, often leading to unexpected behavior.</p><p>If you’ve been in the coding game for a while, you’ve likely faced the frustration of emerging issues throughout the development cycle. It’s a real challenge to spot and address these issues effectively.</p><p>And let’s be honest, they tend to linger around, haunting your application if you don’t have clear visibility into real-world performance. The struggle is even more real when dealing with complex distributed systems. Without proper insight, it’s tough to make informed design decisions or assess the impact of code changes.</p><p>That’s where Continuous Feedback steps up to help. The <a href="https://digma.ai/">Digma plugin</a> has been fundamental on this front, allowing us to constantly sniff out various issues throughout the development cycle and providing valuable insights in real time. But let’s not get lost in the background details. Let’s dive into the specifics of what we’ve been up to.</p><p>Recently, we noticed some unexpected behavior and hit a roadblock with performance in one of our backend services. So, what did we do? We decided to put Digma to the test, aiming to identify the issue and zero in on the root cause.</p><p>In a traditional scenario, such an investigation would have required a backlog item to be created, prioritized, assigned, and hopefully not pushed aside because of some urgent matters. Luckily, using existing observability data, Digma was able to show a very specific analysis of the concurrency issue we were facing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/0*__rSrObUAXPhlzGD" /><figcaption>Digma Insights</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*LBv9eowS-5zHGC17" /><figcaption>Digma Dashboard</figcaption></figure><p>Digma’s analysis went beyond just identifying the issue but also helping us resolve it by precisely pinpointing the root cause of the scaling problem.</p><p>Represented by the orange line in the graph, which runs parallel to the overall execution time, the root cause corresponds to a query call triggered during request handling in a specific endpoint.</p><p>Both lines exhibit a similar pattern, indicating that the scaling issue is specifically affecting that particular query, which then propagates to the endpoint. After identifying the root cause, we examined the problematic span and found an inefficient query execution plan.</p><p>We addressed the underlying problem by refactoring the query and adding missing indexes, swiftly resolving the scaling issue.</p><h4>Tips to help prevent concurrency problems in Java</h4><ul><li>Use atomic variables — The java.util.concurrent.atomic package provides classes like AtomicInteger and AtomicLong, enabling atomic operations without explicit synchronization.</li><li>Avoid sharing mutable objects — Design classes to be immutable whenever possible, eliminating the need for synchronization and ensuring thread safety.</li><li>Minimize lock contention — To minimize lock contention, use fine-grained locking or techniques like lock striping to reduce competition for the same lock.</li><li>Utilize the synchronized keyword to create synchronized blocks or methods to ensure that only one thread can access the synchronized code block at a time.</li><li>Use Thread-Safe data structures — Java’s java.util.concurrent package offers thread-safe data structures like ConcurrentHashMap, CopyOnWriteArrayList, and BlockingQueue to handle concurrent access without additional synchronization.</li></ul><h3>Conclusion: resolving Java performance problems</h3><p>I hope you found this discussion resourceful. Remember not to fall victim to premature optimization. It is also crucial to recognize that not all sections of code contribute equally to an application’s performance. The key lies in identifying and prioritizing the critical areas that have a substantial impact on performance. Digma excels at this by allowing you to<a href="https://digma.ai/blog/optimizing-code-by-measuring-performance-impact/"> make your optimization efforts more guided and less random</a>. In other words, Digma analyzes the runtime data to help you identify those pieces of code that affect the system’s ability to scale the most.</p><p><a href="https://plugins.jetbrains.com/plugin/19470-digma-continuous-feedback"><strong>Download Digma for free here</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b88f42dc6118" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/6-tips-for-resolving-common-java-performance-problems-b88f42dc6118">6 Tips for Resolving Common Java Performance Problems</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[25 REASONS WHY JAVA IS STILL AROUND IN 2024]]></title>
            <link>https://medium.com/javarevisited/25-reasons-why-java-is-still-around-in-2024-452c582d55d0?source=rss-478417ae25e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/452c582d55d0</guid>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Nir Shafrir]]></dc:creator>
            <pubDate>Wed, 14 Feb 2024 14:36:05 GMT</pubDate>
            <atom:updated>2024-02-14T14:36:05.682Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*10-Qo1plUmdTTCa4vuICUA.png" /></figure><p>“There are only two kinds of programming languages: the ones people complain about and the ones nobody uses.” — Bjarne Stroustrup.</p><p>When I learned Java, the OOP hype was at its height (late 90s), and Java was pretty much the only language actually implementing those concepts (I did learn C++ before, but come on).</p><p>I actually liked how Java evolved in the meantime. I did look into Python, but I never got the fever it seems to cause in people; then again, maybe I just didn’t get in deep enough. I’ve worked on really big Java projects, and they handled (reasonably) fine; I can’t imagine Python at that scale. Then again, newer projects tend to go into the microservice direction — guess Python’s fine for that, but I wouldn’t know. I know Java is.</p><p>When I learned Java, the OOP hype was at its peak in the late ’90s, and Java stood out as the language actually implementing those concepts (I did learn C++ before, but come on). I appreciated Java’s platform independence.</p><p>I prefer structure and consistency over simplicity is my main point for sticking with Java I guess.</p><p>Throughout my career, I’ve had my fair share of encounters with less-than-ideal Java codebases, and there were times when I found myself getting a bit bored with Java. Then, I worked on many other great projects and started to love Java again.</p><p>It seems like those who criticize and complain about Java are often younger, with more exposure to JavaScript than anything else. Compared to JS, Java can come off as a bit heavy and restrictive — boilerplate everywhere, a type system rigorously enforced by the compiler, and so on. But given the choice, I’d opt for a suboptimal Java codebase over a JS one, no doubt about it.</p><p>It’s only after accumulating some real-world experience, dealing with code scattered across dozens or hundreds of files, that you start to realize the so-called “limitations” of Java are actually safeguards preventing you from shooting yourself in the foot.</p><p>“There are only two kinds of programming languages: the ones people complain about and the ones nobody uses.” This is a famous quote attributed to Bjarne Stroustrup, the creator of C++.</p><p>Do you think Java has a high number of complaints? You should look at C++. People love and hate that language like it’s an inescapable abusive relationship.</p><p>Python has had its fair share of complaints too.</p><p>People constantly talk about how the GIL (global interpreter lock) prevents true, efficient multithreading. So many parts of the Python core rely on the GIL that it will probably never be extricated. As a result, people have had to work around it by using multiple processes and creating message-passing schemes to communicate between the processes. Python performance is also extremely slow unless you rewrite the hotpaths in C/C++. And, of course, the whole Python 2 to 3 transition, etc.</p><p>Also. I once worked on a Django project (when it was the cool thing) and thought that Python was better than typed languages(It has its uses but not in a complex system with 1000s of classes).</p><p>Once this project scaled up from me being the only developer on it to have multiple people and more than 10k lines of code, it became a complex piece to maintain.</p><p>Discovering and switching back to Java was a revelation. It made me realize that I love Java and its ecosystem. That’s why I decided to jot down some of my favorite things about the Java ecosystem. So, if anyone ever badmouths Java, you have 25 reasons to tell them why they are wrong.</p><h3>1. THE ECOSYSTEM IS MATURE</h3><p>Java has been around for more than 25 years. Having been a developer working within this ecosystem, it’s fascinating to reflect on how this ecosystem has matured over the years.</p><p>One of the best things about Java’s extensive ecosystem is the wide range of libraries, build tools, and frameworks that I can choose from.</p><p>JVM ecosystem is completely spoilt, with best-in-class libraries for almost every problem, all high performance and well maintained. Plenty of choices when it comes to building tools, including Gradle, Maven, and Bazel for fast reproducible builds. If you’re still new to the ecosystem, Java provides default implementations for various functionalities, such as logging, database connectivity, messaging, and application servers, which is a great starting point.</p><p>For instance, let’s say you need logging for your application. No worries, Java has you covered straight out of the box with a default logging option seamlessly integrated into the JDK. What if you don’t like the default option, or it’s not enough? The default logging is just a reference implementation to the logging API. There are other nice logging libraries you can choose from.</p><p>And it’s not just logging. The Java ecosystem gives you options for database connectivity, messaging, application servers, servlets, and more.</p><h3>2. WRITE ONCE, RUN EVERYWHERE (WORA)</h3><p>This is a slogan that we often use to refer to the cross-platform benefits of the Java language. Without sounding vindictive here, I know most developers learning Java nowadays may not realize how groundbreaking this feature was to the development of software.</p><p>Here is some context. A decade before Java was born, C++ was the predominant programming language. However, one of the challenges developers faced was the platform-dependent nature of C++. Code written in C++ needed to be recompiled and often modified to run on different operating systems or hardware architectures.</p><figure><img alt="Source: Geeks for Geeks" src="https://cdn-images-1.medium.com/max/539/0*SiDLR1tTdGBMYhnc" /></figure><h3>3. BACKWARD COMPATIBILITY</h3><p>Can you imagine if you had to rewrite code for your program every time there is a new version of Java? That would be very costly and time-consuming, especially for large organizations.</p><p>Java has been around for a while, and that means that there exist software products established on older versions of Java and form the backbone of many enterprises, serving essential functions in various sectors.</p><p>In enterprise development, where projects are large and complex, migration of such systems to the latest Java versions requires careful planning and execution.</p><p>Java’s commitment to backward compatibility is very important as it gives assurance to any developer or organization that has invested a lot into developing a system that it will remain operational and can be maintained without requiring a complete rewrite. Backward compatibility of Java (JVM) also streamlines the migration process, facilitating the adoption of new features and improvements without jeopardizing the stability of existing systems.</p><h3>4. JAVA STRONG TYPE SYSTEM</h3><p>Java is a strongly typed language as opposed to languages such as Python, which are loosely typed. If you have worked with Python, you would immediately feel the flexibility of assigning values of different types to the same variable, and the language would adapt dynamically.</p><p>int age = 25;</p><p>String name = “John”;</p><p>But this flexibility comes at a cost. I remember working on a financial application that dealt with complex calculations involving different numerical data types. With Java’s strong typing, the compiler would flag any attempt to mix incompatible data types or perform operations that could lead to data loss or unexpected results. Some of these obvious bugs might have gone unnoticed with a language such as Python until runtime.</p><p>This is one of the reasons why Java is attractive for developing enterprise applications, especially in industries like banking and finance, where reliability and security are important. Apart from reducing runtime errors that you have to deal with, Java’s strong type system improves code readability by making it easier to understand the intended data types of variables, parameters, and return values.</p><h3>5. FASTER RELEASE CYCLE — CONSTANT IMPROVEMENTS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*TtYKUS4iLlOMCyxu" /><figcaption>Source: JDK</figcaption></figure><p>Traditionally, as Java developers, we were used to getting new Java features following a major release every few years. However, to keep up with the requirements of modern programming, Java’s release cadence has since changed to only six months after the release of Java 9. However, for enterprise organizations that do not need to jump into new versions, Oracle proposed that it will be releasing an LTS version every three years.</p><p>The more frequent, smaller releases reduce the complexity and risk associated with upgrading to a new Java version. Developers are less likely to face major compatibility issues, as the incremental changes are designed to be more backward-compatible.</p><h3>6. BEST IDES</h3><p>Java has come a long way with so many changes and features that make it a great fit for modern development. However, this would only be useful if developers are supported by powerful Integrated Development Environments (IDEs) like IntelliJ IDEA, Eclipse, and NetBeans.</p><p>I can’t imagine what it is like writing code in an environment lacking features like intelligent code completion, automated refactoring, seamless version control integration, and many more. However, it is also important to pause and appreciate that this has not always been the case, especially in the early Java days.</p><p>Fast forward to modern IDEs like IntelliJ and Eclipse, which have made development in Java a breeze. These IDEs integrate seamlessly with build tools like Maven and Gradle, handling compilation, dependency resolution, and project management. Features like intelligent code completion make Java feel less verbose, built-in static code analysis tools make debugging easier, while access to plugins allows you to customize your environment as you like.</p><h3>7. GRAALVM NATIVE IMAGE SUPPORT</h3><p>We have already discussed how the JVM is a wonderful beast that has propelled Java to glory. But it is also true that the JVM has long been plagued by the perception of slow startup times. This can be very problematic, especially now that almost every developer I know is moving towards microservices, serverless computing, and environments where rapid startup and optimized resource consumption are critical.</p><p>There have been efforts to lower memory footprints and achieve faster startup times compared to traditional Java applications running on the JVM. One of the solutions that I’m excited about is the GraalVM Native Image technology. <a href="https://www.oracle.com/ke/java/graalvm/">Oracle GraalVM</a> is a high-performance JDK that can speed up the performance of Java and JVM-based applications using an alternative just-in-time (JIT) compiler known as the Graal compiler.</p><p>GraalVM also includes a native image utility that compiles Java Bytecode ahead of time(AOT), allowing applications to start almost instantaneously. The Graal compiler also works as an AOT compiler, producing native executables. So, the input is Java bytecode, and the output is native executables.</p><p>Here is an example of a small Java program that reverses a String using recursion.</p><pre>public class Example {<br>    public static void main(String[] args) {<br>        String str = &quot;Native Image is awesome&quot;;<br>        String reversed = reverseString(str);<br>        System.out.println(&quot;The reversed string is: &quot; + reversed);<br>    }<br>    public static String reverseString(String str) {<br>        if (str.isEmpty())<br>            return str;<br>        return reverseString(str.substring(1)) + str.charAt(0);<br>    }<br>}</pre><p>You can compile it and build a native image from the Java class.</p><pre>javac Example.java<br>native-image Example</pre><p>The native image builder ahead-of-time compiles the Example class into a standalone executable, example, in your current working directory. You can then run the executable.</p><pre>./example</pre><h3>8. OPEN SOURCE LIBRARIES AND FRAMEWORKS.</h3><p>Open-source libraries and frameworks stand out as one of the key reasons why Java holds a special place in my toolkit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*EvjKA856H5hc28Mz" /><figcaption>Source: Google</figcaption></figure><p>These libraries and frameworks are like building blocks I can seamlessly integrate into my projects, sparing you as a developer the need to reinvent the wheel for common functionalities. It’s like having a store of well-written and test code readily available for use.</p><p>The sheer volume of these libraries means that I cannot get stuck on one solution. I can always pick one that works best for my needs. The open nature of these libraries encourages transparency and accountability. It also means that I can dive into the source code, understand how things work under the hood, and even contribute improvements.</p><p>The list of open source libraries in Java includes JSON parsing libraries like Jackson and Gson, logging libraries like Log4j, SLF4j, and LogBack, unit testing libraries including JUnit, Mockito, and PowerMock, database connection libraries, messaging libraries, and many more.</p><p>Java also owes at least part of its popularity to its expansive ecosystem of frameworks. Spring and Springboot is one of my favorite combinations. Other frameworks I have worked with also include the Jakarta Faces, Struts, Hibernate, and Quarkus.</p><h3>9. MULTITHREADING</h3><p>Java supports multithreading which means that I can design applications that seamlessly juggle multiple tasks simultaneously, whether it’s processing data, handling user interactions, or managing background computations. Java supports multithreading by either implementing a Runnable interface or by extending Thread Class.</p><p>The java.util.concurrent package in Java also provides high-level concurrency utilities, including ExecutorService, ScheduledExecutorService, Future, CyclicBarrier, and more for developing concurrent applications.</p><pre>public class MyRunnable implements Runnable {<br>   public void run() {<br>       // code to be executed in the new thread<br>   }<br>}<br>MyRunnable myRunnable = new MyRunnable();<br>Thread myThread = new Thread(myRunnable);<br>myThread.start();</pre><h3>10. JAVA’S OBJECT-ORIENTED NATURE</h3><p>I know what you’re thinking: Java is not the only object-oriented language, so what makes it any special from the likes of Python and C ? Well, unlike some programming languages that have adopted elements of OOP or have introduced features that support OOP concepts, Java was designed with object-oriented principles from the ground up.</p><p>Java’s adherence to object-oriented principles such as abstractions, inheritance, polymorphism, and encapsulation makes it a good choice for building complex, scalable, and maintainable software systems. There are many benefits that I find beneficial from Java’s support for the OOP paradigm. These benefits include building modular, flexible, readable, maintainable, and scalable Java applications.</p><h3>11. MEMORY MANAGEMENT AND GARBAGE COLLECTION</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*4OWtprzlNcdgFmje" /></figure><p>Source: Digital Ocean</p><p>I’ll be honest, I hate taking out the trash. It’s one of those chores that always feels like a hassle, and I’m sure many can relate. In manual memory management, developers are responsible for allocating and deallocating memory, much like deciding when and how to dispose of each piece of trash. Forget to take out the trash, and you end up with clutter, just as forgetting to deallocate memory leads to memory leaks and performance issues.</p><p>Now, consider Java’s automatic memory management; it is like having a reliable trash collection service. In Java, the garbage collector assumes the role of the diligent garbage collector, autonomously identifying and disposing of memory that is no longer needed.</p><p>Having worked with C++ before transitioning to Java, I have had the experience of both sides. C++ provides unparalleled control over memory management but also a lot of responsibility to you as a developer to ensure that there are not memory leaks.</p><p>Java, on the other hand, there is no need to worry about the low-level system technical details or matters of manual garbage collection, underlying OS, or tracking of memory allocations and deallocations. The garbage collector also automatically identifies and reclaims memory that is no longer in use. This reduces the risk of memory leaks.</p><p>As a developer, this means that I can focus more on the business logic and higher-level aspects of application development. And if you’re working with a team, Java’s automatic memory management improves your development cycles and increases productivity.</p><h3>12. OBSERVABILITY AND MONITORING</h3><p>Until recent years, many developers I know were primarily engaged in developing and maintaining monolithic applications. Troubleshooting and resolving bugs had a certain level of straightforwardness, with the entirety of the application residing in a single, cohesive codebase. Tracking down issues in these types of applications is like navigating a well-mapped territory.</p><p>This has changed dramatically with the rise of microservices, serverless computing, and distributed systems. Identifying and resolving issues is increasingly difficult because microservices run as independent services communicating over a network. When an issue arises, it may not be confined to a single codebase. Here are some of my favorite tools that I use when working with Java.</p><p><strong>Standard Profilers.</strong></p><p>VisualVM.</p><p>VisualVM is like my trusty sidekick when it comes to understanding what’s happening under the hood of my Java applications. It brings together JConsole and VisualGC, giving me a visual playground for monitoring threads, heap usage, and CPU profiling. Plus, it plays nicely with various JDK utilities, making it a reliable tool.</p><p>YourKit.</p><p>This profiler is like having a secret agent in my toolkit. It digs deep into method-level details, exposing execution times and memory allocations. It gives you a simple, easy, and secure way to profile in clouds, containers, and clustered environments.</p><p><strong>APM Tools.</strong></p><p>New Relic.</p><p>New Relic is my go-to for Application Performance Monitoring (APM). It feels like having a personal assistant watching over my applications 24/7. From real-time insights to detailed transaction traces. The alerting features are my safety net, ensuring I’m alerted to any unexpected behavior.</p><p><strong>AppDynamics.</strong></p><p>AppDynamics, my performance artist! It takes a holistic approach to monitoring, observing and visualizing my full technology stack, from database and server to cloud-native and hybrid environments. I appreciate how it helps me understand the impact of performance on end-users, making it not just a monitoring tool but a user satisfaction tool.</p><p><strong>Logging Solutions.</strong></p><p>Log4j.</p><p>This is like the elder statesman of logging frameworks. It’s been with me through thick and thin, faithfully logging events and errors. The flexibility it offers in configuring appenders and filters makes it a reliable workhorse for any logging needs.</p><p>SLF4J.</p><p>SLF4J is like my logging Swiss Army knife. It doesn’t log directly but acts as a facade, allowing me to plug in different logging implementations seamlessly. This flexibility makes it a smart choice when working with various libraries that have their logging preferences.</p><p><a href="https://digma.ai/blog/coding-with-java-observability/"><strong>Observability in Java</strong></a><strong>.</strong></p><p>Digma: Continuous Feedback (FC).</p><p>If you can’t see how your code performs in the real world, you can’t make informed design decisions and assess the impact of your changes. By closing the loop between observability and code, Digma opens the way for a new method of development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*oALKnAdqI0huQLj6" /><figcaption>Digma.ai</figcaption></figure><p><a href="https://digma.ai/">Digma is a Continuous Feedback(CF) tool </a>that is meant to streamline the work of collecting and processing data about your code from <a href="https://digma.ai/blog/opentelemetry-a-practical-guide-to-improving-code-design/">OTEL </a>observability sources. Digma runs locally as an IDE plugin and collects data about your code, from traces to logs and metrics, while you’re coding. This means you can catch issues and get insights in real time.</p><p>Prometheus and Grafana.</p><p>Prometheus and Grafana, my dynamic duo! Prometheus scrapes metrics from my applications, and Grafana turns those metrics into beautiful, customizable dashboards. The open-source nature and the active community around these tools make them my dynamic observability duo.</p><p><strong>Elastic Stack (ELK).</strong></p><p>An Open, extensible, full-stack observability built on AI and search. Elasticsearch, Logstash, and Kibana together they create a powerhouse for searching, analyzing, and visualizing logs. The ability to correlate logs, metrics, and traces gives me a complete investigative toolkit.</p><h3>13. FUNCTIONAL PROGRAMMING SUPPORT</h3><p>Function programming is yet another programming paradigm supported by Java from the release of Java 8. In functional programming, we treat functions as first-class citizens, meaning they can be assigned to variables, passed as arguments, and returned as values.</p><p>Some of the features in this paradigm make Java an attractive programming language. Embracing the functional programming features in Java has been a game-changer for me as a developer. The introduction of lambda expressions and functional interfaces has allowed me to write code that’s not only more concise but also incredibly expressive. With its ability to harness parallel processing on multicore processors, the Stream API has given my applications a performance boost.</p><pre>import java.util.ArrayList;<br>import java.util.Arrays;<br>import java.util.List;<br>public class Main {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; list = new ArrayList&lt;&gt;(Arrays.asList(1, 2, 3, 4, 5));<br>        <br>        int sum = list.stream().reduce(0, (a, b) -&gt; a + b);<br>        System.out.println(sum);<br>    }<br>}</pre><p>I’ve found that adopting a declarative style, as encouraged by functional programming, makes my code more readable and easier to understand. The emphasis on immutability and avoiding side effects has had a tangible impact, making my code more predictable and maintainable. And when it comes to <a href="https://medium.com/javarevisited/beyond-pass-fail-a-modern-approach-to-java-integration-testing-68eb3e82fa79">testing,</a> the prevalence of pure functions has made testing easier.</p><h3>14. JAVA’S RICH DOCUMENTATION</h3><p>If you have a chance to work on a team project, you will certainly understand the importance of documentation. Personally, I consider documentation as a user manual that explains what the code does, how it does it, and why it does it that way. And if you’re a beginner learning Java, it is like having a mentor by your side.</p><p>The <a href="https://docs.oracle.com/en/java/">documentation </a>includes a rich set of code samples, tutorials, developer guides, API documentation, and more that you can use to quickly develop your prototype and scale it up to a real-world application.</p><p>Documentation is not any good if it’s not up to date. Java’s documentation is kept up to date and revised regularly to reflect new developments in the ecosystem by developers and experts. The documentation is also structured in such a way that it is easy to find information about a specific class, method, or concept.</p><h3>15. BUILD TOOLS AND DEPENDENCY MANAGEMENT</h3><p>An average Java/Spring boot project could have dozens, if not hundreds, of direct and transitive dependencies. Managing such dependencies manually can be a headache, especially when working on a large enterprise project, because of issues such as version compatibility. By leveraging build tools, you can unify disconnected builds when working with multiple developers who are running their builds locally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*vPRUte9ojuGrQ_5q" /><figcaption>Source: Google</figcaption></figure><p>However, build tools like Maven and Gradle simplify building, testing, and managing dependencies, making your work easier as a developer. To begin with, these tools also save you the trouble of staying informed about updates and security patches about different dependencies by fetching dependencies from repositories and checking for updates automatically.</p><p>Build tools also enforce conventions and standards for project structure and configuration, making it easy to understand and work with a team of other Java developers.</p><h3>16. ROBUST TESTING FEATURES</h3><p>As much as we developers dread resolving bugs and working with QA engineers, we also acknowledge that comprehensive testing is one of the most effective ways to ensure our applications are as bug-free as possible.</p><p>Choosing a language with robust testing features can significantly ease the burden and contribute to a more reliable and maintainable codebase. This is one of the reasons why I vouch for Java as the go-to programming language for building bug-free software.</p><p>Whether it’s unit, integration, or end-to-end testing, Java provides a comprehensive set of tools to write comprehensive tests. JUnit is the de facto standard for unit testing in Java. It provides a simple and elegant way to write and execute tests. JUnit uses annotations such as @Test, @Before, @After, @BeforeClass, and @AfterClass to define the lifecycle of test methods. This allows you to set up preconditions before running tests.</p><p>As much as we developers dread resolving bugs and working with QA engineers, we also acknowledge that comprehensive testing is one of the most effective ways to ensure our applications are as bug-free as possible.</p><p>Choosing a language with robust testing features can significantly ease the burden and contribute to a more reliable and maintainable codebase. This is one of the reasons why I vouch for Java as the go-to programming language for building bug-free software.</p><p>Whether it’s unit, integration, or end-to-end testing, Java provides a comprehensive set of tools to write comprehensive tests. JUnit is the de facto standard for unit testing in Java. It provides a simple and elegant way to write and execute tests. JUnit uses annotations such as @Test, @Before, @After, @BeforeClass, and @AfterClass to define the lifecycle of test methods. This allows you to set up preconditions before running tests.</p><pre>// EmployeeServiceTest.java<br>import org.junit.jupiter.api.Test;<br>import org.mockito.InjectMocks;<br>import org.mockito.Mock;<br>import org.springframework.boot.test.context.SpringBootTest;<br>import java.util.ArrayList;<br>import java.util.List;<br>import java.util.Optional;<br>import static org.junit.jupiter.api.Assertions.assertEquals;<br>import static org.mockito.Mockito.*;<br>@SpringBootTest<br>public class EmployeeServiceTest {<br>    @Mock<br>    private EmployeeRepository employeeRepository;<br>    @InjectMocks<br>    private EmployeeService employeeService;<br>    @Test<br>    public void testGetAllEmployees() {<br>        // Mocking repository response<br>        when(employeeRepository.findAll()).thenReturn(new ArrayList&lt;&gt;());<br>        // Test case for getAllEmployees method<br>        List&lt;Employee&gt; result = employeeService.getAllEmployees();<br>        // Assertion<br>        assertEquals(0, result.size());<br>        // Verify that the repository method was called<br>        verify(employeeRepository, times(1)).findAll();<br>    }<br>}</pre><p>Writing tests with JUnit is straightforward and integrates seamlessly with popular Java IDEs (Integrated Development Environments) such as Eclipse, IntelliJ IDEA, and NetBeans.</p><p>Other tools I have found useful for testing in the Java ecosystem include TestNG for integration testing, Cucumber for behavior-driven development, and Selenium for automating functional and regression test cases. Mockito is also a powerful mocking framework that you can use in conjunction with other testing frameworks such as JUnit and TestNG.</p><h3>17. LARGE COMMUNITY</h3><p>The Java community has been instrumental in my journey as a Java developer. I have lost count of the number of times that I have sought for help and guidance from the Java community. Whether I’m stuck on a bug, exploring a new library, or seeking best practices when implementing a new solution, the community has proven to be an invaluable source of information.</p><p>The Java community is one of the most responsive community and you will always be sure to receive help almost instantly. For instance, I’m part of the r/java community of Reddit, consisting of thousands of Java developers. Other communities across platforms such as Stack Overflow and Github include a diverse range of developers, from beginners to seasoned professionals. This diversity is a strength, as it means there’s a wealth of expertise covering various domains and levels of experience.</p><p>Apart from online communities, several Java events, conferences, and meetups provide opportunities for developers to connect, share experiences, and learn from one another in person. These gatherings promote networking and collaboration, contributing to the sense of community among Java developers.</p><h3>18. JAVA ANNOTATIONS SUPPORT</h3><p>ava annotations are a very popular topic but also contentious. Annotations were introduced in Java 5, and we all got excited. Personally, I shared in this enthusiasm. The introduction of annotations signaled a departure from the era of extensive Hibernate or Spring XML configuration files. Instead, annotations allowed us to embed information, instructions, or configurations directly within the source code precisely where needed.</p><pre>Predefined annotations<br>@Deprecated<br>@Override<br>@SuppressWarnings<br>@SafeVarargs<br>@FunctionalInterface<br>2. Meta-annotations<br>@Retention<br>@Documented<br>@Target<br>@Inherited<br>@Repeatable<br>3. Custom annotations<br>It is also possible to create our own custom annotations.</pre><p>Java annotations have certainly improved code clarity and expressiveness by reducing the need to refer to external documentation. Annotations can also help cut down some boilerplate code by encapsulating repetitive tasks or configurations. For instance, using annotations, you can define aspects like dependency injection, ORM mappings, and transaction boundaries.</p><p>Some developers feel that although annotations are convenient and have many benefits, they remain skeptical about some of the annotations.</p><h3>SECURITY FEATURES</h3><p>Programs we write are not just lines of code. They also handle sensitive information, such as personal user data, financial details, and proprietary business information. Users expect us to protect their information and provide a secure environment. For businesses, especially those involved in software development or innovation, securing applications is important to prevent the theft of intellectual property. Protecting source code, algorithms, and proprietary information is crucial for maintaining a competitive edge.</p><p>Java has a lot of features that make it easier to develop secure applications. Some of these features include cryptography, public key infrastructure, secure communication, authentication, and access control. You can also access plenty of APIs and tools, allowing you to seamlessly integrate security measures into your Java applications, from cryptography to smart card I/O and other authentication protocols that ensure secure communication.</p><p>This list is far from complete. You can learn about many more features that you can leverage from the official Java Security Guide.</p><h3>20. RICH API SET</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*tcpXiUUN4kztIWAo" /></figure><p>Java is also known for its rich set of Application Programming Interfaces (APIs) that provide a standardized way for us developers to interact with various software components, libraries, and services. These APIs include a rich collection of pre-compiled classes, interfaces, and methods that provide ready-to-use functionality.</p><p>Let’s say you are building a car from scratch. Java APIs make it feel like you assembling already manufactured parts sourced from suppliers as opposed to manufacturing the parts yourself before assembling them. In this case, you have the flexibility of choosing APIs that exactly match your needs. The APIs are standardized and well-documented, making it easy to use them.</p><p>Java’s API is that it abstracts away the complex details of component building, allowing you to focus on assembling a fully functional car, which is your application in this case. These APIs can help you accomplish different tasks across domains such as networking, IO, file handling, database connectivity, multithreading, and many more.</p><p>The Java API is organized into several packages. Some of the most common ones include java.lang, java.util, java.io, and java.net.</p><h3>21. JAVA’S PERFORMANCE</h3><p>Another thing that has kept me in the loop with Java over a long period is witnessing the continuous improvements in Java’s performance over time, which has validated my choice as the primary programming language.</p><p>These improvements in terms of performance have been great in fixing issues and also allowing me to build performant applications capable of serving the modern customer. Some of the notable.</p><p>For instance, the Java Virtual Machine (JVM) has seen significant optimizations with each new release. Just-in-time (JIT) compiler improvements, garbage collection enhancements, and better runtime profiling have collectively contributed to faster execution and reduced memory overhead.</p><p>Project Valhalla introduced value types, allowing us to define more efficient, compact data structures. This reduces memory consumption and also enhances cache locality, resulting in substantial performance gains, especially in scenarios with large amounts of data.</p><p>More recently, we have see JDK 21 usher in 15 features, including a key encapsulation mechanism API, virtual threads, and previews of string templates and structured concurrency which significantly enhance Java.</p><h3>A LEAP FORWARD WITH VIRTUAL THREADS IN JDK 21 AND OTHER FEATURES</h3><h3>22. STRUCTURED CONCURRENCY</h3><p>The proposed API for <a href="https://digma.ai/wp-admin/post.php?post=3079&amp;action=edit">structured concurrency</a> remains a purview feature in JDK 21 with an aim to simplify concurrent programming by treating groups of related tasks in different threads as a single unit of work. This approach enhances error handling, cancellation, reliability, and observability. The feature is not intended to replace existing concurrency constructs in java.util.concurrent.</p><p>This feature will allow us to do away with the complexity of managing tasks and subtasks in concurrent programming using existing constructs like ExecutorService and Future. The lack of inherent relationships between tasks and subtasks leads to challenges in error handling, cancellation, and observability. The proposed structured concurrency approach seeks to align the syntactic structure of the code with the runtime hierarchy of tasks, making concurrent programming more readable, maintainable, and reliable.</p><h3>23. VIRTUAL THREADS</h3><p>Initially introduced as a preview feature in JDK 19 and JDK 20, <a href="https://digma.ai/wp-admin/post.php?post=3157&amp;action=edit">virtual threads</a> have now officially arrived in JDK 21. Each instance of java.lang.Thread has traditionally been associated with a platform thread, binding it to an underlying OS thread throughout its lifecycle.</p><p>However, virtual threads bring a paradigm shift. There are still instances of java.lang.Thread but operate in a manner where they run Java code on an underlying OS thread without monopolizing it. This breakthrough enables multiple virtual threads to share a single OS thread efficiently. Unlike platform threads, virtual threads do not lock down precious OS threads, and their numbers can scale well beyond the constraints of OS thread availability.</p><p>Virtual threads are a compelling addition to JDK 21. They can have a substantial positive impact on application performance, particularly in scenarios where there’s a high volume of concurrent tasks, often exceeding several thousand.</p><p>You now have the flexibility to choose between virtual threads and traditional platform threads based on your application’s specific requirements.</p><h3>24. PATTERN MATCHING FOR SWITCH</h3><p>This exciting feature had its origins in the JDK 17 proposal and went through a series of refinements in JDK 18, JDK 19, and JDK 20. Now, it’s all set to become a part of JDK 21, with additional improvements based on the feedback and experience from the Java community.</p><p>The main aim of this feature is to expand the capabilities and versatility of switch expressions and statements. It is also about letting patterns play a more prominent role in case labels, allowing for a bit more flexibility when it comes to handling null values and making switch statements safer by requiring comprehensive coverage of all possible input values using pattern switch statements.</p><p>And don’t worry if you’re already using switch expressions and statements; the goal is to ensure that they’ll continue to work just as they do now, without requiring any changes.</p><h3>25. STRING TEMPLATES</h3><p>String templates have arrived in Java, finally bringing support for string interpolation, something developers have longed for. Until now, combining multiple strings or wrangling with string.format was the only way to go, and let’s admit it, it was annoying. But with Java 21, we’re in for a treat. This new feature empowers developers to take Java’s string literals and text blocks and infuse them with string templates.</p><pre>int x = 10;<br>int y = 20;<br>String s = STR.&quot;\{x} + \{y} = \{x + y}&quot;;</pre><p>The main goal is to streamline the creation of dynamic Strings by simplifying the expression of values that can be compiled at runtime. Another goals is aim is to enhance readability, addressing the verbosity associated with StringBuilder and StringBuffer classes. Finally, string templates will also help us overcome security concerns associated with existing string interpolation techniques in other programming languages.</p><h3>SUMMING IT UP</h3><p>Java is not easier; it’s just better! Also, modern Java is very fast. Easy to read -&gt; easy to maintain. It is hard trying to be smart in Java -&gt; don’t need to deal with rockstar coworkers. And let’s all be honest; we do care about the salary, and Java developers get high salaries. There are lots of jobs available as most corporations and large organizations use Java as the main language. Some I know who are still working with Java 8 and are happy.</p><p>Install <a href="https://digma.ai/get-digma/">Digma </a>for Free!</p><h3>FAQ.</h3><p><strong>What makes Java a popular programming language?</strong></p><p>Java has gained popularity due to its platform independence, robustness, and extensive community support. It’s widely used in various domains, from web development to enterprise applications.</p><p><strong>What are the advantages of using Java for enterprise-level applications?</strong></p><p>Java provides a stable and scalable environment, supports multithreading, and has many of libraries and frameworks like Spring Boot that simplify enterprise application development.</p><p><strong>How does Java support cross-platform development?</strong></p><p>Java achieves cross-platform compatibility through the “write once, run anywhere” principle, allowing Java code to be executed on any device with a Java Virtual Machine (JVM).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=452c582d55d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/25-reasons-why-java-is-still-around-in-2024-452c582d55d0">25 REASONS WHY JAVA IS STILL AROUND IN 2024</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 REASONS WHY IT IS WORTH LEARNING SPRING BOOT IN 2023]]></title>
            <link>https://medium.com/javarevisited/10-reasons-why-it-is-worth-learning-spring-boot-in-2023-fd06bf833de8?source=rss-478417ae25e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd06bf833de8</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Nir Shafrir]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 14:53:00 GMT</pubDate>
            <atom:updated>2023-12-28T13:29:05.678Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, I’ll outline why learning and mastering Spring Boot in 2023 is a worthwhile endeavor, even though there may be a few differing opinions. I’ll also explore how Spring Boot compares to other backend technologies and alternative Java frameworks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCXL_9yEdIgmnD9xa0aI5g.png" /></figure><h3>10 REASONS WHY LEARNING SPRING BOOT IS WORTH IT IN 2023</h3><p>Hey folks, I’m currently in the process of exploring backend technologies, particularly for startups where time-to-market is crucial. As I started my research to find a technology that complements my existing knowledge, my heart was leaning toward Spring. However, there was a common concern that kept cropping up — many voices in the community seemed to echo the same sentiment: Spring Boot is sluggish in terms of development speed.</p><p>In my case, it’s even more confusing because I have a similar level of proficiency in Django, Node, and Spring. So, I decided to put them to the test, not with simple to-do lists or hello-world apps, but with a complex part of my app. And frankly, my experience led me to a different conclusion. I strongly disagree with the idea that Spring is slower when it comes to development speed. In fact, quite the opposite.</p><p>To make my decision-making process even more difficult, I also get a choice of between the alternatives in building backend apps on Java like Quarkurs, Micronaut, VertX, Play + Akka, Dropwizard, etc. and the list can be even bigger if to include Kotlin, Scala and Clojure frameworks.</p><p>I know that Spring/Boot does have a lot of problems to overcome. But the same counts for other ones as well. But the development speed part seems unjustified. So I continued my research and got more opinions. Based on my results and the different POVs of different Java SE and EM.</p><p>The answer is yes, in 2023, and most likely will be in 2033 as well. Spring is everywhere!</p><p>In this blog, I’ll list the reasons it is worth learning Spring Boot in 23 and how it compares to other backend technologies and alternative Java frameworks.</p><h3>1. SPRING REMAINS VIABLE, AND ITS TRACK RECORD OF STAYING CURRENT AND RELEVANT IS IMPRESSIVE</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/0*4ZXidijh7WrVf6_V" /><figcaption>Java frameworks</figcaption></figure><p>Many experienced developers I’ve had the privilege to speak and work with, who have been deeply involved in the world of Java and Spring for many years, readily admit that the release of Spring Boot was nothing short of a relief.</p><p>The burden of configuring every aspect of a Spring application was overwhelming, especially for newbies, and Spring Boot’s introduction marked a turning point. It brought simplicity and efficiency to Java development, allowing developers to shed the burden of a lot of boilerplate code and focus on what truly mattered: writing robust business logic.</p><p>But it doesn’t stop there. What truly sets Spring Boot apart is its ability to evolve. It’s not merely a technology of the past. Instead, it has continually adapted to meet the ever-changing demands of modern software development.</p><p>Spring Boot’s journey, marked by continuous innovation, a dynamic and supportive community, and an inherent commitment to staying at the forefront of technology trends, is a testament to its reliability.</p><p>Spring Boot now provides enterprise-ready features and integrates well with the microservices and cloud-native trend, providing a platform that’s perfectly suited for building scalable, distributed applications in a cloud-centric world.<br>According to the <a href="https://www.jetbrains.com/lp/devecosystem-2022/java/#:~:text=Spring%20Boot%20and%20Spring%20MVC,by%20a%20few%20percentage%20points.">recent developer ecosystem survey JetBrains</a>, Spring Boot and Spring MVC keep their leading positions as the most used web frameworks for developing in Java.</p><h3>2. THE ECOSYSTEM INTEGRATES WITH EXISTING POPULAR LIBRARIES</h3><p>Many experienced developers I’ve had the privilege to speak and work with, who have been deeply involved in the world of Java and Spring for many years, readily admit that the release of Spring Boot was nothing short of a relief.</p><p>The burden of configuring every aspect of a Spring application was overwhelming, especially for newbies, and Spring Boot’s introduction marked a turning point. It brought simplicity and efficiency to Java development, allowing developers to shed the burden of a lot of boilerplate code and focus on what truly mattered: writing robust business logic.</p><p>But it doesn’t stop there. What truly sets Spring Boot apart is its ability to evolve. It’s not merely a technology of the past. Instead, it has continually adapted to meet the ever-changing demands of modern software development.</p><p>Spring Boot’s journey, marked by continuous innovation, a dynamic and supportive community, and an inherent commitment to staying at the forefront of technology trends, is a testament to its reliability.</p><p>Spring Boot now provides enterprise-ready features and integrates well with the microservices and cloud-native trend, providing a platform that’s perfectly suited for building scalable, distributed applications in a cloud-centric world.<br>According to the <a href="https://www.jetbrains.com/lp/devecosystem-2022/java/#:~:text=Spring%20Boot%20and%20Spring%20MVC,by%20a%20few%20percentage%20points.">recent developer ecosystem survey JetBrains</a>, Spring Boot and Spring MVC keep their leading positions as the most used web frameworks for developing in Java.</p><h3>2. THE ECOSYSTEM INTEGRATES WITH EXISTING POPULAR LIBRARIES</h3><pre>Many experienced developers I’ve had the privilege to speak and work with, who have been deeply involved in the world of Java and Spring for many years, readily admit that the release of Spring Boot was nothing short of a relief. <br><br>The burden of configuring every aspect of a Spring application was overwhelming, especially for newbies, and Spring Boot’s introduction marked a turning point. It brought simplicity and efficiency to Java development, allowing developers to shed the burden of a lot of boilerplate code and focus on what truly mattered: writing robust business logic.<br><br>But it doesn’t stop there. What truly sets Spring Boot apart is its ability to evolve. It’s not merely a technology of the past. Instead, it has continually adapted to meet the ever-changing demands of modern software development.<br><br>Spring Boot’s journey, marked by continuous innovation, a dynamic and supportive community, and an inherent commitment to staying at the forefront of technology trends, is a testament to its reliability.<br><br>Spring Boot now provides enterprise-ready features and integrates well with the microservices and cloud-native trend, providing a platform that’s perfectly suited for building scalable, distributed applications in a cloud-centric world.<br>According to the recent developer ecosystem survey JetBrains, Spring Boot and Spring MVC keep their leading positions as the most used web frameworks for developing in Java.<br><br>2. THE ECOSYSTEM INTEGRATES WITH EXISTING POPULAR LIBRARIES</pre><p>As a developer in the present day, you’ll find yourself juggling many tools and libraries to build applications. These tools range from programming languages, frameworks, and libraries to databases, database connectors like Hibernate and JPA, and messaging systems like Apache Kafka and RabbitMQ.</p><p>Let’s say you’re building a web application. You might use a programming language like Python, a backend web framework, a front-end framework, and a database like PostgreSQL. You may also need to tap into various third-party APIs for functionalities like payment processing, user authentication, and sometimes geolocation services. It is your job as a developer to make all of these components work seamlessly together.</p><p>Modern frameworks like Spring Boot make your work as a developer much easier. Instead of trying to integrate these tools yourself each time you’re developing a new product, Spring Boot really makes your life as a developer much easier by streamlining the process of incorporating these technologies into your project.</p><p>This reduces the time you’d have to spend integrating them by yourself and makes you a more efficient developer.</p><p>If you have been following developments in the tech space in the last couple of years, you can actually attest that Spring Boot has done well in keeping up with new libraries and tools that have emerged. Whether you’re working with GraphQL for powerful query languages, reactive programming with Spring WebFlux, or cloud-native technologies such as Docker and Kubernetes, Spring Boot integrates seamlessly, making it an excellent choice for modern development.</p><h3>3. SPRING IS EVERYWHERE — PERSONAL OR CORPORATE</h3><p>When I reflect on my developer journey, I can’t help but appreciate how Spring Boot has become an integral part of my career. It’s a framework that bridges the gap between my personal passion projects and the projects we are doing at work.</p><p>What struck me as remarkable was the seamless transition between my personal and corporate development experiences. This means that the skills I practice in personal projects using Spring Boot are directly transferable to my work in the corporate world. This means you can use Spring Boot anywhere.</p><p>So whether you want to build a simple personal project or a large enterprise application at your workplace, Spring Boot is the go-to framework that rises to the occasion.</p><p>In the corporate world, Spring Boot’s adoption has been remarkable. It’s not just a framework of choice; it’s become a standard and the backbone of many enterprise-level applications.</p><p>Its reliability, community support, and mature ecosystem of integrations also make it the go-to solution for building scalable, maintainable, and enterprise-grade applications.</p><h3>4. SPRING BOOTS TESTABILITY</h3><pre>import org.junit.jupiter.api.Test;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.boot.test.context.SpringBootTest;<br>@SpringBootTest<br>public class ProductServiceTest {<br>    @Autowired<br>    private ProductService productService;<br>    @Test<br>    public void testProductCreation() {<br>       <br>        Product product = new Product(&quot;Sample Product&quot;, 10.0);<br>        // Act<br>        Product savedProduct = productService.createProduct(product);<br>        // Assert<br>        assertNotEquals(0, savedProduct.getId());<br>        assertEquals(&quot;Sample Product&quot;, savedProduct.getName());<br>        assertEquals(10.0, savedProduct.getPrice(), 0.01);<br>    }<br>}<br></pre><p>Testing is every developer’s best friend, right? Well, it should be, but let me take you back to when it was more like a nagging headache than a relief.</p><p>In my early days as a developer, writing tests was a daunting exercise, especially while I was still trying to master the basic concepts of programming. Setting up test cases felt like solving a riddle and catching exceptions was always a constant struggle. The process was so cumbersome that I felt discouraged from writing thorough tests and would often find ways to evade them.</p><p>Fast forward a few years, when I started working with the Spring Boot framework writing unit, and integration tests became less of a headache and more of a satisfying routine. I would also encourage you to choose a framework with good features that enhance writing tests to help you along.</p><p>Spring Boot is an excellent choice for developing applications with robust testing features.</p><p>For the following reasons:</p><ul><li>Spring Boot integrates seamlessly with popular testing frameworks like JUnit, Mockito, and Spring Test.</li><li>Spring Boot provides a wide range of testing annotations, including @SpringBootTest, @DataJpaTest, and @WebMvcTest, which help configure the application context for specific types of testing, streamlining the process.</li><li>Spring Boot allows you to leverage the vast ecosystem of Spring Frameworks, such as Spring Security for security testing and Spring Data for database-related testing.</li><li>Spring Boot support for mocking frameworks like Mockito gives you access to utilities for generating test data, enabling you to build even more robust applications.</li><li>Spring Boot integrates well with <a href="https://www.atomicjar.com/2023/10/beyond-pass-fail-a-modern-approach-to-java-integration-testing/">TestContainers</a> to fast-track your integration tests.</li></ul><p><strong>If you’re building a distributed application, testing is non-negotiable.</strong></p><h3>5. MONITORING AND OBSERVABILITY</h3><p>When I started my programming journey back in college I started by developing basic single-page applications, which were relatively straightforward and had limited complexity. These single-page applications typically had a simple front end, minimal data processing, and a single server handling requests. With this type of application, it was easy to pinpoint issues and make adjustments on the fly.</p><p>However, as time has gone by, my projects have grown in scope and complexity, and I now find myself dealing with more complicated applications. These applications mostly feature multiple microservices, databases, external integrations, and complex business logic.</p><p>Over this time, as the complexity of the systems I work on increases, I’ve learned to value metrics, logs, and distributed tracing.</p><p>Spring Boot, especially Spring Boot 3, offers <a href="https://digma.ai/how-it-works/">built-in observability capabilities</a> that make it easier for you to monitor, diagnose, and gain insights into the internal state of your applications in production environments. Here are some Spring Boot features that you can leverage to observe and monitor your applications:</p><h4>1. Actuator Endpoints.</h4><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Actuator Endpoints are a set of built-in tools and functionalities in Spring Boot that offer various insights into the internals of our applications. Some of the endpoints you’ll find useful include:</p><ul><li><strong>/actuator/health </strong>endpoint that provides information about the health of your application</li><li>/actuator/metrics provides detailed metrics on various aspects of your application, such as memory usage, garbage collection.</li><li>The<strong> /actuator/info</strong> endpoint lets us expose custom application information.</li><li><strong>/actuator/env </strong>provides access to the application’s environment properties, which can be useful for troubleshooting configuration issues.</li><li>You can also build your custom endpoints to help you expose specific data or trigger actions.</li></ul><h4>2. Metrics Collection — Micrometer integration.</h4><p>I’ve seen how the rise of microservices and cloud-native architectures has made monitoring these distributed systems absolutely necessary. This is where Micrometer comes into play, presenting itself as the go-to “SLF4J” for application metrics.</p><p>Micrometer is like an all-around utility belt for application metrics, ready to support a wide range of monitoring systems. It’s like a multipurpose tool for developers, enabling us to collect valuable insights from our applications without being locked into a particular monitoring solution.</p><p>It’s all about giving us the flexibility to choose the right tool for the job and ensuring that we’re not confined to a single system. For instance, you can work with tools such as Prometheus, Datadog, InfluxDB, and more.</p><p>Micrometer also has a rich set of instrument types, such as gauges, counters, timers, and distribution summaries.</p><h4>3. Logging.</h4><pre>2023-03-05 10:57:51.112  INFO 45469 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.52<br>2023-03-05 10:57:51.253  INFO 45469 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext<br>2023-03-05 10:57:51.253  INFO 45469 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1358 ms<br>2023-03-05 10:57:51.698  INFO 45469 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: &#39;dispatcherServlet&#39; to [/]<br>2023-03-05 10:57:51.702  INFO 45469 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: &#39;hiddenHttpMethodFilter&#39; to: [/*]</pre><p>The significance of logging has grown over time from a mere debugging tool to a way that you can build reliable, maintainable, and efficient software.</p><p>In my experience with Spring Boot, it’s great to know that it relies on Commons Logging for its internal logs but remains flexible when it comes to the underlying log implementation. It’s like having the best of both worlds!</p><p>Out of the box, Spring Boot provides default configurations for Java Util Logging, Log4J2, and Logback. In each scenario, the loggers come pre-configured to display log messages on the console, and you also have the option to direct the logs to a file if needed.</p><p>If you’re using the ‘Starters,’ Spring Boot sets up Logback for your logging needs by default. What’s cool is that it takes care of Logback routing too, ensuring that even if you have dependent libraries that use different logging frameworks like Java Util Logging, Commons Logging, Log4J, or SLF4J, everything will work harmoniously.</p><p>So, you’ve got the freedom to choose your preferred logging framework, but Spring Boot’s default setup with Logback simplifies things, making it easy to get started without worrying about compatibility issues with other libraries.</p><pre>&#39;dispatcherServlet&#39; to [/]<br>2023-03-05 10:57:51.702  INFO 45469 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: &#39;hiddenHttpMethodFilter&#39; to: [/*]</pre><p><strong>4. Distributed Tracing with OpenTelemetry.</strong></p><p>Let’s say you’re a relatively new developer responsible for maintaining a large e-commerce platform. One day, you receive a report from the customer support team indicating that some customers are experiencing issues during the checkout process. Users are complaining about orders not being processed, and they’re unable to complete their purchases.</p><p>Without proper observability tools and distributed tracing, you don’t have end-to-end visibility into the request flow. You’re blind to the interactions between microservices and it becomes hard to trace how each request is handled, and where are the errors and bottlenecks.</p><p>OpenTelemetry is today considered the standard for tracing with a wide range of OSS and commercial tools to support it such as Jaeger, Zipkin, and enterprise APMs. Fortunately, Spring has extensive support for OTEL across its many projects and libraries. Spring Boot supports both the OTEL agent <a href="https://opentelemetry.io/docs/instrumentation/java/automatic/">instrumentation</a> — a very quick and unobtrusive way to get started in dev and test, as well as the more performant <a href="https://micrometer.io/docs/tracing">Micrometer Tracing</a> library.</p><p>If you need an extra shortcut in bootstrapping OpenTelemetry (OTEL) to your spring application or want to integrate all of that important data into your dev process, consider free developer tools such as <a href="https://digma.ai/">Digma</a>. Digma is a <a href="https://digma.ai/blog/coding-with-java-observability/">Continuous Feedback</a>(CF) tool that is meant to streamline the work of collecting and processing data about your code from OTEL observability sources. Digma runs locally as an IDE plugin and collects data about your code, from traces to logs and metrics, while you’re coding. This means you can catch issues and get insights in real-time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vUCHz9WXTEnpbvQ-" /><figcaption>The Digma Continuous Feedback Dashboard</figcaption></figure><h3>6. Simplicity and Rapid Development</h3><p>Choosing the right tool at the onset of any project is a strategic decision with far-reaching consequences. It can affect everything from the development process and performance to security, scalability, and user experience.</p><p>Equally, choosing the right framework can significantly impact your learning curve and early experiences. Spring Boot is an excellent choice if you’re just starting your coding adventure due to its “convention over configuration” philosophy.</p><p>Spring Boot reduces Spring’s verbose and complex setup. This means that as a beginner, you can focus on coding your application’s core logic without getting lost in a sea of configuration files. With Spring Boot, you can create self-contained, executable JAR files, making deployment very easy. There’s no need to manage application servers or complex deployments.</p><p>Spring Boot also offers preconfigured templates or collections of dependencies that simplify setting up and configuring an application; these are known as Spring Boot starters. These starters are designed to look at your classpath and the beans you’ve configured and make reasonable assumptions about what might be missing. They then automatically add the necessary components, libraries, and configurations to get your application up and running quickly.</p><h3>7. Microservice support</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/0*En73gCNtQKSm15RI" /></figure><p>You may have heard many conversations lately that microservice architectures are the ‘new normal,’ way of developing applications.</p><p>It’s true, they’re cool. The idea of breaking down monolithic applications into smaller, independently deployable services makes sense. So, inspired by the hype, I joined a discussion on Reddit about microservices. It started with enthusiasm, but as the thread grew, a theme emerged — the “<a href="https://www.reddit.com/r/programming/comments/16g7f3y/death_by_a_thousand_microservices/">Death by a Thousand Microservices.</a>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/0*wI0P2iakwKXbOp9o" /></figure><p>Source; Reddit.</p><p>As developers shared their experiences, it was evident that managing many microservices can be a real headache. The challenge of orchestrating and monitoring all these components can lead to complexity overload.</p><p>Spring Boot comes to the rescue. I’ve found that its features make working with microservices far less intimidating. Spring Boot’s integration with Spring Cloud provides tools for service discovery, load balancing, and distributed configuration. These features simplify the creation and management of microservices, ensuring they work seamlessly together.</p><p>Other features that I and many other Java developers appreciate when working with Spring Boot include support for containerization technologies like Docker and orchestration platforms like Kubernetes, seamless integration and interoperability with many technologies and extensive documentation.</p><h3>8. Embedded Servers</h3><pre>&lt;dependency&gt;<br>     &lt;groupId&gt;org.apache.tomcat.embed&lt;/groupId&gt;<br>     &lt;artifactId&gt;tomcat-embed-core&lt;/artifactId&gt;<br>     &lt;version&gt;8.5.23&lt;/version&gt;<br>     &lt;scope&gt;compile&lt;/scope&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>     &lt;groupId&gt;org.apache.tomcat.embed&lt;/groupId&gt;<br>     &lt;artifactId&gt;tomcat-embed-el&lt;/artifactId&gt;<br>     &lt;version&gt;8.5.23&lt;/version&gt;<br>     &lt;scope&gt;compile&lt;/scope&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>     &lt;groupId&gt;org.apache.tomcat.embed&lt;/groupId&gt;<br>     &lt;artifactId&gt;tomcat-embed-websocket&lt;/artifactId&gt;<br>     &lt;version&gt;8.5.23&lt;/version&gt;<br>     &lt;scope&gt;compile&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>To give you a good context, let me take you back to the time when we typically had to set up and configure web servers manually for deploying web applications. This is when deployments and containerization were not as prevalent as they are today.</p><p>So once you have your web application, you would typically deploy it on standalone web servers like Apache HTTP Server or Nginx. These web servers were responsible for handling incoming HTTP requests, processing them, and forwarding them to the web applications running in separate containers.</p><p>Configuring these external standalone web servers required writing extensive XML configuration files. You also had to specify servlet mappings, data source connections, and other deployment-specific details in these configuration files.</p><p>On the other hand, using Spring Boot’s Embedded servers in Spring Boot makes deployments much easier. Spring Boot includes support for embedded Tomcat, Jetty, and Undertow servers. These servers are bundled with the application, allowing you to package your applications as standalone JAR files. This approach simplifies deployment, eliminating the need for separate server installations and complex server configurations.</p><h3>9. Spring Boot is open source</h3><p>The open-source nature of Spring Boot is something that has resonated deeply with me and many other developers. What I love about the open-source nature of Spring Boot is that it levels the playing field for everyone. So regardless of whether you’re a student, a newbie in technology, or an experienced developer, you have access to the <strong>same code, the same documentation, and the same opportunities for contribution as anyone else.</strong></p><p>Open source promotes transparency. So you’re not just working with a black-box solution, but you can investigate how the framework works under the hood and even make modifications as you deem fit. It also means that there are no costs attached. You can use the framework freely for personal projects, side hustles, or enterprise-grade applications without worrying about costs.</p><p>Finally, one of the most fulfilling aspects is that you can contribute through bug fixes, documentation improvements, and even new Spring Boot features.</p><h3>10. Community and Support</h3><p>I have been a developer for a little over a decade, and I have lost count of the number of times I have sought and received support from different communities. These communities are distributed across different platforms such as Reddit, Twitter, and Stack Overflow.</p><p>As a developer, it is often easy to get carried away with the notion that staying indoors in your small room and coding around the clock in isolation is the way to progress. However, the reality of software development is quite the opposite. The field of programming is collaborative in nature, driven by the constant exchange of ideas and a team approach to solving complex issues.</p><p>Being part of a community is very helpful, especially when you’re just starting your coding journey.</p><p>Spring Boot has been around for a while and has a thriving ecosystem of developers, architects, and experts who constantly share ideas and resources and help each other solve problems. Due to its open-source nature, developers can also share ideas that improve the Spring Boot framework, and you can also participate.</p><h3>Spring Boot Vs Quarkus</h3><p>I came across an engaging discussion on Reddit that revolved around the topic of “<a href="https://www.reddit.com/r/java/comments/yr8yli/micronaut_vs_othersspring_boot_quarkus_and_co/">Micronaut vs others (Spring Boot, Quarkus, and co.)</a>.” Developers are actively exploring different alternatives when it comes to selecting a framework for building microservices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/0*ANIDag4h69ZPGPQn" /><figcaption>Source Reddit</figcaption></figure><p>In this Reddit conversation, many opinions and experiences were shared. Some developers expressed their love for Micronaut, highlighting its rapid development capabilities and the efficiency of <a href="https://digma.ai/wp-admin/post.php?post=1092&amp;action=edit">Micronaut</a> Data. They appreciated the out-of-the-box support for various third-party frameworks, which streamlined their development process. However, concerns were raised regarding certain documentation gaps and the need to navigate the <strong>application.yml </strong>file for configuration.</p><p>On the other hand, Quarkus found favor with several participants due to its rapid development and exceptional performance, thanks to GraalVM native image compilation, making it ideal for resource-efficient, containerized deployments and serverless applications.</p><p>Many praised the documentation’s clarity and completeness, which ensures that they rarely needed to seek answers in forums. The optional use of reactive programming in Quarkus was a welcome feature because it provides flexibility based on specific project requirements.<br>Many developers also acknowledged that while the ecosystem is growing,<strong> Spring Boot remains a compelling choice for microservices,</strong> particularly when dealing with more complex and enterprise-level projects. Partly, this is due to its large ecosystem of libraries and extensions and strong community support.</p><h3>SPRING BOOT VS. DJANGO OR NODE JS.</h3><p>In my experience and career, I have also come to appreciate the unique strengths and trade-offs of different technologies. Many developers seem to share similar opinions when comparing Spring Boot to other frameworks outside of the Java ecosystem.</p><p>The Java ecosystem has a relatively higher initial learning curve but stands out for its robustness and extensive libraries. Spring Boot excels in scenarios where reliability and scalability are important. However, one trade-off is the slightly longer startup times compared to other frameworks.</p><p>Python and Django, on the other hand, offer a delightful experience for web development, particularly in projects where developer productivity and rapid iterations are essential.</p><p>Python may not be as performant as Java in certain situations, it has a readable and clean code syntax. Django has shown that it’s an excellent choice for content management systems, web applications, and situations where getting a project up and running quickly is a priority.</p><p>Node.js, with its JavaScript backbone, has been my go-to for real-time applications and microservices. Its performance, especially for I/O-bound and real-time scenarios, is exceptional.</p><p>My experience with Node.js is that it is a perfect choice where speed and scalability are paramount, particularly when building real-time applications like chat platforms. Besides, the ability to use a single language for both client and server makes your life even easier.</p><h3>CONCLUSION: IT IS WORTH LEARNING SPRING BOOT</h3><p>Spring Boot is still the leading framework in the Java world, and it doesn’t seem to change anytime soon.</p><p>Spring Boot is still very relevant. If or when it is surpassed by something else, you will learn portable concepts that will likely be used in other frameworks. Until then, the marketplace has opportunities for Spring Boot knowledge now and well into the future. Moreover, with the new Spring Boot releases, I’d say that Spring Boot is likely to stay the de-facto Java framework for the next few years at least.</p><p>It’s also important to note the growing relevance of frameworks like Micronaut and Quarkus, which offer unique advantages for specific types of projects. Exploring these alternatives and understanding when to apply them can further enhance your abilities as a developer.</p><h3>FAQ</h3><p><strong>What is Spring Boot, and why should I consider learning it in 2023?</strong></p><p>Spring Boot is a popular open-source Java framework that makes it easier to create microservices and web applications. Learning Spring Boot in 2023 is worth it because it offers numerous advantages for modern software development projects and a lot of work opportunities.</p><p><strong>What are the key features that make Spring Boot stand out in 2023?</strong></p><p>Spring Boot offers features like auto-configuration, rapid development, and a wide range of built-in tools for microservices, web applications, and more. These features enhance developer productivity and code quality.</p><p><strong>What are some real-world applications of Spring Boot in 2023?</strong></p><p>Spring Boot is used in a wide range of applications, from web development and microservices to API creation and backend systems. Companies such as Netflix, Alibaba, LinkedIn, Uber and Groupon use Spring Boot.</p><p>Install Digma for free: <a href="https://digma.ai/get-digma/">Here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd06bf833de8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/10-reasons-why-it-is-worth-learning-spring-boot-in-2023-fd06bf833de8">10 REASONS WHY IT IS WORTH LEARNING SPRING BOOT IN 2023</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code Refactoring in Java: Tips, Best Practices, Techniques]]></title>
            <link>https://medium.com/javarevisited/code-refactoring-in-java-tips-best-practices-techniques-c240fb334925?source=rss-478417ae25e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c240fb334925</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Nir Shafrir]]></dc:creator>
            <pubDate>Sat, 09 Sep 2023 10:49:44 GMT</pubDate>
            <atom:updated>2023-09-09T10:49:44.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*KwOjHqm-7RfvpW2sfJMZyg.jpeg" /></figure><p>Throughout my journey as a Java developer, I have learned to acknowledge the fact that most of the code I write from the initial stages of developing a product is destined to undergo massive changes before it is done. As developers, our job does not just entail crafting new lines of code but also routinely revisiting the code we’ve previously written or inherited, not just for minor tweaks but for substantial changes and enhancements. In some cases, the whole codebase needs to be refactored. This fundamental practice in our craft is formally referred to as code refactoring.</p><p>However, <a href="https://medium.com/javarevisited/7-best-courses-to-learn-refactoring-and-clean-coding-in-java-47bea3c67006">code refactoring in Java</a> isn’t always the optimal solution and can have unintended negative consequences. Many developers can share their refactoring stories and experiences of failure. “Works don’t touch” is the famous adage that comes to mind. Sometimes, there is no other choice but <a href="https://medium.com/javarevisited/7-best-courses-to-learn-refactoring-and-clean-coding-in-java-47bea3c67006">code refactoring</a>, but without the right safety net, developers will find themselves dreading the need to retouch the code.</p><p>This is why careful planning is crucial to ensure its success. When undertaking a code refactoring journey, it’s essential to acknowledge that the process may be time-consuming and filled with challenges. Also, it’s important to recognize that when working in a team, each member has their perspectives and considerations that can impact the process when incorporating new features into the freshly refactored code. This requires thorough planning, documentation, and collective decision-making on the new architecture.</p><p>By following specific steps, techniques, and the correct tooling, you can sidestep potential refactoring pitfalls, preventing the emergence of “horror stories” during refactoring such as the one shared in<a href="https://digma.ai/blog/coding-horrors-refactoring-and-feature-creep/"> this article</a>. So let’s start by first exploring what Java code refactoring is:</p><p><a href="https://medium.com/javarevisited/7-best-courses-to-learn-refactoring-and-clean-coding-in-java-47bea3c67006">7 Best Courses to Learn Refactoring and Improve Coding Skills in Java</a></p><h3>What Is Java Code Refactoring?</h3><p>Java Code refactoring is the practice of restructuring and improving existing code by making small incremental changes that do not impact the external behavior of the code. Code refactoring involves changing the internal structure of the code to improve readability, performance, maintainability, and efficiency without breaking the code’s functionality.</p><p>Martin Fowler is a software developer and author who has written extensively about design and refactoring code. In his book titled “<a href="https://martinfowler.com/books/refactoring.html"><em>Refactoring Improving the Design of Existing Code</em></a><em>” </em>He describes refactoring as follows</p><blockquote><strong><em>“Refactoring is a controlled technique for improving the design of an existing code base. Its essence is applying a series of small behavior-preserving transformations, each of which “too small to be worth doing”. However the cumulative effect of each of these transformations is quite significant” Martin Fowler</em></strong></blockquote><p>Some of the common changes you can make when refactoring your Java code include:</p><ul><li><strong>Renaming variables, classes, functions, and other elements </strong>in your code to more readable and descriptive names.</li><li><strong>Inline replacement of methods or functions </strong>that have become redundant with their content at call sites.</li><li>You can also extract blocks of code from functions and move them into their own separate functions to improve modularity and readability.</li><li><strong>Reducing redundancy</strong> by removing pieces of code that perform the same function and replacing them with one.</li><li>Refactoring can also involve <strong>extracting and splitting classes</strong> or modules that handle too many responsibilities into smaller, more focused components.</li><li>You can also <strong>combine classes or modules with similar functionality</strong>.</li><li>Refactoring changes can also include making changes to improve code performance.</li></ul><h3>Java Code Refactoring Techniques</h3><h3>Renaming Variables and Methods</h3><p>Choosing meaningful variable and method names is key to making your code more readable. Code readability is arguably one of the most important aspects of any good codebase. Readable code clearly communicates the intent to the reader, while less readable code increases the likelihood of bugs during refactoring. Using meaningful variable and method names reduces the need for comments and makes collaboration easy.</p><pre>// Before Refactoring<br>int d = 30; // days<br>int h = 24; // hours in a day<br><br>// After Refactoring<br>int daysInMonth = 30;<br>int hoursInDay = 24;</pre><h3>Extract Method</h3><p>The extract method is one of the most common Java code refactoring techniques. The extract method is useful when you have a long, complex method that performs multiple responsibilities. Extracting tasks to separate methods makes the original method less complex and readable. This method also allows you to refactor your code to be more reusable and easily maintainable. Suppose you have a simple class that processes orders and calculates subtotal cost, tax rate, and total cost.</p><pre>public class OrderProcessor {<br>    private List&lt;Item&gt; items;<br>    private double taxRate;<br><br>    public double processOrder() {<br>        double subtotal = 0;<br>        for (Item item : items) {<br>            subtotal += item.getPrice();<br>        }<br>        <br>        double totalTax = subtotal * taxRate;<br>        double totalCost = subtotal + totalTax;<br>        <br>        return totalCost;<br>    }<br>}</pre><p>You can refactor the code above such that the code related to calculating the subtotal, tax, and total cost has been extracted into separate methods: <strong>calculateTax</strong>, <strong>calculateSubtotal</strong>, and <strong>calculateTotalCost</strong> as shown below. This makes the class more readable, modular, and reusable.</p><pre>public class OrderProcessor {<br>    private List&lt;Item&gt; items;<br>    private double taxRate;<br><br>    public double processOrder() {<br>        double subtotal = calculateSubtotal();<br>        double totalTax = calculateTax(subtotal);<br>        return calculateTotalCost(subtotal, totalTax);<br>    }<br>    <br>    private double calculateSubtotal() {<br>        double subtotal = 0;<br>        for (Item item : items) {<br>            subtotal += item.getPrice();<br>        }<br>        return subtotal;<br>    }<br>    <br>    private double calculateTax(double subtotal) {<br>        return subtotal * taxRate;<br>    }<br>    <br>    private double calculateTotalCost(double subtotal, double totalTax) {<br>        return subtotal + totalTax;<br>    }<br>}</pre><h3>Remove Magic Numbers and Strings.</h3><p>Magic numbers and strings are values hardcoded into your code. Using such values in your code makes the code less maintainable and increases inconsistencies and errors due to mistypes. Instead of using hardcoded values, refactor your Java code to use constants with descriptive names.</p><pre>// Before Refactoring<br>if (status == 1) {<br>    // ... code for active status ...<br>}<br><br>// After Refactoring<br>public static final int ACTIVE_STATUS = 1;<br><br>if (status == ACTIVE_STATUS) {<br>    // ... code for active status ...<br>}</pre><h3>Code De-duplication.</h3><p>Duplicate codes are similar code fragments that appear in multiple places in the codebase. Duplicate code is dreaded in software development due to its negative effects on quality, maintainability, and efficiency. It also increases bug intensity, increases inconsistencies, and bloats the size of your codebase.</p><p><strong>Before Refactoring</strong></p><pre>public class NumberProcessor {<br><br>    public int calculateTotal(int[] numbers) {<br>        int total = 0;<br>        for (int i = 0; i &lt; numbers.length; i++) {<br>            total += numbers[i];<br>        }<br>        return total;<br>    }<br><br>    public double calculateAverage(int[] numbers) {<br>        int total = 0;<br>        for (int i = 0; i &lt; numbers.length; i++) {<br>            total += numbers[i];<br>        }<br>        double average = (double) total / numbers.length;<br>        return average;<br>    }<br>}<br><br><br><br></pre><p><strong>After Refactoring</strong></p><pre>public class NumberProcessor {<br><br>    public int calculateSum(int[] numbers) {<br>        int total = 0;<br>        for (int i = 0; i &lt; numbers.length; i++) {<br>            total += numbers[i];<br>        }<br>        return total;<br>    }<br><br>    public int calculateTotal(int[] numbers) {<br>        return calculateSum(numbers);<br>    }<br><br>    public double calculateAverage(int[] numbers) {<br>        int total = calculateSum(numbers);<br>        double average = (double) total / numbers.length;<br>        return average;<br>    }<br>}</pre><p>In the refactored example, we have extracted the duplicate logic for summing up the number into the <strong>calculateSum</strong> method. Both <strong>calculateTotal</strong> and <strong>calculateAverage</strong> methods now utilize the <strong>calculateSum</strong> method to calculate the sum.</p><h3>Simplify Methods.</h3><p>Over time, your code gets more dated and maintained by different developers it is easy to end up with complex and convoluted methods. This Java code refactoring technique lets you keep your methods easy to understand, maintain, and extend.</p><p>The simplification method may involve identifying overly complex methods that contain nested logic and too many responsibilities before applying the steps below to simplify the method.</p><ul><li>Apply the Single Responsiblity Principle (SPR) to the method.</li><li>Extract sub-methods to standalone methods.</li><li>Eliminate redundant and unused code.</li><li>Limit the level of nesting within the method.</li></ul><p>Here is a simple Java code refactoring example to illustrate the method simplification technique.</p><p><strong>Before simplification</strong></p><pre>public class ShoppingCart {<br>    private List&lt;Item&gt; items;<br><br>    public double calculateTotalCost() {<br>        double total = 0;<br>        for (Item item : items) {<br>            if (item.isDiscounted()) {<br>                total += item.getPrice() * 0.8;<br>            } else {<br>                total += item.getPrice();<br>            }<br>        }<br>        if (total &gt; 100) {<br>            total -= 10;<br>        }<br>        return total;<br>    }<br>}</pre><p>We can simplify the example above by extracting the <strong>calculateItemPrice</strong> logic to <strong>calculateItemPrice</strong> and <strong>applyDiscount </strong>and simplify the conditionals by using ternary operators instead.</p><pre>public class ShoppingCart {<br>    private List&lt;Item&gt; items;<br><br>    public double calculateTotalCost() {<br>        double total = 0;<br>        for (Item item : items) {<br>            total += calculateItemPrice(item);<br>        }<br>        total -= applyDiscount(total);<br>        return total;<br>    }<br><br>    private double calculateItemPrice(Item item) {<br>        return item.isDiscounted() ? item.getPrice() * 0.8 : item.getPrice();<br>    }<br><br>    private double applyDiscount(double total) {<br>        return total &gt; 100 ? 10 : 0;<br>    }<br>}<br><br></pre><p>Red-green refactoring</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HeopxNOFM1Dxw0e0" /></figure><p>The red-green refactoring method is also commonly called the Test Driven Development (TDD). This Java code refactoring technique emphasizes writing tests before writing the actual code that passes the tests already written. This is a repetitive cycle, and on each iteration, you should write new tests before implementing just enough code to pass those tests.</p><p>The red-green Java code refactoring technique involves the following three steps.</p><p><strong>Red: </strong>At this step in the cycle, you have no actual code. You should start by writing failing tests(Red) because there is no implementation to satisfy the test cases.</p><p><strong>Green:</strong> In this phase, you should write the minimal code necessary to pass the failing test cases. The goal is not to write perfect or optimized code at this stage but to make the test pass (turn the test from red to green).</p><p><strong>Refactor: </strong>Once you are confident that the code you have implemented passes the tests, you can now focus on refactoring the code to improve performance, structure, and other aspects without breaking the functionality lest the test cases fail.</p><p>The cycle repeats itself once you are done with a specific test case. In the new cycle, you can move to the next test case, which involves writing a new test case and just enough code implementation to pass the new test case before refactoring the code to add improvements.</p><h3>Fix Code Classes that Violate the Single Responsibility Principle.</h3><p>You’ve probably heard about the SOLID principles in object-oriented programming. SOLID is an acronym for the five principles, and one of these is the Single Responsibility principle, represented by the first letter. According to this principle, every class should have one and only one reason for change. In other words, a class should have only one responsibility.</p><p>The single responsibility principle is one of the most important aspects of keeping your code maintainable, readable, flexible, and modular. Here is an example of an OrderProcessing class that violates the single responsibility principle since it is also responsible for logging information to a file.</p><p><strong>Before refactoring</strong></p><pre>public class OrderProcessor {<br>    public void processOrder(Order order) {<br>        // Processing logic<br>        <br>        // Logging<br>        Logger logger = new Logger();<br>        logger.log(&quot;Order processed: &quot; + order.getId());<br>    }<br>}</pre><p>According to the single responsibility principle we can refactor this class such that we have and <strong>OrderProcessor</strong> class responsible for processing and order and <strong>OrderLogger</strong> class responsible for logging.</p><p><strong>After refactoring</strong></p><pre>public class OrderProcessor {<br>    public void processOrder(Order order) {<br>        // Processing logic<br>        <br>        // Logging<br>        OrderLogger orderLogger = new OrderLogger();<br>        orderLogger.logOrderProcessed(order);<br>    }<br>}<br><br>public class OrderLogger {<br>    public void logOrderProcessed(Order order) {<br>        Logger logger = new Logger();<br>        logger.log(&quot;Order processed: &quot; + order.getId());<br>    }<br>}</pre><h3>13 Java code refactoring best practices.</h3><p>Java code refactoring is an important practice that holds the potential to elevate the quality of your code, among other benefits we have highlighted above. However, you should also take care, especially when <a href="https://digma.ai/blog/coding-horrors-tales-of-codebase-complexity/">refactoring a large codebase </a>or working with an unfamiliar one, lest you inadvertently alter software functionality or introduce unforeseen flaws.</p><p>Here are some tips and best practices you can follow when refactoring Java code to avoid eny potential problems.</p><ol><li><strong>Preserver functionality:</strong> The primary aim of Java code refactoring is improving quality. However, the external behaviour of the program i.e how it responds to inputs and outputs and other user interactions should remain unchanged. Remember that with a tool such as <a href="https://digma.ai/">Digma</a>, you never have to worry about breaking stuff. Digma lets you know which services use the code you’re working on, which might break if you make changes, and what you need to test.</li><li><strong>Understand the code well: </strong>Before setting out to refactor a certain piece of code, ensure that you understand the code you’re about to refactor. This includes its functionality, interactions, and dependencies. This comprehension will guide your decisions and help you avoid making changes that may impact the functionality of your code.</li><li><strong>Break down your Java Refactoring process into small steps: </strong>Refactoring a large piece of software can be overwhelming, especially if it is new to you. However, by breaking down the refactoring process into smaller manageable steps, you make your workload easier, reduce the risk of errors, and allow you to continuously and easily validate your changes.</li><li><strong>Use version controls to create a backup:</strong> Since refactoring involves making changes to your codebase, there is a chance that things may not go as planned. It is a good idea to back up your working software in a separate branch to avoid wasting a lot of time and resources when you cannot figure out which changes have broken your software. Version control systems like Git allow you to manage different software versions concurrently.</li><li><strong>Run Frequent Tests on your changes: </strong>The last thing you want when refactoring your code is inadvertently breaking the functionality of your program or introducing bugs that affect your software. Before embarking on any significant code changes, especially refactoring, having a suite of tests in place provides a safety net. These tests validate that your code behaves as expected and that existing functionality remains intact. You can also use the Digma filtering or sorting by “impact” metric in the asset section on the sidebar and identify areas that might need attention during the refactoring. This allows you to gain insights into which parts of the codebase might have the most significant impact and could potentially benefit the most from refactoring. With Digma, you can proactively prioritize your refactoring efforts instead of blindly refactoring different sections of your code.</li><li><strong>Leverage Refactoring Tools: </strong>With modern IDEs like Eclipse and IntelliJ, Java code refactoring does not have to be stressful. For instance, the IntelliJ IDEA includes a set of robust refactoring capabilities. Some features include safe delete, extract method/parameter/field/variable, inline refactoring, copy/move, and many more. These features make your work easier and reduce the chances of you introducing bugs during refactoring.</li><li><strong>Gain insights into the code changes. </strong>Gaining insights into your code changes can help you speed up the refactoring process by identifying any issues that may arise along the way. Tools like <a href="https://digma.ai/">Digma</a> can help you do that. Digma is a runtime linter that lets you quickly identify risky code, potential errors, and bottlenecks in complex codebases. It uses OpenTelemetry behind the scenes to collect data such as traces, logs, and metrics when you run your code locally. As you embark on refactoring your Java code, you can leverage the Digma insights to identify issues, anomalies, and patterns to facilitate informed and efficient Java code refactoring. Measuring and recording various metrics related to your code’s performance and behavior also gives you a before/after picture that serves as a baseline to understand the impact of your changes. By comparing the before and after states, you can identify areas that require further optimization, and assess whether the refactoring achieved the intended goals.</li><li><strong>Leverage unit tests: </strong>As a developer, you’d want to refactor your code with confidence that you’re not going to break your application or introduce bugs. A complete unit test suite allows you to detect regressions, ensure functionality is not broken, facilitate collaboration, and ensure long-term maintainability.</li><li><strong>Keep track of performance changes with Continuous Feedback: </strong>Java code refactoring is not just about improving the structure of your but also the performance. Keeping track of performance metrics takes the guesswork out of the equation, allowing you to validate that your refactoring efforts are yielding results. Besides quantifying your improvements, tracking performance improvements allows you to compare different Java refactoring strategies. <a href="https://digma.ai/">Digma</a> gives you continuous access to evidence-based feedback, so you can continuously optimize and improve your code. You don’t need to be an observability expert or wait until there’s a production-breaking issue. With valuable data such as code execution times, scaling limitations, and <a href="https://digma.ai/blog/n1-query-problem-and-how-to-detect-it/">N+1 query</a> issues, you can quickly fix performance issues in your code.</li><li><strong>Peer review your Java code refactoring changes: </strong>Once you make you’re done with your refactoring changes, it is always a good idea to have another developer with a fresh perspective look at the changes. An impartial peer review from your colleague can identify issues you might have overlooked and bring new insights and valuable feedback. A peer review is a good way to foster collaboration and knowledge sharing among team members if you’re working in a team.</li><li><strong>Document the refactoring changes:</strong> If you’re working with a team of other developers, it is obvious that your changes may impact their work. To promote collaboration and enhance transparency, it is imperative that you document reasons for changes that may not be immediately obvious. Documenting changes also improves knowledge sharing and onboarding.</li><li><strong>Regression testing: </strong>Once you’re done with refactoring your Java code, you need to ensure that the existing functionalities are preserved. Regression testing allows you to ensure that your newly introduced logic does not conflict with the existing code.</li><li><strong>Keep your Team in the Loop:</strong> If you’re working on a team with other developers, communicate your refactoring changes to your colleagues. This prevents conflicts and helps them adapt to any changes you make.</li><li><strong>Revert If Necessary:</strong> If you encounter unexpected issues during refactoring, don’t hesitate to revert to a working state. It’s better to take a step back than waste a lot of time and resources when you can’t figure out what went wrong in the Java code refactoring process.</li></ol><h3>Conclusion.</h3><p>Refactoring is an essential practice that contributes to the long-term success of software projects. By incorporating refactoring using the techniques we have discussed above alongside diligent adherence to the best practices into your development cycle, you can turn any <a href="https://digma.ai/blog/coding-horrors-tales-of-codebase-complexity/">complex and tangled codebase</a> into a readable, maintainable, and extensible software solution. However, keep in mind that Java code refactoring is not a one-off activity but an ongoing process that can be integrated into your development cycle.</p><h3>FAQ</h3><p><strong>When should I refactor my Java code?</strong></p><p>Code refactoring can be done throughout the software development lifecycle. It’s often a good idea to refactor when you’re adding new features, fixing bugs, or working on a piece of code that’s hard to understand. Regularly setting aside time for refactoring prevents technical debt from accumulating and helps maintain a high-quality codebase.</p><p><strong>How do I decide which code to refactor?</strong></p><p>You can start by identifying areas of the codebase that are difficult to understand, contain duplicated logic, or are prone to bugs. Look for long methods, complex conditionals, and instances where following design principles like the Single Responsibility Principle would improve code organization.</p><p><strong>How can I ensure that refactoring doesn’t introduce bugs?</strong></p><p>A strong suite of automated tests is essential to minimize the risk of introducing bugs to your code. Before refactoring, ensure that your code has good test coverage to help you catch any regressions and ensure the code’s functionality remains unaffected.</p><p><strong>How to refactor classes in Java?</strong></p><p>Begin by identifying the target class that requires improvement, understanding its behaviour and analyzing its dependencies. Break down large methods, move methods to suitable classes, and leverage inheritance and interfaces for cleaner structures. Rename, reorganize, and simplify conditionals to boost readability. Thoroughly test changes to ensure that functionality is not broken.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c240fb334925" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/code-refactoring-in-java-tips-best-practices-techniques-c240fb334925">Code Refactoring in Java: Tips, Best Practices, Techniques</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is The N+1 Query Problem and How to Detect It]]></title>
            <link>https://medium.com/javarevisited/what-is-the-n-1-query-problem-and-how-to-detect-it-4ad751034c5a?source=rss-478417ae25e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ad751034c5a</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[n-plus-1-queries]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[observability]]></category>
            <dc:creator><![CDATA[Nir Shafrir]]></dc:creator>
            <pubDate>Tue, 15 Aug 2023 15:10:53 GMT</pubDate>
            <atom:updated>2023-08-16T15:47:42.821Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’ll dive deep into the infamous N + 1 query problem using a practical example, its effects on application performance, and how innovative solutions can help detect and mitigate the N + 1 query problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rI4Qak5lWC-AM--UFQDLxA.png" /></figure><p>If you have used any ORM framework like <a href="https://medium.com/javarevisited/5-best-spring-data-jpa-courses-for-java-developers-45e6438be3c9">Hibernate</a>, you can attest to how easy it is to define data models in simple regular classes and map them to any relational database. Much of the convenience that we enjoy when working with Object Oriented Programming languages and relational databases has been made possible by ORM tools like <a href="https://medium.com/javarevisited/top-5-books-to-learn-hibernate-for-java-developers-b2cb4b16ccd6">Hibernate</a>.</p><p>Although programming languages have different ORM tools, their general purpose is similar: They speed up development, keep your code DRY, improve security, and lessen the need for mastering <a href="https://javarevisited.blogspot.com/2017/02/top-6-sql-query-interview-questions-and-answers.html">raw SQL queries</a>.</p><p>As a developer, however, you should also watch out for the shortcomings of any technology. The infamous N + 1 query problem is an anti-pattern that stems from the leaky abstraction that ORMs provide. Because ORMs make it extremely simple to access data without making queries, they also make it easy to access that data inefficiently. T<strong>his problem is mainly associated with how ORM frameworks handle the lazy loading of related entries. You can find the details below.</strong></p><h3>What is The N+1 Query Problem?<a href="https://signoz.io/blog/N+1-query-distributed-tracing/#what-is-n1-query-problem">​</a></h3><p>To better understand the N + 1 query problem, we’ll first need to understand the concept of data fetching in ORM tools. By default, most ORM tools, such as <a href="https://medium.com/javarevisited/8-best-spring-and-hibernate-training-courses-for-java-developers-acf09aa0e244">Hibernate </a>and <a href="https://medium.com/javarevisited/my-favorite-courses-to-learn-django-for-beginners-2020-ac172e2ab920">Django</a>, use lazy loading as the default data fetching behavior. This means they only fetch data explicitly requested from the database and delay any related data you have not requested.</p><p>Let’s look at an example. Suppose you are building a blog application with multiple blog posts, and every blog post is linked to its respective author through a one-to-many relationship. If your application fetches a list of blogs and then subsequently fetches the associated author for each blog using a separate query, this results in many roundtrips to the database.</p><pre>// Fetching All Blogs<br>List&lt;Blog&gt; blogs = blogRepository.findAll();<br>// N+1 Queries: One Query for Blogs, N Queries for Authors<br>for (Blog blog : blogs) {<br>    Author author = blog.getAuthor(); // Triggers a separate query for each blog post&#39;s author<br>}</pre><p>The tricky part is noticing that this is happening. In your code, you would seem only to be iterating over objects. Because ORMs provide an abstraction over <a href="https://medium.com/javarevisited/8-best-resources-to-learn-sql-online-for-free-b00506d88c91">SQL</a>, they also make it very difficult to guess which object property access will result in a query. In this case, you are running one query to fetch the list of blog posts and then running multiple queries that fetch N number of authors corresponding to every blog post, hence the name N + 1 query problem.</p><p>The more blog posts and Authors in your database, the more severe the problem can be, impacting application performance and user experience. Here are some issues that can be caused by the N + 1 query problem:</p><ul><li><strong>Slow response times: </strong>The N + 1 query problem slows down data retrieval, which makes your application less responsive to user requests.</li><li><strong>Limited scalability: </strong>As your application grows, the N + 1 query problem can limit your application’s ability to handle the growing user demands.</li><li><strong>Increase Database load</strong>: The increased number of queries due to the N + 1 query problem strains your database.</li><li><strong>Limited throughput:</strong> The N + 1 query problem reduces the number of transactions your database can handle per section.</li><li><strong>Degrades user experience: </strong>With slow load times, users are likely to wait longer for pages to load, which is frustrating, to say the least.</li></ul><h3>Fixing N+1 Query Issues</h3><p>Most ORMs also provide the means to avoid N+1 queries by controlling the lazy vs. eager loading of related entities. With <a href="https://javarevisited.blogspot.com/2013/05/10-hibernate-interview-questions-answers-java-j2ee-senior.html">Lazy load</a>, the related entity is loaded as a proxy, only to be initialized when one of the entity properties is accessed in the code. On the other hand, Eager loading performs a <a href="https://javarevisited.blogspot.com/2012/11/how-to-join-three-tables-in-sql-query-mysql-sqlserver.html">SQL join</a> when initializing the original entity so that no further queries are necessary.</p><p>Hibernate provides several ways to configure eager loading, either on the relationship mapping itself or per query:</p><h3>1. Configuring the entity relationship as eager</h3><p>This is the most aggressive of the three strategies as it fundamentally changes how the entity is loaded. Most ORM tools like <a href="https://www.java67.com/2016/02/top-20-hibernate-interview-questions.html">Hibernate </a>lazy load-related entities by default, resulting in multiple database queries. Configuring the relationship between related entities as eager instructs your ORM to fetch the main entity and its related entities in a single query.</p><pre>@Entity<br>public class Author {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    private String name;<br>    @OneToMany(mappedBy = &quot;author&quot;, fetch = FetchType.LAZY)<br>    @BatchSize(size = 10) // Batch loading strategy<br>    private List&lt;Post&gt; posts = new ArrayList&lt;&gt;();<br>    // Getters and setters<br>}</pre><h3>3. Eager loading on query level</h3><p>You can also prevent N + 1 query problems by explicitly specifying queries that should be eagerly loaded alongside the main entity. This approach is useful when you know exactly which related entities you want to fetch, eliminating the need for subsequent querying.</p><pre>public interface PostRepository extends JpaRepository&lt;Post, Long&gt; {<br>    @Query(&quot;SELECT p FROM Post p JOIN FETCH p.author&quot;)<br>    List&lt;Post&gt; findAllPostsWithAuthorsEagerly();<br>}</pre><p>In cases where you only need to fetch related entities occasionally, and the relationships between your entities are fairly simple, then eager loading on a query level is an overkill. You can opt to use manual loading or ‌rely on the ORM’s default eager loading.</p><h3>4. Manually load-related entities in the code</h3><p>This approach gives you granular control when loading related entities from the database. ORM frameworks typically provide methods that allow you to load related entities. For instance, if your application has a <strong>Post</strong> entity related to <strong>Author, </strong>you can manually load related Authors using a method such as<strong> post.getAuthor(). </strong>You avoid running into the N + 1 query problem using this manual approach.</p><pre>@Service<br>public class PostService {<br>    @Autowired<br>    private PostRepository postRepository;<br>    public Post getPostWithAuthor(Long postId) {<br>        Post post = postRepository.findById(postId).orElse(null);<br>        if (post != null) {<br>            // Manually load the author for every blog post<br>            Hibernate.initialize(post.getAuthor());<br>        }<br>        return post;<br>    }<br>}</pre><p>However, you should also remember that if the relationships between entities are straightforward, your ORM’s automatic eager loading feature should be enough.</p><h3>Understanding Continuous Feedback</h3><p><a href="https://digma.ai/">Digma</a> Continuous Feedback is a runtime linter that lets developers quickly identify risky code, potential errors, and bottlenecks in complex codebases. It uses OpenTelemetry behind the scenes to collect data such as traces, logs, and metrics when you run your code locally.</p><p>Once the data is collected, Digma looks for regressions, anomalies, code smells, or other patterns that can be useful for knowing about your code while in the development phase. This allows you to accelerate your development cycles and, at the same time, catch potential problems in your code.</p><h3>How Continuous Feedback Can Help Detect The N+1 Query Problem</h3><p>As your application grows, such query issues can become serious performance bottlenecks that significantly increase the database load and slow down application performance</p><p>. If you have a complex application performing hundreds of queries to the database, it can be difficult to spot them by simply reading through the code. However, with Digma, you can easily detect such queries even when working with complex codebases.</p><p>Problems such as repeated queries associated with N+1 Select statements are easy to detect in the runtime data. Specifically, in traces that Digma automatically collects using OpenTelemetry.</p><p>Here is what an N+1 Select query looks like in a trace:</p><figure><a href="https://www.java67.com/2016/02/top-20-hibernate-interview-questions.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RglirwkuFmJWWHj6" /></a></figure><p>Once Digma has collected and analyzed the data, it then highlights that the second query responsible for fetching user roles has a potential N + 1 query problem. Digma then generates an insightful alert next to the query source code/</p><figure><img alt="Suspected N+1 notice" src="https://cdn-images-1.medium.com/max/530/0*mIrUR8saKp1RBOnh" /><figcaption>Trace</figcaption></figure><p>Apart from that, you can also notice that Digma also highlights the impact on ‌response time, showing that the endpoint handling this query (e.g., GET /owner) is affected by the N+1 problem. While the duration of the query time of 1.1 ms for the 10 repeat DB calls seems small, this can quickly increase if your application makes more queries, taking a toll on your application’s performance.</p><p>Digma also goes a step further and provides insights at the endpoint level. This allows you to note the endpoint that is potentially affected by an N + 1 query problem, the severity of the impact, and the method causing the issue, as shown in the output below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/0*TfvCPiQg7rRDexBO" /></figure><p>Armed with Digma insights above, at the query and endpoint level, you can easily find and fix code that’s causing N + 1 query problems.</p><h3>Case Study: Reducing Execution Time for Specific APIs</h3><p><a href="https://www.linkedin.com/in/markus-westergren-1926992/">Markus Westergren</a> is an experienced Senior Consultant/Staff Engineer with a demonstrated history of working in the information technology and services industry. Markus is a Beta user of Digma and recently shared with us that they could detect such N+1 query issues in their code, which reduced execution time for specific APIs.</p><h3>What coding issues did you encounter that led you to try Digma?</h3><p>I recently joined a team that is developing a new product. There were performance issues with some use cases. My job was to find and fix them. I used manual analysis and a profiler to try and pinpoint hotspots in the code. Any changes I made had to be tested and measured to see if an issue was fixed.</p><h3>How did Digma help you solve these issues?</h3><p>With Digma, I get continuous feedback on the application’s performance. It will instantly show me where the biggest bottlenecks are, so I don’t have to search for them myself. I can now get direct feedback on how my latest fix performs compared with the previous version. It also found bottlenecks that we did not even know about. It takes the guesswork out of the picture. We save lots of time finding and fixing performance issues.</p><h3>How did Digma help handle suspected N-plus-1 in SQL queries?</h3><p>We are using <a href="https://www.java67.com/2021/11/best-hibernate-and-spring-data-jpa-courses.html">Hibernate</a>, and it makes it much easier to see what’s really going on.</p><p>We have already identified some cases where Hibernate produces N-plus-1 queries which are affecting the performance of the application.</p><p>We’ve made big improvements, and Digma has helped us identify some cases where N+1 queries may affect the application’s performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5izF7LQcw-0bVvYe" /></figure><p>Besides the insights on the repeating database spans, Digma also provides key endpoint insights that allow us to detect and fix N + 1 queries related to specific endpoints, among other performance issues at their source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NgSea8i31OHTaEAs" /></figure><p>Digma has certainly been a great addition to our development workflow, and we will continue leveraging it to optimize and improve our code and provide the best user experience.</p><h3>Conclusion</h3><p>The N + 1 query problem is a common problem when working with ORM frameworks such as <a href="https://javarevisited.blogspot.com/2018/01/top-5-hibernate-and-jpa-courses-for-java-programmers-learn-online.html">Hibernate</a>. Although different solutions, such as overriding lazy loading provided by ORM frameworks, can help avoid this problem, detecting such queries is crucial. Digma is a reliable tool that can save you the manual effort of finding such queries. With Digma in your development workflow, you can leverage continuous evidence-based feedback to optimize your code.</p><p>Happy Observing:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ad751034c5a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/what-is-the-n-1-query-problem-and-how-to-detect-it-4ad751034c5a">What is The N+1 Query Problem and How to Detect It</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices for Writing Clean Java Code]]></title>
            <link>https://medium.com/javarevisited/best-practices-for-writing-clean-java-code-7e88eacf10e0?source=rss-478417ae25e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e88eacf10e0</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[linter]]></category>
            <dc:creator><![CDATA[Nir Shafrir]]></dc:creator>
            <pubDate>Sun, 30 Jul 2023 12:33:35 GMT</pubDate>
            <atom:updated>2023-09-06T06:32:29.332Z</atom:updated>
            <content:encoded><![CDATA[<p>Even bad code can function. But if code isn’t clean, it can bring a development organization to its knees — Uncle Bob.</p><figure><img alt="Java developer writing clean code" src="https://cdn-images-1.medium.com/max/800/0*PBo8pNfreVuF2XB0.jpg" /></figure><p>Having spent a few years in the technology industry, mostly developing software, I’ve been accustomed to the reality that most of my time is spent working with different teams and reviewing code written by other software developers. Over the years, I’ve had diverse experiences working with code written by different developers. These experiences have fundamentally reinforced my appreciation for clean code.</p><p><em>“Indeed, the ratio of time spent reading versus writing is well over 10 to 1. We are constantly reading old code as part of the effort to write new code. …[Therefore,] making it easy to read makes it easier to write.” </em>from <a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship-ebook/dp/B001GSTOAM">Clean Code: A Handbook of Agile Software </a>Craftsmanship (Uncle Bob).</p><p>Whether you have been a software developer for a while or just started, I’m confident that you can relate to the experience and effort required when inheriting a new codebase. Inheriting a codebase often involves familiarizing yourself with the code, its structure, functionality, programming language, libraries, framework, and any other technology used.</p><p>Navigating unfamiliar code or code you wrote a while ago can be daunting. Whether you want to<a href="https://digma.ai/blog/coding-with-java-observability/"> fix bugs,</a> enhance functionality, improve performance, or join an ongoing project, the time and effort required depends on the state of the code.</p><p>Code written with clean Java code principles can save you countless hours and frustrations. On the other hand, when working with messy code, you’re likely to spend most of your time deciphering tangled logic, uncommented code, and poorly named variables.</p><h3>What is clean Java Code and Its Benefits?</h3><p><a href="https://medium.com/javarevisited/clean-code-a-must-read-coding-book-for-programmers-9dc80494d27c">Clean code</a> is the practice of writing straightforward, readable, testable, and easy-to-understand code. Other features of clean code include adherence to good conventions and best practices that promote expressiveness, conciseness, organization, and maintainability. Clean code should also be free from bugs, unjustifiable complexity, code smells, and redundant code.</p><p>Robert C. Martin, popularly known as Uncle Bob, has written extensively on the subject of clean code. Programmers of all levels of experience who desire to write clean code can benefit from his book on clean code, articles, and a series of talks. In his book, he says,</p><p><em>“ Even bad code can function. But if code isn’t clean, it can bring a development organization to its knees. Every year, countless hours and significant resources are lost because of poorly written code. But it doesn’t have to be that way ” from </em><a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship-ebook/dp/B001GSTOAM"><em>Clean Code: A Handbook of Agile Software Craftsmanship.</em></a></p><p>The importance of writing clean Java code cannot be overstated. Some benefits that can be immediately realized from clean code include:</p><ul><li>Maintainability — Clean code is easy to modify and update.</li><li><a href="https://digma.ai/blog/11-java-debugging-tips-techniques-using-intellij-ide/">Debugging</a> — Clean code is less prone to errors. It is also easier to isolate and fix issues within the code.</li><li>Scalability — Clean code is modular, reusable, and accommodative of future changes.</li><li>Collaboration — Clean code allows teammates to understand each other’s code.</li><li>Documentation — Clan code is self-explanatory and reduces the need for excessive comments.</li><li>Efficiency — Clean code removes code duplication and unnecessary complexity, which improves performance.</li><li>Readability — Clean code is easy to read, reduces confusion, and improves maintainability.</li></ul><h3>1. Use a Standard Project Structure</h3><p>Project structure outlines how to arrange various components in your project, such as Java source files, test files, documentation files, build files, and configuration files. A clear project structure makes it easy to understand, navigate and modify a project codebase. On the other hand, a poor project structure can cause confusion, especially when working with projects with many files.</p><p>Although <a href="https://medium.com/javarevisited/top-5-java-online-courses-for-beginners-best-of-lot-1e1e240a758">Java </a>doesn’t enforce a specific project structure, build tools such as <a href="https://medium.com/javarevisited/6-best-maven-courses-for-beginners-in-2020-23ea3cba89">Maven </a>suggests a project structure you can follow.</p><pre>  ├── main<br>    │   ├── java                   Application/Library sources<br>    │   ├── resources              Application/Library resources<br>    │   ├── filters                Resource filter files<br>src    │   └── webapp                 Web application sources<br>    │   <br>    └── test<br>        ├── java                   Test sources<br>        ├── resources              Test resources<br>        └── filters                Test resource filter files</pre><h3>2. Stick to Java Naming Convention</h3><p>Java naming conventions are a set of rules that dictate how Java developers should name identifiers. ‌The <a href="https://docs.oracle.com/javase/specs/">Java Specification Document</a> includes rules for naming variables, packages, classes, and methods. These naming conventions allow developers to keep things in order when writing code. Good naming improves code readability, consistency, and maintainability.</p><p>Some of the Java naming conventions include:</p><ul><li>Class and interface names should be nouns and have the first letter capitalized.</li><li>Method names should be verbs.</li><li>Variable names should be short and meaningful.</li><li>Package names should be lowercase.</li><li>Constant names should be capitalized.</li></ul><pre>package com.example.project;<br>public class Person {<br>    private String firstName;<br>    private String lastName;<br>    public Person(String firstName, String lastName) {<br>        this.firstName = firstName;<br>        this.lastName = lastName;<br>    }<br>    public String getFullName() {<br>        return firstName + &quot; &quot; + lastName;<br>    }<br>    public static final int MAX_AGE = 100;<br>    public boolean hasValidName() {<br>        return firstName != null &amp;amp;&amp;amp; lastName != null;<br>    }<br>}</pre><p>You can find more information about <a href="https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html">Java naming conventions here</a>.</p><h3>3. Readability Over Reusability</h3><p>Reusability is one of the most advocated concepts in software development. It lessens development time and reduces the effort required to maintain software when developers understand the reusable components very well.</p><p>While the concept of reusability sounds great and has many benefits, it also has many potential pitfalls, especially when working on an unfamiliar codebase. When working with large applications, code reusability can reduce readability, usability, and maintainability if a proper design is not in place. Code reusability affects the readability of code when it makes it difficult to understand the logical flow of the code without tracing execution.</p><p>Poor code readability makes debugging difficult and increases the effort required to maintain the codebase. This can be challenging, especially when trying to onboard new developers into your project. Therefore, as you develop software, ensure that you don’t prioritize reusability over readability.</p><h3>4. Lint Your Code with Static and Dynamic Analysis Tools</h3><p>Static and dynamic code analysis tools complement each other. Both dynamic and static analysis tools can help in writing clean Java code. Static analysis tools allow you to inspect your application source code and ensure adherence to coding standards, spot vulnerabilities, and detect bugs during development.</p><p>On the other hand, dynamic analysis allows you to test your application at runtime. It allows you to measure your application’s performance, behavior, and functionality and identify runtime errors, memory leaks, and resource consumption reducing the chances of running into issues in production.</p><p><a href="https://digma.ai/">Digma</a> is a runtime linter that lets developers quickly identify risky code, potential errors, and bottlenecks in complex codebases. Digma leverages OpenTelemetry behind the scene to collect data such as traces, logs, and metrics. Once the data is collected, Digma analyzes it to detect meaningful insights about the code. It looks for regressions, anomalies, code smells, or other patterns that can be useful for knowing about the code, allowing you to push clean Java code to production.</p><figure><img alt="Digma Continuous feedback pipeline: The Digma JetBrains plugin analyzes your code for you, all the time. As you code, Digma. analyzes runtime data to find hidden issues that you may have missed. Digma helps to identify risky code, potential errors, and bottlenecks in complex codebases." src="https://cdn-images-1.medium.com/max/1024/0*TP2nHGXLcBy-pvLJ.png" /><figcaption>Digma Continuous Feedback Pipeline</figcaption></figure><h3>6. Consistent and Proper Code Formatting: Whitespaces and Indentation</h3><p>Code formatting may not seem like a big issue when you’re working on a personal project whose code may never be maintained by another developer. However, consistent code formatting and style are critical when working with a team of other developers.</p><p>Maintaining a consistent formatting and coding style in your team and codebase ‌is important if you wish to write clean Java code as a team. Whitespace and indentation are essential in maintaining a consistent coding style.</p><p>Good usage of whitespace between operators, commas, and around flow statements enhances code readability. For instance, you can organize code into logical groups using whitespaces, enhancing readability and visual clarity.</p><p>Indentation refers to using tabs or spaces within loops, methods, and control structures. Although there is no enforced convention for code indention in Java, you can choose to adopt popular convection and use it consistently.</p><h3>7. Use Consistent and Proper Code Formatting: Whitespaces and Indentation</h3><p>7. Use Consistent and Proper Code Formatting: Whitespaces and Indentation</p><p>Code formatting may not seem like a big issue when you’re working on a personal project whose code may never be maintained by another developer. However, consistent code formatting and style are critical when working with a team of other developers.</p><p>Maintaining a consistent formatting and coding style in your team and codebase ‌is important if you wish to write clean Java code as a team. Whitespace and indentation are essential in maintaining a consistent coding style.</p><p>Good usage of whitespace between operators, commas, and around flow statements enhances code readability. For instance, you can organize code into logical groups using whitespaces, enhancing readability and visual clarity.</p><p>Indentation refers to using tabs or spaces within loops, methods, and control structures. Although there is no enforced convention for code indention in Java, you can choose to adopt popular convection and use it consistently.</p><pre>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>@SpringBootApplication<br>public class MyApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(MyApplication.class, args);<br>    }<br>    <br>    // Rest of the code goes here<br>    // ...<br>}</pre><h3>8. Restrict the Number of Method Parameters</h3><p>Parameters are necessary when working with methods. However, care should be taken to avoid using too many parameters in one method. Too many parameters may indicate that your method is addressing more than one concern and violates the single responsibility principle.</p><p>Too many method parameters make your code less readable since keeping track of their types and meanings is difficult. To write clean Java code, you should: limit the number of method parameters and use objects or data structures instead of individual parameters or group-related parameters into objects.</p><p>Here is an example of a Java method with too many method parameters:</p><pre>public class Order {<br>    private String customerName;<br>    private String shippingAddress;<br>    private String billingAddress;<br>    private String productName;<br>    private int quantity;<br>    private double price;<br>    private boolean isExpressShipping;<br>    // Constructors, getters, and setters<br>    // Other methods related to an order<br>}<br>public void processOrder(Order order) {<br>    // Method implementation<br>}</pre><h3>9. Leverage Unit Tests and Test-Driven Development (TDD)</h3><p>Unit testing and TDD are very common practices in software development. Unit testing involves writing tests for individual functions, methods, and classes to ensure that they work in isolation. TDD is also a popular development practice that involves writing tests before code.</p><p>Both Unit tests and a TDD approach can propel your efforts toward writing clean Java code. Unit tests allow you to verify correctness, detect bugs early, and write more modular code. TDD provides immediate feedback and increases your confidence in writing reliable and maintainable code.</p><figure><img alt="Unit testing involves writing tests for individual functions, methods, and classes to ensure that they work in isolation. In this image are two objetects that went through unit testing but not integration" src="https://cdn-images-1.medium.com/max/640/0*BKJYLUwEXq9C0fwf.gif" /><figcaption>Source: Twitter</figcaption></figure><h3>10. SOLID Principles</h3><p>The SOLID principles by Robert C. Martin (Uncle Bob) are very popular; every developer should know them. These principles can also help you write clean, maintainable, and scalable code.</p><p>Let’s discuss how each of the principles in the SOLID acronym can help you write clean Java code.</p><p><strong>Single Responsibility Principle (SRS):</strong> The single responsibility principle states that a class should only have one responsibility. Following the SRS principle guarantees that we write concise, readable, and maintainable code.</p><p><strong>Open-closed principle (OCP):</strong> The OCP states that classes should be open for extension but closed for modification except when fixing bugs. This principle allows you to add new features without introducing bugs or breaking existing functionality. In Java, you can use interfaces or abstract classes to extend the functionality of existing classes.</p><p><strong>Liskov substitution principle (LSP): </strong>The LSP principle states that we should be able to use superclasses with their respective subclasses interchangeably without breaking the functionality of our program. Using this principle allows you to use inheritance correctly and write decoupled clean Java code.</p><p><strong>Interface Segregation Principle:</strong> States that we should opt for smaller focused interfaces instead of large monolithic ones. Using this principle allows us to write modular and clean Java code where the implementing classes focus only on methods that concern them.</p><p><strong>Dependency Inversion Principle (DIP):</strong> This principle emphasizes loose coupling, guaranteeing that components such as classes only depend on abstractions and not on their concrete implementations. DIP helps us enforce clean Java code using Inversion of Control (IoC) and dependency injection.</p><h3>11. Keep It Simple, Studio (KISS), and Don’t Repeat Yourself (DRY) Principle</h3><p>KISS and DRY are very fundamental concepts in software development and can help you write clean Java code. The DRY principle states that as a developer, you should ensure that your code is not duplicated multiple times across the system. Eliminating code duplication improves your code maintainability and makes finding and fixing bugs easier.</p><p>The KISS principle emphasizes that we should strive to keep the design and development of the software we build simple and straightforward. By following this principle, you can avoid unnecessary complexity in your code and instead opt to write simple and understandable code.</p><p>The KISS principle promotes the maintainability of your code and makes it more readable. Maintainable and readable code improves collaboration and eases the onboarding of developers into the project.</p><h3>12. The Source Files Structure</h3><p>A typical source file in Java contains different elements that are key in running any Java program. To maintain the readability of your code, you should enforce a consistent source file structure. Although there is no one-size-fits approach to structuring your source file, there are popular style guides that you can follow.</p><p>Normally a typical ordering of a source file structure in Java begins with package statements followed by static and non-static import statements, preceded by one primary top-level class.<br>11. THE SOURCE FILES STRUCTURE</p><p>A typical source file in Java contains different elements that are key in running any Java program. To maintain the readability of your code, you should enforce a consistent source file structure. Although there is no one-size-fits approach to structuring your source file, there are popular style guides that you can follow.</p><p>Normally a typical ordering of a source file structure in Java begins with package statements followed by static and non-static import statements, preceded by one primary top-level class.</p><pre>    // Class variables<br>    private static int count;<br>    private String name;<br>    <br>    // Instance variables<br>    private int age;<br>    private List&lt;String&gt; hobbies;<br>    // Constructors<br>    public MyClass() {<br>        // Constructor implementation<br>    }<br>    <br>    public MyClass(String name, int age) {<br>        // Constructor implementation<br>    }<br>    <br>    // Methods<br>    public void setName(String name) {<br>        // Method implementation<br>    }<br>    <br>    public String getName() {<br>        // Method implementation<br>    }<br>    <br>    public void addHobby(String hobby) {<br>        // Method implementation<br>    }<br>    <br>    // Other methods<br>    <br>}<br>// Additional classes (if any)<br>class MyStaticClass {<br>    // Class implementation<br>}</pre><h3>13. Avoid Hard Coding Values</h3><p>Hardcoding refers to embedding values directly into your program’s source code instead of using variables. Altering the source code of your program is the only way to change values hardcoded into your programs. Hardcoded values limit reusability and testability and can also lead to duplication and undesired behavior from your program.</p><p>To improve code reusability, testability, and maintainability, which are key features of clean Java code, it is important that you avoid hard coding values in your program source code. Instead, replace hard-coded values with abstractions such as constant variables or enums.</p><p>Here’s an example of a Java program with hardcoded values.</p><pre>@RestController<br>public class HelloWorldController {<br>    @GetMapping(&quot;/hello&quot;)<br>    public String sayHello() {<br>        return &quot;Hello, World!&quot;;<br>    }<br>    <br>    @GetMapping(&quot;/user&quot;)<br>    public String getUser() {<br>        // hardcode values<br>        String username = &quot;John&quot;;<br>        int age = 30;<br>        return &quot;Username: &quot; + username + &quot;, Age: &quot; + age;<br>    }<br>    <br>    // Other controller methods<br>    <br>}</pre><h3>Conclusion</h3><p>Writing clean Java code is key to developing high-quality software.</p><p>In this article, we have shared some of the best and most common practices that can help you write clean Java code. However, it is important to note that this isn’t a definitive list of what it takes to write clean Java code. Other key factors that contribute to writing clean Java code include the culture, tools available, and goals of the team you’re working with. You can write readable, testable, extensible, and modular code by embracing these principles.</p><h3>FAQ</h3><h4><strong>What is clean code?</strong></h4><p>Clean code refers to readable, and maintainable code that is written based on best practices and conventions. It is code that is easy to understand, modify, and extend by both the original author and other developers. who inherited the code.</p><h4><strong>Why is it important to write clean Java code?</strong></h4><p>Clean code improves readability, enhances collaboration, reduces the chances of introducing bugs, and makes maintainability easier.</p><h4><strong>Are there tools that can help in writing clean Java code?</strong></h4><p>There are many tools that aid the process of writing clean Java code. Some include static code analysis tools such as SonarQube, FindBugs, and Digma. IDEs such as IntelliJ and Eclipse can also be helpful.</p><h4><strong>Which resources can I use to learn more about writing clean Java code?</strong></h4><p>Plenty of blogs and online tutorials exist, such as Baeldung. I would also recommend books such as “Clean Code: A Handbook of Agile Software Craftsmanship” by Robert C. Martin and “Effective Java” by Joshua Bloch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e88eacf10e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/best-practices-for-writing-clean-java-code-7e88eacf10e0">Best Practices for Writing Clean Java Code</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[11 JAVA DEBUGGING TIPS & TECHNIQUES USING INTELLIJ IDE]]></title>
            <link>https://medium.com/javarevisited/11-java-debugging-tips-techniques-using-intellij-ide-6e9ec1979d58?source=rss-478417ae25e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e9ec1979d58</guid>
            <category><![CDATA[intellij]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[devtools]]></category>
            <dc:creator><![CDATA[Nir Shafrir]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 09:00:02 GMT</pubDate>
            <atom:updated>2023-07-09T11:16:03.440Z</atom:updated>
            <content:encoded><![CDATA[<p>To reduce the time spent debugging, developers need to adopt effective debugging techniques and understand the power of modern Java debugging developer tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oXdyhX_EVdIQC_qe.png" /></figure><p>As a Java developer, I can’t help it but I often think about the good old days when I started my journey as a programmer. Back then, the systems we developed were relatively simple, and developers spent more time building software rather than fixing it. Sadly, gone are those days as the rise of distributed systems, microservices, and cloud-based computing has introduced a new level of <a href="https://digma.ai/blog/coding-horrors-tales-of-codebase-complexity/">complexity</a> and potential pitfalls to building software.</p><p>The realization that I’m spending much of my creative energy and time debugging software sometimes makes me think that maybe I’m not good at my job. However, it turns out that <a href="https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.444.9094&amp;rep=rep1&amp;type=pdf">software developers, in general, spend about 30 to 50 percent of their time debugging</a> and fixing software. Since, just like Maurice Wilkes, I realized that a large part of my life will be spent finding and fixing bugs in my code.</p><blockquote><strong>“I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs”. </strong><a href="https://www.azquotes.com/author/28840-Maurice_Wilkes"><strong>Maurice Wilkes</strong></a></blockquote><p>Rather than getting frustrated about how much time I spend debugging software, I decided instead to embrace it as an integral part of the software development lifecycle. And find the most efficient techniques to effectively debug or just write better code with fewer bugs in the first place.</p><p>However, to reduce the time we spend debugging, we need to adopt effective debugging techniques and understand the power of modern Java debugging developer tools.<br><br>So I decided to share some Java debugging tips and techniques you can use to debug Java apps using IntelliJ IDE. I’ll also discuss how to leverage the IntelliJ IDE debugging features to track down and fix bugs efficiently. I hope you get some value from it:)</p><h3>Here are the tips for debugging Java:</h3><h3>1. LEVERAGE IDE DEBUGGING CAPABILITIES</h3><p>Long gone are the times when developers used to skim through thousands of lines of code just to find the missing semicolon or bracket. Modern IDEs such as IntelliJ now include various tools that make debugging less excruciating.</p><p>For example, the IntelliJ IDE includes Java debugging features such as advanced breakpoints, integration with testing frameworks, remote debugging, and integration with testing frameworks.</p><p>Such features will save you time and enhance your visibility and precision while debugging.</p><h3>2. SETTING LINE BREAKPOINTS FOR PRECISE DEBUGGING</h3><p>Breakpoints are so common in programming chances are you have already encountered them. In real life, breakpoints are synonymous with red traffic lights that you are almost certain to encounter while driving, allowing you to temporarily stop, observe the surroundings, and ensure a safe passage before you resume your journey.</p><p>Similarly, line breakpoints are special markers that suspend the execution of a piece of code at a specific line of code. Pausing the execution of code just before the line of code is suspected to have a bug allows you to examine the program’s behavior at runtime.</p><figure><img alt="An example of setting line breakpoints for precise debugging" src="https://cdn-images-1.medium.com/max/920/0*cWCouHJ4DKzQKvFJ" /><figcaption>Line Breakpoints</figcaption></figure><h3>3. LEVERAGING WATCHPOINTS FOR TARGETED DEBUGGING</h3><p>Just like line breakpoints, watchpoints allow you to pause the execution of a program. However, unlike line breakpoints, watchpoints allow you to focus on a specific field. For instance, you can focus on a particular instance variable allowing you to pause and investigate your program behavior whenever that variable is read or written to.</p><p>This is very helpful when your program returns a wrong value. Setting a watchpoint allows you to investigate and correct the issue. Watch points are sometimes called data breakpoints.</p><p>To set a field watchpoint on IntelliJ, you can place a caret on the line where the field is declared and press <strong>Ctrl + F8.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/0*qW6jD306_X4i-ZaL" /><figcaption>Leveraging watchpoints</figcaption></figure><h3>4. STEP INTO SELECTION: FOCUSING ON SPECIFIC CODE SEGMENTS</h3><p>Debugging large Java code bases can be overwhelming, even for an experienced developer. There are many techniques that can be used to debug large codebases effectively. One of the most common strategies is using ‌IntelliJ ‌stepping actions.</p><p>IntelliJ IDEA provides different stepping functions that you can choose from depending on your strategy. Generally, stepping functions allow you to perform step-by-step execution of your code.</p><p>Step into is one of the step actions provided by Intellij. This technique is particularly useful whenever you’re unsure which methods in your code are returning the wrong result. Using this action, you can focus your debugging efforts on code segments that you think are more likely to cause issues.</p><p>IntelliJ IDEA, press the F7 function key to toggle this action. Alternatively, you can use the Step Into button under the debugger actions menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/0*LX6JzcDeAEA8sKvB" /></figure><p>It is also important to note that in cases where you have multiple method calls, it’s wise to use the Smart Step Into action. This action lets you choose which method to enter whenever you have multiple methods.</p><h3>5. STEP FILTERING: NAVIGATING CODE EXECUTION EFFICIENTLY</h3><p>Suppose you’re debugging a huge code base, and you’ve decided to use the step into action. However, upon further inspection, you realize your code includes helper methods and external libraries you don’t want to enter. This is where the step filtering action comes in handy.</p><p>Using the step filtering action in your IntelliJ IDEA allows you to skip through JDK classes, packages, and external libraries during debugging. The step filtering action streamlines your debugging process, allowing you to focus on debugging the most relevant sections of your code, saving you time and unnecessary mental strain.</p><p>You can set up Step Filtering by going to <strong>Settings -&gt; Build, Execution, Deployment -&gt; Debugger -&gt; Stepping</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7ho_D0iFDzRCjNAn" /></figure><h3>6. STEP OVER AND OUT: FINE-TUNING CODE EXECUTION DURING DEBUGGING</h3><p>We’ve highlighted how Step into Action can help you delve into methods, while Step filtering can be useful if you want to skip through unnecessary code. However, what if, during a debugging session, you wish to skip through a line of code that has a method call into the next line? This is where you can use the Step Over action.</p><p>The Step Over actions is useful whenever you are certain that the method implementation works fine. For instance, in the example below, skipping line 5 skips the debugger to line 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/0*zI3Sf_lqqJ38-XLf" /></figure><p>You can also use the step-out action to return to step out of the current method and return to the caller method.</p><h3>7. OPENTELEMETRY AND OBSERVABILITY</h3><p>If you have been developing applications for the last couple of years, certain practices such as continuous development and continuous integration (CI/CD), microservices, DevOps, and tools such as Docker and Kubernetes have become very popular.</p><p>These tools have allowed us to develop more distributed and complex systems that are loosely coupled. Relying on traditional Java debugging techniques for such applications isn’t reliable.</p><p>However, using modern observability tools, you can instrument your code and obtain valuable information such as logs, traces, and metrics.</p><p>One such observability tool that Java developers can use is OpenTelemety (OTel). OTel is an open-source observability framework made up of a collection of APIs, tools, and SDK. Using OTel, Java developers can collect, instrument, and analyze data and use it to understand, troubleshoot and fix bugs in complex distributed systems.</p><p>Another useful software tool that Java developers can leverage is <a href="https://www.jaegertracing.io/">Jaeger</a>. When working with complex distributed systems, Jaeger allows developers to gain visibility through features such as transaction monitoring, root cause analysis, service dependency analysis, and distributed context propagation.<br>Java developers can also use <a href="https://digma.ai/">Digma</a> to understand and debug complex code bases. Digma leverages OpenTelemetry behind the scene to collect data such as traces, logs, and metrics. Once the data is collected, Digma analyzes it to detect meaningful insights about the code. It looks for regressions, anomalies, code smells, or other patterns that can be useful for knowing about the code and its use making the debugging process much easier.</p><h3>8. USE THE VARIABLES VIEW AND EXPRESSION EVALUATION FOR COMPREHENSIVE INSIGHTS</h3><p>Debugging is an interactive process that involves changing values and refining code to see if the most recent changes work. However, as developers, sometimes we wish to have an idea of how the changes we intend to make will affect our code or how the output might change.</p><p>Instead of using print statements, variable inspection allows you to view variable values inline at the end of the line where they are used. Alternatively, if you would like more information about variables, the Variables tab under the Debug window enables you to do that. In this window, you can modify variables and observe the program’s behavior under certain conditions without affecting the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sjyWIWNmZa4OLLdb" /></figure><p>Examining your program’s state and the effect of potential code changes at runtime is also important. The Evaluate Expression editor provides a sandbox environment to test code changes and try variables. This can be useful when debugging code, and you’re not sure whether your changes will work.</p><h3>9. REMOTE DEBUGGING AND COLLABORATION</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0CM6f9Il3qIedxye" /></figure><p>The Covid pandemic has pushed most teams to remote working, which is the norm now for most development teams. Unfortunately, in such a setup, you can’t quickly have a physical debugging session with colleagues in different physical locations.</p><p>However, IDEs such as IntelliJ now have advanced features enabling you to collaborate with other developers. Collaborative debugging sessions enhance ‌productivity and knowledge sharing, allowing teams to solve complex bugs quickly.</p><p>Remote debugging and collaboration can also be useful if you’re working with distributed systems. If your program is running in a remote environment, using remote debugging allows you to connect to those environments and fix issues in real-time as if the code was running locally on your machine.</p><p>Remote Java debugging can also be useful whenever you wish to replicate different real-world scenarios, allowing you to observe how your application will behave in different use cases.</p><h3>10. THOROUGH TESTING AND VALIDATION</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/0*ug91q4TeAzh24nEn" /></figure><p>Testing your applications can help you evade debugging nightmares by enabling you to detect and fix issues in your code early in the development phase. This is commonly called proactive debugging, where developers focus on finding bugs before they occur.</p><p>There are different ways that you can leverage tests to identify bugs. You can start by making sure that you write comprehensive unit tests for your application. Unit tests are meant to ensure that individual code units in your program are working as intended. You can cover different edge cases, scenarios, and potential failure points through unit tests, increasing your chances of detecting potential bugs.</p><p>Besides unit tests, you should also use integration tests, functionality tests, and regression tests to ensure that different components in your program are working effectively. Using these tests, you can easily identify bugs that may come up due to compatibility issues or communication failures. You can also leverage system tests to uncover bugs that may come up when your app is deployed to real-world users.</p><h3>11. MAINTAIN A DEBUGGING CHECKLIST</h3><p>As simple as it sounds, maintaining a debugging checklist can save you from confusion and simply getting overwhelmed when debugging Java applications. Maintaining a Java debugging checklist can also help you maintain a systematic approach when debugging your applications.</p><p>Documenting your debugging details can also serve as a future point of reference whenever you face a similar bug again. Similarly, your team members can refer to the same document if they encounter a similar bug in future development. Such a practice can also improve knowledge sharing in your team.</p><h3>CONCLUSION: DEBUGGING JAVA USING INTELLIJ</h3><p>Debugging is a skill that every developer needs to have. However, mastering the art of easily finding and resolving bugs takes time and requires understanding the codebase you’re dealing with. In this article, we’ve shared Java debugging tools that, if incorporated into your debugging workflow, can help you debug faster and deliver robust applications.</p><h3>FAQ</h3><h3>What is Java debugging?</h3><p>Java debugging is the process of identifying and fixing errors and bugs in Java code, ensuring that an application works smoothly.</p><h3>How do I start Java debugging with IntelliJ or Eclipse?</h3><p>You need an IDE such as IntelliJ or Eclipse that has a set of debugging tools. To start Java debugging, you can set breakpoints in your code and run your Java program in debug mode.</p><h3>Is debugging Java using IntelliJ IDE easy?</h3><p>Java and model IDEs such as IntelliJ include a set of tools that make Java debugging easier. However, debugging depends on many other factors such as experience and availability of tools.</p><h3>What is the best debugger for Java?</h3><p>The choice of a debugger depends on your needs and personal preferences. However, modern IDEs such as IntelliJ, Eclipse, and VS Code have excellent debugging capabilities.<br><br>Digma is a runtime linter that lets developers quickly identify risky code, potential errors, and bottlenecks in complex codebases. Discover how Digma can help you with debugging Java apps using IntelliJ IDE: <a href="https://digma.ai/how-it-works/">Here.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e9ec1979d58" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/11-java-debugging-tips-techniques-using-intellij-ide-6e9ec1979d58">11 JAVA DEBUGGING TIPS &amp; TECHNIQUES USING INTELLIJ IDE</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>