Skip to content

Improve Readability of Code Builders #400

@MitchRazga

Description

@MitchRazga

Is your feature request related to a problem? Please describe.
To make the code builders more readable, maintainable and performant, Rocks could make use of a custom InterpolatedStringHandler that automatically handles indentation, new-lines, string.Join etc.

With this, around 230 calls to writer.Indent could be removed entirely and the builder code would be significantly more readable. For example, code similar to below could now be a single call with an interpolated raw string literal:

writer.WriteLine($"internal {expectationsFullyQualifiedName}.Adornments.AdornmentsForHandler{memberIdentifier} This({instanceParameters})");
writer.WriteLine("{");
writer.Indent++;
writer.WriteLine("global::Rocks.Exceptions.ExpectationException.ThrowIf(this.Expectations.WasInstanceInvoked);");

I've developed one of these to use in my own codebase, so here is a snippet of what it can look like:

$$"""
// <auto-generated/>
#nullable enable

namespace {{containerNamespace}};

internal sealed partial class {{containerTypeName}} : {{interfaces:,}}
{
	private readonly Lock _lockObject = new();

	{{fields:newline}}

	public void Dispose()
	{
		{{disposables:newline}}
	}

	{{methods:newline}}
}
"""

Describe the solution you'd like
Implement a SourceCodeInterpolatedStringHandler (or similar named) handler that will format code to simplify indentation, new-lines, string.Join etc.

Describe alternatives you've considered

  • Leave as is.
  • Increase the usage of raw string literals and interpolated strings where already possible.

Additional context
With a custom InterpolatedStringHandler you can control internal buffers and format specific types differently.
So in addition to readability, there are potentially signifcant performance benefits since you can now reuse buffers (reducing allocations), specify initial capacities (avoiding grow + copies that DefaultInterpolatedStringHandler will do) and avoid materializing intermediary strings.

Hopefully this will also reduce the time it takes to run Rocks.CodeGenerationTest a bit.

This would not change any generated code output but we may discover some existing indentation bugs.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions