Skip to content

Commit 526767b

Browse files
Valkyrienyanko cleanup (#69)
* Remove extra blank lines * Simplify new() expressions * Remove redundant ToString()'s * Simplify using statements * Mark methods that don't access instance as static * Use Any() over Count() == 0 to improve performance * Make .Where statement more readable * Use Array.Empty for empty arrays (Performance) * Simplify conditions * Simplify default expressions * Use char over string (Performance) * Prefer explicit tuple names * Simplify null checks * update to 0.2.13 for code style updates --------- Co-authored-by: valkyrienyanko <[email protected]>
1 parent b12dac5 commit 526767b

32 files changed

+181
-245
lines changed

CHANGELOG.md

+4
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file.
44

55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
66

7+
## [0.2.13] 2024-09-15
8+
* General code cleanup by @valkyrienyanko. Make use of some C# language features such as target-typed `new()` to simplify code.
9+
* Potential breaking change: DispatchCommandToNode on DialogueRunner has been marked static. Users generally do not need to call this method directly, so it shouldn't affect most or possibly any projects.
10+
711
## [0.2.12] 2024-09-15
812
* Use file-scoped namespaces in all plugin scripts to reduce indentation, by @valkyrienyanko
913

Samples/SQLiteVariableStorage/SQLVariableStorage.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ public override bool TryGetValue<T>(string variableName, out T result)
5252
return true;
5353
}
5454

55-
result = default(T);
55+
result = default;
5656
return false;
5757
}
5858

@@ -97,7 +97,7 @@ public override bool TryGetValue<T>(string variableName, out T result)
9797
}
9898

9999
// otherwise TryGetValue has failed
100-
result = default(T);
100+
result = default;
101101
return false;
102102
}
103103

Samples/VisualNovel/Scripts/VisualNovelManager.cs

+6-6
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ private void OnDialogueComplete()
7373
GD.Print("Visual novel sample has completed!");
7474
}
7575

76-
private Dictionary<string, string> _bgShortNameToPath = new Dictionary<string, string>
76+
private Dictionary<string, string> _bgShortNameToPath = new()
7777
{
7878
{
7979
"bg_office", "res://Samples/VisualNovel/Sprites/bg_office.png"
@@ -97,7 +97,7 @@ public void Scene(string backgroundImage)
9797
_background.Texture = texture;
9898
}
9999

100-
private Dictionary<string, string> _audioShortNameToUuid = new Dictionary<string, string>
100+
private Dictionary<string, string> _audioShortNameToUuid = new()
101101
{
102102
{
103103
"music_funny", "res://Samples/VisualNovel/Sounds/music_funny.mp3"
@@ -110,7 +110,7 @@ public void Scene(string backgroundImage)
110110
}
111111
};
112112

113-
private List<AudioStreamPlayer2D> _audioPlayers = new List<AudioStreamPlayer2D>();
113+
private List<AudioStreamPlayer2D> _audioPlayers = new();
114114

115115
private async void PlayAudio(string streamName, float volume = 1.0f, string doLoop = "loop")
116116
{
@@ -141,9 +141,9 @@ private class Actor
141141
public TextureRect Rect;
142142
}
143143

144-
private Dictionary<string, Actor> _actors = new Dictionary<string, Actor>();
144+
private Dictionary<string, Actor> _actors = new();
145145

146-
private Dictionary<string, string> _spriteShortNameToPath = new Dictionary<string, string>
146+
private Dictionary<string, string> _spriteShortNameToPath = new()
147147
{
148148
{
149149
"biz-guy", "res://Samples/VisualNovel/Sprites/biz-guy.png"
@@ -168,7 +168,7 @@ private Vector2 GetPosition(string coordinateX, string coordinateY)
168168

169169
// utility function to convert words like "left" or "right" into
170170
// equivalent screen ratios, where 0 for an x coordinate is extreme left
171-
private float GetCoordinate(string coordinate)
171+
private static float GetCoordinate(string coordinate)
172172
{
173173
switch (coordinate)
174174
{

addons/YarnSpinner-Godot/Editor/YarnImporter.cs

+4-7
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ public override Error _Import(
5555
var saveErr = ResourceSaver.Save(importedMarkerResource, $"{savePath}.{_GetSaveExtension()}");
5656
if (saveErr != Error.Ok)
5757
{
58-
GD.PrintErr($"Error saving yarn file import: {saveErr.ToString()}");
58+
GD.PrintErr($"Error saving yarn file import: {saveErr}");
5959
}
6060

6161
return (int) Error.Ok;
@@ -70,10 +70,8 @@ public override Error _Import(
7070
/// <returns>The hash of <paramref name="inputString"/>.</returns>
7171
private static byte[] GetHash(string inputString)
7272
{
73-
using (HashAlgorithm algorithm = SHA256.Create())
74-
{
75-
return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
76-
}
73+
using HashAlgorithm algorithm = SHA256.Create();
74+
return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
7775
}
7876

7977
/// <summary>
@@ -108,8 +106,7 @@ public static string GetHashString(string inputString, int limitCharacters = -1)
108106
}
109107
}
110108

111-
112-
private void ImportYarn(string assetPath)
109+
private static void ImportYarn(string assetPath)
113110
{
114111
GD.Print($"Importing Yarn script {assetPath}");
115112
var projectPath = YarnProjectEditorUtility.GetDestinationProjectPath(assetPath);

addons/YarnSpinner-Godot/Editor/YarnMarkupPaletteInspectorPlugin.cs

-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
using Godot;
55
using YarnSpinnerGodot.Editor.UI;
66

7-
87
namespace YarnSpinnerGodot.Editor;
98

109
/// <summary>

addons/YarnSpinner-Godot/Editor/YarnProjectEditorUtility.cs

+15-21
Original file line numberDiff line numberDiff line change
@@ -77,10 +77,10 @@ private static IEnumerable FindAllYarnProjects()
7777
private const int PROJECT_UPDATE_TIMEOUT = 80; // ms
7878

7979
private static ConcurrentDictionary<string, DateTime> _projectPathToLastUpdateTime =
80-
new ConcurrentDictionary<string, DateTime>();
80+
new();
8181

82-
private static Dictionary<string, Task> _projectPathToUpdateTask = new Dictionary<string, Task>();
83-
private static object _lastUpdateLock = new object();
82+
private static Dictionary<string, Task> _projectPathToUpdateTask = new();
83+
private static object _lastUpdateLock = new();
8484

8585
/// <summary>
8686
/// Queue up a re-compile of scripts in a yarn project, add all associated data to the project,
@@ -412,7 +412,7 @@ public static void CompileAllScripts(YarnProject project)
412412
{
413413
lock (project)
414414
{
415-
List<FunctionInfo> newFunctionList = new List<FunctionInfo>();
415+
List<FunctionInfo> newFunctionList = new();
416416
var assetPath = project.ResourcePath;
417417
GD.Print($"Compiling all scripts in {assetPath}");
418418

@@ -447,7 +447,7 @@ public static void CompileAllScripts(YarnProject project)
447447
errors = compilationResult.Value.Diagnostics.Where(d =>
448448
d.Severity == Diagnostic.DiagnosticSeverity.Error);
449449

450-
if (errors.Count() > 0)
450+
if (errors.Any())
451451
{
452452
var errorGroups = errors.GroupBy(e => e.FileName);
453453
foreach (var errorGroup in errorGroups)
@@ -489,7 +489,7 @@ public static void CompileAllScripts(YarnProject project)
489489
var newDeclarations = new List<Declaration>() //localDeclarations
490490
.Concat(compilationResult.Value.Declarations)
491491
.Where(decl => !decl.Name.StartsWith("$Yarn.Internal."))
492-
.Where(decl => !(decl.Type is FunctionType))
492+
.Where(decl => decl.Type is not FunctionType)
493493
.Select(decl =>
494494
{
495495
SerializedDeclaration existingDeclaration = null;
@@ -514,15 +514,13 @@ public static void CompileAllScripts(YarnProject project)
514514

515515
CreateYarnInternalLocalizationAssets(project, compilationResult.Value);
516516

517-
using (var memoryStream = new MemoryStream())
518-
using (var outputStream = new CodedOutputStream(memoryStream))
519-
{
520-
// Serialize the compiled program to memory
521-
compilationResult.Value.Program.WriteTo(outputStream);
522-
outputStream.Flush();
517+
using var memoryStream = new MemoryStream();
518+
using var outputStream = new CodedOutputStream(memoryStream);
519+
// Serialize the compiled program to memory
520+
compilationResult.Value.Program.WriteTo(outputStream);
521+
outputStream.Flush();
523522

524-
compiledBytes = memoryStream.ToArray();
525-
}
523+
compiledBytes = memoryStream.ToArray();
526524
}
527525

528526
project.ListOfFunctions = newFunctionList.ToArray();
@@ -614,7 +612,6 @@ public static FunctionInfo CreateFunctionInfoFromMethodGroup(MethodInfo method)
614612
/// <seealso cref="assembliesToSearch"/>
615613
public static bool searchAllAssembliesForActions = true;
616614

617-
618615
private static void CreateYarnInternalLocalizationAssets(YarnProject project,
619616
CompilationResult compilationResult)
620617
{
@@ -678,7 +675,7 @@ public static IEnumerable<StringTableEntry> GenerateStringsTable(YarnProject pro
678675
var errors =
679676
compilationResult.Value.Diagnostics.Where(d => d.Severity == Diagnostic.DiagnosticSeverity.Error);
680677

681-
if (errors.Count() > 0)
678+
if (errors.Any())
682679
{
683680
GD.PrintErr("Can't generate a strings table from a Yarn Project that contains compile errors", null);
684681
return null;
@@ -755,15 +752,14 @@ private static string GenerateCommentWithLineMetadata(string[] metadata)
755752
{
756753
var cleanedMetadata = RemoveLineIDFromMetadata(metadata);
757754

758-
if (cleanedMetadata.Count() == 0)
755+
if (!cleanedMetadata.Any())
759756
{
760757
return string.Empty;
761758
}
762759

763760
return $"Line metadata: {string.Join(" ", cleanedMetadata)}";
764761
}
765762

766-
767763
/// <summary>
768764
/// Removes any line ID entry from an array of line metadata.
769765
/// Line metadata will always contain a line ID entry if it's set. For
@@ -823,9 +819,7 @@ public static void AddLineTagsToFilesInYarnProject(YarnProject project)
823819
if (containsErrors)
824820
{
825821
GD.PrintErr($"Can't check for existing line tags in {path} because it contains errors.");
826-
return new string[]
827-
{
828-
};
822+
return Array.Empty<string>();
829823
}
830824

831825
return result.StringTable.Where(i => i.Value.isImplicitTag == false).Select(i => i.Key);

addons/YarnSpinner-Godot/Editor/YarnProjectImporter.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ public override Error _Import(
8383
var saveErr = ResourceSaver.Save(godotProject, godotProject.ImportPath);
8484
if (saveErr != Error.Ok)
8585
{
86-
GD.PrintErr($"Error saving .yarnproject file import: {saveErr.ToString()}");
86+
GD.PrintErr($"Error saving .yarnproject file import: {saveErr}");
8787
}
8888

8989
YarnProjectEditorUtility.UpdateYarnProject(godotProject);

addons/YarnSpinner-Godot/Editor/YarnProjectInspectorPlugin.cs

-3
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
using Yarn.Compiler;
1111
using YarnSpinnerGodot.Editor.UI;
1212

13-
1413
namespace YarnSpinnerGodot.Editor;
1514

1615
[Tool]
@@ -251,7 +250,6 @@ public void CSVFileSelected(string savePath)
251250
_project.SaveJSONProject();
252251
}
253252

254-
255253
private void LocaleAdded()
256254
{
257255
if (string.IsNullOrEmpty(_localeTextEntry.Text))
@@ -372,7 +370,6 @@ public override void _ParseBegin(GodotObject @object)
372370
scriptPatternsGrid.AddChild(addPatternButton);
373371
AddCustomControl(scriptPatternsGrid);
374372

375-
376373
var numScriptsText = "None";
377374
if (sourceScripts.Any())
378375
{

addons/YarnSpinner-Godot/Runtime/Commands/ActionManager.cs

+6-16
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
using Yarn;
99
using Node = Godot.Node;
1010

11-
1211
namespace YarnSpinnerGodot;
1312

1413
using Injector = Func<string, object>;
@@ -228,20 +227,11 @@ private static string GetActionName(YarnActionAttribute metadata, MethodInfo met
228227

229228
private static void FindAllActions()
230229
{
231-
if (commands == null)
232-
{
233-
commands = new Dictionary<string, DispatchCommand>();
234-
}
230+
commands ??= new Dictionary<string, DispatchCommand>();
235231

236-
if (functions == null)
237-
{
238-
functions = new Dictionary<string, Delegate>();
239-
}
232+
functions ??= new Dictionary<string, Delegate>();
240233

241-
if (searchedAssemblyNames == null)
242-
{
243-
searchedAssemblyNames = new HashSet<string>();
244-
}
234+
searchedAssemblyNames ??= new HashSet<string>();
245235
var injectorCache = new Dictionary<string, Injector>();
246236

247237
// Find the assemblies we're looking for
@@ -311,18 +301,18 @@ private static void FindAllActions()
311301
/// <summary>
312302
/// The Yarn commands that we have found.
313303
/// </summary>
314-
private static Dictionary<string, DispatchCommand> commands = new Dictionary<string, DispatchCommand>();
304+
private static Dictionary<string, DispatchCommand> commands = new();
315305

316306
/// <summary>
317307
/// The Yarn functions that we have found.
318308
/// </summary>
319-
private static Dictionary<string, Delegate> functions = new Dictionary<string, Delegate>();
309+
private static Dictionary<string, Delegate> functions = new();
320310

321311
/// <summary>
322312
/// A list of names of assemblies that we have searched for commands and
323313
/// functions.
324314
/// </summary>
325-
private static HashSet<string> searchedAssemblyNames = new HashSet<string>();
315+
private static HashSet<string> searchedAssemblyNames = new();
326316

327317
/// <summary>
328318
/// Try to execute a command if it exists.

addons/YarnSpinner-Godot/Runtime/Commands/DefaultActions.cs

-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
using System.Threading.Tasks;
44
using Godot;
55

6-
76
namespace YarnSpinnerGodot;
87

98
public partial class DefaultActions : Godot.Node

addons/YarnSpinner-Godot/Runtime/Commands/DispatchCommand.cs

+1-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
using System.Reflection;
44
using Godot;
55

6-
76
namespace YarnSpinnerGodot;
87

98
using Injector = Func<string, object>;
@@ -33,7 +32,7 @@ public bool TryInvoke(string[] args, out object returnValue)
3332
}
3433
catch (Exception e) when (
3534
e is ArgumentException // when arguments are invalid
36-
|| e is TargetException // when a method is not static, but the instance ended up null
35+
or TargetException // when a method is not static, but the instance ended up null
3736
)
3837
{
3938
GD.PrintErr($"Can't run command {args[0]}: {e.Message}");

addons/YarnSpinner-Godot/Runtime/Commands/YarnActionAttribute.cs

-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
using System;
22
#nullable disable
33

4-
54
namespace YarnSpinnerGodot;
65

76
[AttributeUsage(AttributeTargets.Method, Inherited = false)]

addons/YarnSpinner-Godot/Runtime/Commands/YarnFunctionAttribute.cs

-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
using System;
33
using Yarn;
44

5-
65
namespace YarnSpinnerGodot;
76

87
/// <summary>

addons/YarnSpinner-Godot/Runtime/Commands/YarnParameterAttribute.cs

-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
#nullable disable
22
using System;
33

4-
54
namespace YarnSpinnerGodot;
65

76
/// <summary>

0 commit comments

Comments
 (0)