Type matching in java

Type matching in Java equals — getClass() vs. instanceof

There is an ongoing dispute on how type matching in the equals method should be implemented. A nice overview article can be found in Angelika Langers Secrets of equals() — Part 1 where you can find additional useful references. In short there are two possible ways to test the object’s type in the equals method:

 if (!(obj instanceof SomeClass))

The properties of the getClass() approach can be summarized as:

  • you can add fields into the subtypes and use them in subtype’s equals method. The notoriously popular example is that of subclassing the Point class to a ColorPoint class by adding an extra color field to it. The overridden equals in ColorPoint can match the point’s coordinates and also it’s color.
  • The drawback of this approach is that the supertype Point can never be equal to its subtype ColorPoint (a good example is in Josh Bloch’s book Effective java, chapter 3)

Simply put in the instanceof approach:

  • the subtype and supertype can be equal,
  • but equals is constrained to matching supertype fields only. The instanceof in supertype’s equals method does not reveal which type of the class hierarchy you are currently examining. As a result you only use supertype’s equals method and therefore you check only fields common to all types in the hierarchy. There is no way to add a field in a subtype that will be checked in the subtype’s overridden equals method without breaking the properties of equivalence relation.
Читайте также:  Python while if elif

At this point we see that one can argue for both approaches, but there is another aspect that makes a big difference. The former approach does not conform to the Liskov Substitution Principle — LSP while the latter does. For starters a good description of LSP is in the article from Robert C. Martin, the original Liskov paper is a bit tough to read. There are several formulations of LSP, I think about LSP as:

The subtype can’t break the contract between the supertype and method (function) where it is used.

Although the getClass() approach breaks LSP the debate around getClass() vs. instanceof still goes on.

On both projects I’ve worked so far (I am a junior dev) the getClass() approach was used for “better flexibility”. Although the LSP is a design guideline not a rigid OO theorem there are numerous simple examples where not following the LSP might cause problems. Consider a Shape class that checks whether a Point is the Shape s center:

 class Shape  public boolean isCentre(Point p)  Point centre = getCentre(); return centre.equals(p); > >

If this method is called with a ColorPoint the result is false although the ColorPoint might have the shapes center coordinates. The ColorPoint violates the conditions of the isCentre method which was imposed by the isCentre ⇿ Point contract and thus breaks the LSP. This behaviour is a trap for a developers.

A safe way to do type matching that conforms to OO principles is by using the instanceof operator. It is of course true that systems can be also implemented with the getClass() approach, you just won’t be able to rely on the logical equivalence in the system.

Site proudly generated by Hakyll

Источник

Pattern Matching for instanceof in Java 14

announcement - icon

Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.

Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.

The feedback is available from the minute you are writing it.

Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.

Of course, Digma is free for developers.

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we’ll continue our series on Java 14 by taking a look at Pattern Matching for instanceof which is another new preview feature included with this version of the JDK.

In summary, JEP 305 aims to make the conditional extraction of components from objects much simpler, concise, readable and secure.

2. Traditional instanceOf Operator

At some point, we’ve probably all written or seen code that includes some kind of conditional logic to test if an object has a specific type. Typically, we might do this with the instanceof operator followed by a cast. This allows us to extract our variable before applying further processing specific to that type.

Let’s imagine we want to check the type in a simple hierarchy of animal objects:

if (animal instanceof Cat) < Cat cat = (Cat) animal; cat.meow(); // other cat operations >else if (animal instanceof Dog) < Dog dog = (Dog) animal; dog.woof(); // other dog operations >// More conditional statements for different animals

In this example, for each conditional block, we’re testing the animal parameter to determine its type, converting it via a cast and declaring a local variable. Then, we can perform operations specific to that particular animal.

Although this approach works, it has several drawbacks:

  • It’s tedious to write this type of code where we need to test the type and make a cast for every conditional block
  • We repeat the type name three times for every if block
  • Readability is poor as the casting and variable extraction dominate the code
  • Repeatedly declaring the type name means there’s more likelihood of introducing an error. This could lead to an unexpected runtime error
  • The problem magnifies itself each time we add a new animal

In the next section, we’ll take a look at what enhancements Java 14 provides to address these shortcomings.

3. Enhanced instanceOf in Java 14

Java 14, via JEP 305, brings an improved version of the instanceof operator that both tests the parameter and assigns it to a binding variable of the proper type.

This means we can write our previous animal example in a much more concise way:

if (animal instanceof Cat cat) < cat.meow(); >else if(animal instanceof Dog dog)

Let’s understand what is happening here. In the first, if block, we match animal against the type pattern Cat cat. First, we test the animal variable to see if it’s an instance of Cat. If so, it’ll be cast to our Cat type, and finally, we assign the result to cat.

It is important to note that the variable name cat is not an existing variable, but instead a declaration of a pattern variable.

We should also mention that the variables cat and dog are only in scope and assigned when the respective pattern match expressions return true. Consequently, if we try to use either variable in another location, the code will generate compiler errors.

As we can see, this version of the code is much easier to understand. We have simplified the code to reduce the overall number of explicit casts dramatically, and the readability is greatly improved.

Moreover, this kind of type of test pattern can be particularly useful when writing equality methods.

4. Conclusion

In this short tutorial, we looked at Pattern Matching with instanceof in Java 14. Using this new built-in language enhancement helps us to write better and more readable code, which is generally a good thing.

As always, the full source code of the article is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью