decentralized-identity / decentralized-identity/web5-rs

Standardize "new" associated functions

Open
#141 1 comment 0 reactions 1 assignee Assigned to @kirahsapong View on GitHub
Dominant language
Kotlin
Stars
19
Forks
15
PR merge metrics
No merged PRs in 30d

Description

Let's standardize the way we instantiate types as to be consistent everywhere.

1. Name the associated function `new()` rather than `create()`
2. Use a single parameter to each `new()` function, named `params`
3. Make use of the UDL's `dictionary` specifically for the `params` types

## Name the associated function `new()` rather than `create()`

UniFFI automatically detects an associated function with the name `new()` for the `interface`'s `constructor` function. From [here](https://mozilla.github.io/uniffi-rs/udl/interfaces.html):

> By convention, the `constructor()` calls the Rust's `new()` method.

So let's settle on `new()` rather than `create()`.

## Use a single parameter to each `new()` function, named `params`

Here's what we currently have for instantiating a `JwsHeader`:

```rust
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct JwsHeader {
pub alg: String,
pub kid: String,
pub typ: String,
}

impl JwsHeader {
pub fn new(alg: String, kid: String, typ: String) -> Self {
Self { alg, kid, typ }
}
```

Unfortunately, UniFFI will not support type aliases, so we have to duplicate the properties. Here's what the proposed pattern would be made up of:

```rust
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct JwsHeader {
pub alg: String,
pub kid: String,
pub typ: String,
}

#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct Params {
pub alg: String,
pub kid: String,
pub typ: String,
}

impl JwsHeader {
pub fn new(params: Params) -> Self {
Self {
alg: params.alg,
kid: params.kid,
typ: params.typ,
}
}
```

## Make use of the UDL's `dictionary` specifically for the `params` types

Following the same example for the `JwsHeader`, here's how we would code the UDL interface for `JwsHeader`. First, ensure that the `Params` type is renamed in the `lib.rs` like so:

```rust
use ::jws::{JwsHeader, Params as NewJwsHeaderParams};
```

Then we write the UDL like so:

```idl
dictionary NewJwsHeaderParams {
string alg;
string kid;
string typ;
};

interface JwsHeader {
constructor(NewJwsHeaderParams params);
};
```

---

It's unclear if this pattern will fit into place will all of our various types, so this work should be done comprehensively as to uncover any unforeseen incompatibilities.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.