user3010678
user3010678

Reputation: 142

How to share code cleanly between client and server?

I have a game client written in Unity and a Server written in Azure Functions. I have a class library in the Azure Function solution with "Domain" classes that will be shared between both client and server. I build the class library to a DLL and drop it in a Plugins folder in Unity, so I can use the shared code in the game client.

This works well, but I came across a situation where I need the game client to have special properties that I don't want the server to have in its solution because it just adds complexity and dependencies (such as dependencies on the Unity Game engine for example that have no business in the server).

What's the cleanest way to make a class that can be enhanced in the game client but kept basic in the server?

Option 1:

use inheritance

public class DomainGun
{
    public int BulletCount;
    public string Name;

    public DomainBullets Bullets;
}

public class DomainBullets 
{
   public string Property;
}

public class GameClientBullet: DomainBullets
{
    BulletRendere Renderer;
}

This fails, because now I have to downcast from DomainBullets to GameClientBulletto get to the Renderer when I do things with the DomainGun on the client.

I can probably do it with generics.

public class DomainGun
{
    public int BulletCount;
    public string Name;

    public DomainBullets Bullets;
}

public class DomainBullets<T>
{
   public string Property;
   public T Renderer;
}

    
   //now I can do this on the server:
    public interface IBulletRenderer
    {
        //placeholder that has nothing in it
    }    
   
   //and this on the client..
    public class BulletRenderer
    {
       UnityRenderingThing UnityDependentThing;
    }

I think this will work - allows me to have shared properties in one place, and then have the client make it more specialized, but using generics in this way with an empty interface feels like a code smell.

I think there is a more clever way to do this with interfaces, but I am spacing right now. Appreciate any ideas.

Upvotes: 0

Views: 306

Answers (1)

Shameel
Shameel

Reputation: 802

Use the decorator design pattern. Keep the base class on the server and the decorator on the client.

https://www.dofactory.com/net/decorator-design-pattern

Upvotes: 1

Related Questions