Thoughts on the cast assistants

To reduce redundant code, I have some throw helper methods:

protected static X ThrowInvalidOperation(string operation, X a, X b) { throw new InvalidOperationException("Invalid operation: " + a.type.ToString() + " " + operation + " " + b.type.ToString()); } 

Using:

  public static X operator +(X a, X b) { if (...) { return new X(...); } return ThrowInvalidOperation("+", a, b); } 

Problem: Since the + operator should always return a value, I fixed this by making ThrowInvalidOperation return the value and call it with return ThrowInvalidOperation("+", a, b);

There are many shortcomings - one of them, because I can not name it from a method that returns a different type.
I want there to be a way to mark the helper function "always throws an exception", so the compiler stops tracking return values.

Q: What opportunities can I do for this?

+6
source share
1 answer

Make an exception:

 protected static Exception MakeInvalidOperation(string operation, X a, X b) { return new InvalidOperationException( "Invalid operation: " + a.type + " " + operation + " " + b.type); } 

Then drop it:

 throw MakeInvalidOperation("+", a, b); 

You are in good company:

 // Type: Microsoft.Internal.Web.Utils.ExceptionHelper // Assembly: WebMatrix.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 // MVID: 3F332B40-45DB-42E2-A4ED-0826DE223A79 // Assembly location: C:\Windows\Microsoft.NET\assembly\GAC_MSIL\WebMatrix.Data\v4.0_1.0.0.0__31bf3856ad364e35\WebMatrix.Data.dll using System; namespace Microsoft.Internal.Web.Utils { internal static class ExceptionHelper { internal static ArgumentException CreateArgumentNullOrEmptyException(string paramName) { return new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, paramName); } } } 

Although there is not much code for writing your own custom type Exception (or InvalidOperationException ) and defining some constructor that formats the message for you.

To reduce redundant code

When I hear this, I think of AOP , which is pretty well implemented by PostSharp. If you have a lot of redundant code, you should consider AOP, but keep in mind that this may be redundant.

+6
source

Source: https://habr.com/ru/post/958771/


All Articles