DarkRiftNetworking / DarkRift

DarkRift Networking by Unordinal
http://darkriftnetworking.com
Other
220 stars 67 forks source link

Add read methods to DarkRiftReader that use out parameters instead of return values #141

Closed CatSandwich closed 1 year ago

CatSandwich commented 2 years ago

Quick Description

Add read methods to DarkRiftReader that use out parameters instead of return values.

Explanation

Quick preface: This is merely a suggestion - take it or leave it. It's something I've made use of, so I'm putting it here in case you deem it useful enough to implement directly in the library.

Often when using DarkRift, writing new data types that get serialized can be a tiny bit tedious, and I've come across a pattern that makes it a tiny bit less so. This pattern is adding a set of read functions (extension methods in my implementation, but I'm suggesting they be built-in) that use out instead of a return value.

Why? Because it allows you to have the same method name for every read method, making for easier coding (can copy paste / duplicate lines without needing to change the method based on the type you're reading).

For example,

public string Payload;
public int IntPayload;

public void Deserialize(DeserializeEvent e)
{
    Payload = e.Reader.ReadString();
    IntPayload = e.Reader.ReadInt32();
}

becomes

public string Payload;
public int IntPayload;

public void Deserialize(DeserializeEvent e)
{
    e.Reader.Read(out Payload);
    e.Reader.Read(out IntPayload);
}

This is much nicer to my eyes, and quicker to write as I don't need to worry about the method name.

Below is my current implementation. It goes a bit further than my suggestion, but it's just to demonstrate how it may be implemented. Thanks for your time!

https://hastebin.com/iquhixoqeg.csharp

CatSandwich commented 2 years ago

Another thing to mention about this is that by having all read operations share a method name, it provides ease for reflection-based systems (don't need to make a dictionary of type to method names - just need to pass in "Read" and a Type to find the right overload).

4real commented 1 year ago

Merged the PR