Is there any easy method to add type safety to identifier properties?

After using C ++, I got used to the concept of an Identifier that can be used with a class for this type, provides type safety and does not have runtime overhead (the actual size is the size of the primitive). I want to do something like this, so I will not be mistaken, for example:

personDao.find(book.getId());//I want compilation to fail  
personDao.find(book.getOwnerId());//I want compilation to succeed

Possible solutions that I don't like:

  • For each object, there is an entity identifier class that wraps the id primitive. I don't like the bloat code.
  • Create a generic class Identifier. Code like this will not compile:

    void foo(Identifier<Book> book);
    void foo(Identifier<Person> person);

Does anyone know a better way?
Is there a library with a utility like this? Does this realize excess?
And the best thing is, can this be done in Java without the overhead of the object, as in C ++?

+3
source share
5 answers

I see that there is no good way to do what I wanted. Even if I use a class hierarchy, I have to manually integrate it with automatic id generators (for example, JPA annotation). Too much work. You just have to be careful. A possible solution would be annotation + validation, something like what intellij does with @Nullable and @NotNull, but I will not implement something similar to myself.

0
source

Java-equese - .

personDao.findByBookOwner(book);

. - API.

+2

, , , , - . , .

, :

Person person = session.get(Person.class, someId);
Person spouse = person.getSpouse(); // proxy, unless configured otherwise

Task t = new TalkToSpouseTask(spouse);
session.save(t);

.

, Java ++?

, Java ( , ). , -, .

0

Java , OO, , typedef, , -, ++ C. , , .

:

void foo(Identifier<Book> book);
void foo(Identifier<Person> person);

, . , :

void foo(Identifier param);

( ), .

0

- , , ( , (, float, - int)).

When you program in Java, you are not worried about the service data of the object, as long as it does not matter - this is when you see a problem with the profiling of the implementation. In most cases, JIT gets rid of problems, or you should just not start with.

Sometimes it matters, but don't try to guess too much where - you are most likely wrong.

0
source

Source: https://habr.com/ru/post/1746841/


All Articles