Dica de TI: O que são constantes?

Dica de TI será uma série de posts com conteúdo sobre tecnologia. São posts curtos explicando alguns conceitos.Ao contrário das variáveis, que podemos alterar o valor conforme a necessidade do algoritmo a ser desenvolvido, as constantes precisam ser inicializadas e não podem ter o seu valor a...

? https://www.roastdev.com/post/....dica-de-ti-o-que-s-o

#news #tech #development

Favicon 
www.roastdev.com

Dica de TI: O que são constantes?

Dica de TI será uma série de posts com conteúdo sobre tecnologia. São posts curtos explicando alguns conceitos.Ao contrário das variáveis, que podemos alterar o valor conforme a necessidade do algoritmo a ser desenvolvido, as constantes precisam ser inicializadas e não podem ter o seu valor alterado.Embora constantes também ocupem espaço na memória, elas não são consideradas variáveis no sentido tradicional, pois seu valor NÃO muda. Uma constante armazena um valor único e imutável durante toda a execução do programa.

Similar Posts

Similar

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

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.