vendredi 13 janvier 2023

What's the best practices in C# for public members that must be used for internal use only?

In a scenario similar to the one described here, I have 2 different assemblies and I need to declare some members in classes of assembly A that must be used only by my classes in assembly B (I mean, who uses a class of the assembly A must be discouraged to call/use those methods/properties/fields).

What is the best practice to declare them?

  1. Creating an interface for them (so you need to explicitly cast the class of assembly A to the interface to see them)
  2. Naming them with a particular prefix (so I can "train my user" to avoid calling/using them)
  3. Naming them with the first letter lowercase (so Intellisense will put them at the end and they will be "more hidden")

Notes:

  • Assembly A is built against .net6 (cross-platform) and assembly B is built against net6-windows (O.S. Windows specific)
  • I can't use InternalsVisibleTo because Assembly A must be obfuscated and this prevents obfuscation for internal members.

Listed below is the code for a better explanation of those cases.


assembly A

case 1

public class Workspace : IWorkspaceInternal
{
   /// <summary>
   /// Does stuff.
   /// </summary>
   public void MyRealPublicMethod() { //do something }

   /// <summary>
   /// For internal use only.
   /// </summary>
   void IWorkspaceInternal.MyMethod1() { //do something }
}

/// <summary>
/// Interfaces with methods/properties/classes for internal use only.
/// </summary>
public interface IWorkspaceInternal
{       
   /// <summary>
   /// Does stuff.
   /// </summary>
   public void MyMethod1() { //do something }
}

case 2

public class Workspace
{
   /// <summary>
   /// Does stuff.
   /// </summary>
   public void MyRealPublicMethod() { //do something }

   /// <summary>
   /// For internal use only.
   /// </summary>
   public void Foo_Method1() { //do something }
}

case 3

public class Workspace
{
   /// <summary>
   /// Does stuff.
   /// </summary>
   public void MyRealPublicMethod() { //do something }

   /// <summary>
   /// For internal use only.
   /// </summary>
   public void myInternalMethod1() { //do something }
}

Other ideas?

Aucun commentaire:

Enregistrer un commentaire