Part 2 of Pattern Matching in Switch - Java

This is the part 2 of the blog covering switch expressions in Java. If you haven't read part 1 yet, please give it a read here as it would cover some of the basic understanding of the switch expression and pattern matching in switch.


Switch Exhaustiveness
Java compiler doesn't force exhausti...

? https://www.roastdev.com/post/....part-2-of-pattern-ma

#news #tech #development

Favicon 
www.roastdev.com

Part 2 of Pattern Matching in Switch - Java

This is the part 2 of the blog covering switch expressions in Java. If you haven't read part 1 yet, please give it a read here as it would cover some of the basic understanding of the switch expression and pattern matching in switch.


Switch Exhaustiveness
Java compiler doesn't force exhaustiveness in switch statements, whereas switch expression are expected to be exhaustive. What really is exhaustiveness? Exhaustiveness ensures that all possible cases are handled in a switch expression, either explicitly or with a default case. For example, When you use an enum type, switch must cover different values of the enum. This is not limited to enums, its applicable to all the types switch supports. Look at the below versions of code, former one with switch statement and the later with switch expressions. This snippet of code compiles and runs fine, without any complaints for not having a case for GREEN.
⛶enum Color {
RED, GREEN, BLUE
}

private static String switchForEnum(Color color) {
String hexCode = null;
switch (color) {
case RED:
System.out.println("Color is red..");
hexCode = "#FF0000";
break;
case BLUE:
System.out.println("Color is blue");
hexCode = "#0000FF";
break;
}
return hexCode;
}Whereas below code will fail to compile with an error: the switch expression does not cover all possible input values. Switch expressions are expected to be exhaustive and the code that does not cover all possible cases, or lacks a Match-All case will result in compiler error. Exhaustiveness enforced in switch expressions because, unlike switch statements, switch expressions are expected to return a value or throw an exception. In the cases, where a case covering a particular value, or a match-all case is missing, switch wont be returning anything and it will cause runtime errors.
⛶private static String switchExpForEnum(Color color) {
return switch (color) {
case RED - {
System.out.println("Color is red..");
yield "#FF0000";
}
case BLUE - {
System.out.println("Color is blue");
yield "#0000FF";
}
// Error can be fixed by uncommenting any of the below code blocks
/*
case GREEN - {
System.out.println("Color is green");
yield "#00FF00";
}
*/
/*
default - {
System.out.println("Color is unknown");
yield "#FFFFFF";
}*/
};
}The above code can be corrected by either adding a case for handling color GREEN or by adding a match-all case. Its better to add explicit case for color GREEN than a default, as default case would sweep issues under the rug if you may have to introduce more values to the enum in the future.Have you noticed that there are no break statements, and there is new term yield?
switch statements are naturally fall-through, ie. without break statements between cases, execution would naturally continue to all the cases below the one that's matched until it encounters break or end of switch. This can cause for lot of troubles and switch expressions are designed to eliminate the fall-through behavior, so there is no need for break making the code concise and safe.
yield is a restricted identifier (not a keyword) introduced to return a value from the statement group matching a case in switch expression, similar to the keyword return used in switch statements.



Records patterns in switch
We have seen Typed Pattern in switch expression in the part 1 of the blog.
Records patterns allows pattern matching for record types and deconstruction of the record components directly in a switch expression. This feature is finalized in Java 21. Lets look at an example for the same.
⛶sealed interface Quad permits Rectangle, Square, Kite {
static double calculatePerimeter(Quad quad) {
return switch(quad) {
case Rectangle(double len, double bre) - 2 * (len + bre);
case Square(double s) - 4 * s;
case Kite(double shortSide, double longSide, _, _) - 2 * (shortSide + longSide);
};
}
}

record Rectangle(double length, double breadth) implements Quad {}
record Square(double side) implements Quad {}
record Kite(double short_side, double long_side, double short_diag, double long_diag) implements Quad {}Quad is a sealed interface which allows 3 records Rectangle, Square and Kite (classes with immutable data components) to implement its functionalities. Check the usage of the Record pattern in switch expression inside calculatePerimeter method.
Given switch expression takes a Quad type and its exhaustive, covering all the allowed record types. If you were to allow another record type for Quad, matching case arm should be added to the switch.
The labels used in the above cases are called Record Patterns. Observe that the components of the records are deconstructed into 1 or more pattern variables and are available directly to use.
Notice the usage of "_" in the last case. If there is any data component that you don't use in your logic, it need not be assigned to any variable. So, if you add an underscore, they are just ignored.



Nested record patterns
Above examples shows top level pattern matching. Records can be nested too ie.. one record can be a component of another record. Switch expressions allows nested pattern matching and nested deconstruction as well. Lets see it as an extension of the above code snippet.
⛶sealed interface Quad permits Rectangle, Square, Kite, Parallelogram {
static double calculatePerimeter(Quad quad) {
return switch(quad) {
// assuming all cases exists for Rectangle, Square and Kite from previous code
case Parallelogram(Coordinate(double x1, double y1), Coordinate(double x2, double y2)) -
2 * (Math.hypot(x1, y1) + Math.hypot(x2, y2));
};
}
}

record Coordinate(double x, double y) {}
record Parallelogram(Coordinate p1, Coordinate p2) implements Quad {}Now, we have one more Quad variant - Parallelogram which has 2 nested components p1 and p2, instances of Coordinate record. In the switch expression, we added a case to perform top level matching of the Parallelogram type, and also deconstructs its nested Coordinate record components into their double types. These are nested records patterns.We have seen how switch expressions makes the code more concise and functional, enhancing the safety and readability. Thank you reading up until this point. If you would like to read more such blogs or share your thoughts, write me at LinkedIn or Email.


References

https://openjdk.org/jeps/440
https://openjdk.org/jeps/441
https://openjdk.org/projects/amber/design-notes/patterns/exhaustiveness

Similar Posts

Similar

Vector Databases: The Secret Sauce for AI-Powered Search (That Won't Make Your Brain Explode)




Welcome to the Future, Where Databases Have Superpowers
Hey there, fellow code wrangler! ? Remember when databases were just boring tables of data? Well, buckle up, because we're about to dive into the world of vector databases – the cool kids on the block that are making AI-powered se...

? https://www.roastdev.com/post/....vector-databases-the

#news #tech #development

Favicon 
www.roastdev.com

Vector Databases: The Secret Sauce for AI-Powered Search (That Won't Make Your Brain Explode)

Welcome to the Future, Where Databases Have Superpowers
Hey there, fellow code wrangler! ? Remember when databases were just boring tables of data? Well, buckle up, because we're about to dive into the world of vector databases – the cool kids on the block that are making AI-powered search feel like magic. But don't worry, I promise not to make your brain ooze out of your ears. Let's keep it fun, shall we?


What's the Big Deal with Vector Databases?
Imagine you're at a party (yes, developers do attend parties occasionally), and you're trying to find someone who shares your passion for obscure 80s sci-fi movies. In a regular database, you'd have to go person by person, asking, "Do you like 'Buckaroo Banzai'?" Exhausting, right?Now, picture a party where everyone's interests are floating around them like colorful bubbles. You just need to look for bubbles that match yours. That's kind of what vector databases do – they turn data into these magical bubbles (vectors) that can be compared super quickly.


The Top Players in the Vector Database Game
Let's break down some of the coolest vector databases out there. Don't worry; I won't bore you with a dry list. Instead, let's imagine these databases as characters in a tech superhero movie.


1. Milvus: The Speed Demon
Milvus is like that friend who always knows the fastest route to the coffee shop. It's open-source, scalable, and faster than my cat when she hears the treat bag opening.

Superpowers: Lightning-fast queries and the ability to handle billions of vectors

Secret Weakness: Sometimes overwhelmed by its own speed (needs careful tuning)

⛶# Quick Milvus example (because who doesn't love code snippets?)
from pymilvus import Collection, connections

connections.connect()
collection = Collection("my_collection")
results = collection.search(vectors_to_search, "embedding", param, limit=10)


2. Pinecone: The Cloud Native Hero
Pinecone is like that friend who's always in the cloud (literally). It's fully managed, which means less headache for you.

Superpowers: Effortless scaling and real-time updates

Secret Weakness: Can be a bit pricey if you're on a shoestring budget



3. Weaviate: The Flexible Shape-Shifter
Weaviate is the Swiss Army knife of vector databases. It's not just about vectors; it can handle all sorts of data types.

Superpowers: Combines vectors with traditional data storage

Secret Weakness: Jack of all trades, master of... well, actually, it's pretty good at everything



4. Qdrant: The New Kid on the Block
Qdrant is like that fresh-faced intern who surprises everyone with their skills. It's relatively new but packs a punch.

Superpowers: Great filtering capabilities and a user-friendly API

Secret Weakness: Still building its reputation in the big leagues



Why Should You Care?
Now, you might be thinking, "Cool story, bro, but why should I care about vector databases?" Well, let me tell you a little story.Last month, I was working on a project to build a recommendation system for a streaming service (let's call it "Betflix"). We started with a traditional database, and searching through millions of movies was slower than my grandma's internet connection.Then we switched to a vector database. Suddenly, our recommendations were flying faster than rumors at a tech conference. User engagement shot up, and the client was so happy they sent us a year's supply of energy drinks (I'm still buzzing).


The Real-World Magic of Vector Databases
Vector databases aren't just for movie recommendations. They're the unsung heroes in:

Image and Face Recognition: Ever wonder how your phone knows it's you even with that questionable lockdown haircut?

Natural Language Processing: Chatbots that actually understand you (most of the time).

Anomaly Detection: Spotting weird patterns in data faster than you can say "that's sus".

Personalized Experiences: Like when a shopping site seems to read your mind (creepy, but convenient).



Tips for Choosing Your Vector Database Sidekick
Picking the right vector database is like choosing a programming language – it depends on your specific needs. Here are some tips:

Know Your Scale: Are you dealing with millions of data points or billions?

Consider Your Resources: Do you have a team of database wizards or are you flying solo?

Think About Integration: How well does it play with your existing tech stack?

Future-Proof Your Choice: Look for databases that are actively developed and have a strong community.



Wrapping Up: The Future is Vectored
Vector databases are changing the game in AI-powered search. They're making our applications smarter, faster, and dare I say, cooler. Whether you're building the next big thing in tech or just trying to make sense of a mountain of data, vector databases are your new best friend.Remember, in the world of data, it's not about how much you have, but how quickly you can find what you need. And vector databases? They're like having a superpower for your data.So, go forth and vectorize! Your future self (and your users) will thank you.If you enjoyed this dive into the vector-verse, follow me for more tech talk that won't make your brain buffer. And remember, in the world of databases, it's hip to be square... or in this case, a multi-dimensional vector! ?
Similar

Cobertura de pruebas en Spring Boot con Jacoco y SonarCloud: configuración paso a paso

Hace poco me encontré con un problema bastante común al trabajar con proyectos en Spring Boot y SonarCloud: la cobertura de pruebas no se estaba reportando correctamente. Aunque las pruebas se ejecutaban sin errores, en SonarCloud la cobertura aparecía como si fuera 0%. ?Después de investigar...

? https://www.roastdev.com/post/....cobertura-de-pruebas

#news #tech #development

Favicon 
www.roastdev.com

Cobertura de pruebas en Spring Boot con Jacoco y SonarCloud: configuración paso a paso

Hace poco me encontré con un problema bastante común al trabajar con proyectos en Spring Boot y SonarCloud: la cobertura de pruebas no se estaba reportando correctamente. Aunque las pruebas se ejecutaban sin errores, en SonarCloud la cobertura aparecía como si fuera 0%. ?Después de investigar y probar diferentes configuraciones, logré que todo funcionara. Aquí te comparto lo que hice, por si te sirve.


1. Agregar la dependencia de mockito-inline
Uno de los problemas que tuve al usar Mockito fue con clases finales o métodos estáticos. Para solucionarlo, agregué esta dependencia en el archivo pom.xml:
⛶org.mockito
mockito-inline
5.2.0
test


2. Configurar Jacoco correctamente
El plugin de Jacoco debe estar bien configurado para generar el archivo jacoco.xml, que es el que SonarCloud usa para calcular la cobertura. Esta fue la configuración que usé en el pom.xml:
⛶org.jacoco
jacoco-maven-plugin
0.8.8


prepare-agent

prepare-agent


${project.build.directory}/jacoco.exec
surefireArgLine



report
test

report



XMLTambién fue necesario configurar el plugin de Surefire para que reciba los argumentos necesarios:
⛶org.apache.maven.plugins
maven-surefire-plugin

@{surefireArgLine} -Xshare:off


3. Configurar SonarCloud
Para que SonarCloud encuentre el archivo generado por Jacoco, es necesario agregar la siguiente ruta en su configuración:
⛶sonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xmlPuedes hacer esto de dos formas:
En el archivo sonar-project.properties (si lo estás usando).
O directamente en la configuración del proyecto en la web de SonarCloud:

Ve a tu proyecto en SonarCloud.
Abre Administration General Settings JaCoCo.
En el campo "Path to XML report", coloca:

⛶target/site/jacoco/jacoco.xml


✅ Resultado
Después de aplicar estas configuraciones y ejecutar:
⛶mvn clean verifyEl reporte de cobertura fue generado correctamente y SonarCloud empezó a reconocer la cobertura real de las pruebas. ?


? Conclusión
No siempre es obvio cómo conectar bien Jacoco con SonarCloud en un proyecto Spring Boot, especialmente si estás empezando. Espero que este post te haya ayudado a evitar horas de prueba y error.
Similar

Microsoft Copilot – Could It Transform How We Work

With AI firmly taking center stage following the launch of ChatGPT in late 2022, it’s clear that AI is rapidly becoming embedded in all aspects of our digital lives. Microsoft, having made significant investments in OpenAI and AI integration, continues to embed AI capabilities across its entire pr...

? https://www.roastdev.com/post/....microsoft-copilot-co

#news #tech #development

Favicon 
www.roastdev.com

Microsoft Copilot – Could It Transform How We Work

With AI firmly taking center stage following the launch of ChatGPT in late 2022, it’s clear that AI is rapidly becoming embedded in all aspects of our digital lives. Microsoft, having made significant investments in OpenAI and AI integration, continues to embed AI capabilities across its entire product ecosystem.


Microsoft’s AI Investment and Partnership with OpenAI
Microsoft's initial $10 billion investment in OpenAI at the start of 2023 marked a major commitment to AI innovation. This partnership was extended, positioning Microsoft as OpenAI's exclusive cloud provider and deeply integrating OpenAI's models into Azure AI services. This allows enterprises to use OpenAI’s advanced AI capabilities securely with their own private and sensitive data.


GitHub Copilot Evolution
Having acquired GitHub in 2018, Microsoft introduced GitHub Copilot in October 2021—an AI-powered coding assistant that leverages vast public code repositories to provide context-aware code suggestions directly inside VS Code and Visual Studio. This accelerated developers’ workflows by suggesting common code structures and automating routine coding tasks.In September 2023, Microsoft announced a major upgrade: GitHub Copilot Chat. This feature extends traditional code completion by offering a chat-based AI assistant that developers can interact with in real time. Features include:Real-time guidance tailored to coding challenges and best practices.
Code explanations and breakdowns of logic.
Security vulnerability identification and remediation suggestions.
Interactive debugging assistance.As of mid-2024, GitHub Copilot and Copilot Chat have expanded support beyond individuals to enterprise environments with more customization and context-awareness powered by enterprise data.


Microsoft 365 Copilot Goes Mainstream
Announced in early 2023 and rolling out progressively through 2023 and 2024, Microsoft 365 Copilot integrates OpenAI’s models directly into Microsoft 365 apps like Word, Excel, Outlook, Teams, and PowerPoint. Powered by organization-specific context and data (Microsoft Graph, SharePoint, OneDrive), it transforms productivity by:
Summarizing long Teams meetings with action points and follow-ups automatically.
Generating draft emails, reports, and presentations using natural language prompts.
Extracting insights from complex datasets and automating data analysis in Excel.
Dynamically creating and assigning tasks from meeting discussions.
Security and governance remain critical. Organizations must ensure data used by Copilot complies with privacy and regulatory standards and provide employee training for adoption. Microsoft continues to improve controls for data privacy and transparency in Copilot’s AI usage.


Windows Copilot Introduced for End Users
Windows Copilot rolled out with the Windows 11 2023 Update and is now generally available. It brings AI-driven assistance directly to users’ desktops, accessible via the taskbar or Win+C shortcuts. Its aim is to simplify everyday tasks with AI, without requiring users to understand the underlying technology. Highlights of the updated Windows Copilot include:
AI enhancements in built-in apps like Paint (background removal, AI-assisted creation), Photos (background blur, content-based photo search), and Snipping Tool (image text extraction and redaction).
Clipchamp integration for AI-assisted video editing with automatic scene creation and narration.
Notepad improvements including session restore and unsaved content recovery.
New Outlook for Windows integrating email accounts with AI-powered writing assistance.
Modernized File Explorer with intelligent search, collaboration insights, and new Gallery views for photos.
Accessibility improvements with advanced voice authoring tools and new Narrator voices.
Windows Backup feature streamlining PC migration with full app and settings transfer.
The Windows Copilot experience continues to evolve with monthly Windows updates, with Microsoft advancing AI-powered usability and task automation directly on the desktop.


Transforming Website Development with Microsoft Copilot
Microsoft Copilot is also reshaping the world of web development by providing AI-powered assistance that accelerates and enhances developers’ workflows. With tools like GitHub Copilot and Copilot Chat integrated into popular development environments such as Visual Studio Code, web developers can rapidly prototype, write, and debug their code with context-aware AI suggestions.Key impacts on web development include:
Faster Coding: Copilot suggests full code snippets, components, and boilerplate code in real time, significantly reducing manual typing and speeding up feature implementation.
Improved Code Quality: The AI helps catch potential bugs, security vulnerabilities, and performance issues early by recommending best practices and writing test cases.
Simplified Learning Curve: Junior developers benefit from explanations of complex code and learn how to use new frameworks or APIs quickly with natural language queries answered directly within the IDE.
Enhanced Collaboration: Copilot can generate documentation, code comments, and technical specifications, facilitating clearer communication across distributed development teams.
Customization and Context Awareness: Enterprises can fine-tune Copilot with their internal coding standards and repositories, ensuring AI suggestions align with company requirements and branding.
Overall, Microsoft Copilot is transforming web development from a labor-intensive process to a more creative, efficient, and collaborative discipline — empowering developers to focus on innovation rather than repetitive coding tasks.



Looking Ahead: The AI Era Has Truly Begun
While concerns around job impacts and data privacy remain, these AI tools aim to augment human skill rather than replace it, automating repetitive or tedious tasks and allowing us to focus on higher-value, creative, or strategic work.The first generation of AI-powered Copilots is just the beginning. As the models improve and new capabilities emerge, we can expect AI to become an indispensable part of how we work, create, and communicate in the years ahead.It’s an exciting time to witness and participate in this transformation. Let’s embrace these new possibilities and see where they take us next!