Enforcing type safety of identifiers in Kotlin

栏目: IT技术 · 发布时间: 4年前

内容简介:For codebases with many different entities, most of us will at some point have hit a bug due to the wrong identifier being assigned to a property or passed to a function. Why don’t we use the type system to give all of our identifiers their own type and en

For codebases with many different entities, most of us will at some point have hit a bug due to the wrong identifier being assigned to a property or passed to a function. Why don’t we use the type system to give all of our identifiers their own type and ensure this never happens again.

It is very common for objects to need a form of identifier, frequently the reason being to refer to entities when communicating with a remote API or a database. We can easily implement this by giving our classes an ID property with an appropriate type, such as String , UUID or Long . An issue here is that imagine User and Team both have a String ID, it would be perfectly possible to pass a User ID to a function when we were meant to provide a Team ID instead.

Let’s explore the idea of enforcing type safety by giving our identifiers their own types. :pray:

Enforcing type safety of identifiers in Kotlin
Type safety

General types

One option for our IDs is to use the String type, especially if they are in an unexpected format. Another common type of identifier is a UUID , an implementation of which is provided by the Java standard library. UUID is designed for storing identifiers and is backed by a String in a specific format.

data class Team(val id: UUID, val size: Int)

data class TeamMember(val id: String, val name: String)

Wrapper type

Rather than relying on the general types, we can easily create a dedicated one.

data class Identifier(val rawValue: UUID)

If we require different raw types, we can either create extra identifier types that contain different raw types or use a single one with a generic type parameter. Using a generic version allows us to have properties or function arguments that require a particular type of identifier.

data class Identifier<RawT>(val rawValue: RawT)

Ensuring the correct type

There are some issues that can appear when using these general types internally. Say Team has a UUID ID and Member has a String ID:

  • Every Team ID is a UUID , but not every UUID refers to a valid Team .
  • A Member ID could have the same value as the raw String backing a Team ID, even though they refer to different entities.

Mixing and matching two different identifiers that use the same raw type is perfectly valid and not prevented by the compiler. We can do better than this! :arrow_double_up:

By adding a second generic type parameter to our Identifier we ca limit its use for a particular entity.

data class Identifier<EntityT, RawT>(
    val rawValue: RawT
)

data class Room(val id: Identifier<Room, UUID>)
data class Meeting(val id: Identifier<Meeting, UUID>)

fun bookMeeting(id: Identifier<Meeting, UUID>) {}

// :x: Compile error: Type mismatch.
bookMeeting(room.id)

Due to EntityT not actually being used within Identifier we will likely get a warning about it being unused, which can be ignored using @Suppress("unused") .

Type aliases

When our codebase has a variety of entities, the number of identifiers will grow and we are likely to get fed up of typing out the Identifier signature. We can rely on type aliases to simplify this task. A nice organisation tip is to store these alongside the entity they identify, making them easy to find.

// Team.kt

typealias TeamId = Identifier<Team, UUID>

data class Team(val id: TeamId)

Specifying identifiers in properties and functions is now so much simpler. :tada:

fun Team.inviteMember(id: MemberId) {}

// :x: Compile error: Type mismatch.
team.inviteMember(team.id)

// :white_check_mark: Compiles.
team.inviteMember(member.id)

Wrap up

By using a type that enforces type safety of our entity identifiers, we can make our model code safer to work on and avoid bugs due to an incorrect identifier being used. Our code will also be more readable as when we see an identifier we will know which entity it refers to. There may even be ways to extend this solution to make it even more powerful! :rocket:

What do you think of this approach to managing identifiers? Do you use something similar or something different all together? Please let me know any thoughts or questions you have on Twitter @lordcodes .

If you like what you have read, please don’t hesitate to share the article andsubscribe to my feed if you are interested.

Thanks for reading and happy coding! :pray:

Check out the sample code for this article on GitHub.


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

100个可操作的网络赚钱方法

100个可操作的网络赚钱方法

陶秋丰 / 云南科技 / 2009-12 / 29.80元

《100个可操作的网络赚钱方法》专为有志于网上创业的读者量身打造,作者是“实战型”的网赚高手,在17岁时就通过互联网创业“年人10万”,如今结合自身的亲身实战经验,与大家分享可以实实在在盈利的100个网络赚钱方法和技巧。内容包括:网站创建与推广、竞价广告、联盟赚钱、网站SEO优化、域名投资、广告投放盈利、威客、博客、淘客赚钱等多个方面。 本手册中作者结合自身的网络赚钱经历,通过具体的、可操作......一起来看看 《100个可操作的网络赚钱方法》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具