Skip to content

Commit b0cdb95

Browse files
committed
Enhance null checks, caching, and code readability
Added a null check in `GetFormatViewDefinitionForObject` to handle cases where `typeName` is null, returning early if necessary. Introduced a caching mechanism using `_formatCache.TryGetValue` to improve performance by reusing cached format view definitions. Refactored object-to-data-table conversion code for better readability by reformatting inline initializations of `DecimalValue` and `StringValue`. Improved clarity in data type assignment logic by wrapping nested loops in braces and adopting modern C# syntax (`is not`) for type checks.
1 parent c22ca70 commit b0cdb95

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

src/Microsoft.PowerShell.ConsoleGuiTools/TypeGetter.cs

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,14 @@ public class TypeGetter
7373
/// <returns>The format view definition if found; otherwise, <see langword="null" />.</returns>
7474
private FormatViewDefinition? GetFormatViewDefinitionForObject(PSObject obj)
7575
{
76-
var typeName = obj.BaseObject.GetType().FullName;
77-
return GetFormatViewDefinitionForType(typeName!);
76+
string? typeName = obj.BaseObject.GetType().FullName;
77+
if (typeName is null)
78+
{
79+
return null;
80+
}
81+
if (_formatCache.TryGetValue(typeName, out var cached))
82+
return cached;
83+
return GetFormatViewDefinitionForType(typeName);
7884
}
7985

8086
/// <summary>
@@ -102,13 +108,13 @@ public static DataTableRow CastObjectToDataTableRow(PSObject ps, List<DataTableC
102108
if (isDecimal)
103109
{
104110
valuePairs[dataColumn.ToString()] = new DecimalValue
105-
{ DisplayValue = stringValue, SortValue = decimalValue };
111+
{ DisplayValue = stringValue, SortValue = decimalValue };
106112
}
107113
else
108114
{
109115
var stringDecorated = new StringDecorated(stringValue);
110116
valuePairs[dataColumn.ToString()] = new StringValue
111-
{ DisplayValue = stringDecorated.ToString(OutputRendering.PlainText) };
117+
{ DisplayValue = stringDecorated.ToString(OutputRendering.PlainText) };
112118
}
113119
}
114120

@@ -130,9 +136,13 @@ private static void SetTypesOnDataColumns(List<DataTableRow> dataTableRows, List
130136

131137
// If every value in a column could be a decimal, assume that it is supposed to be a decimal
132138
foreach (var dataRow in dataRows)
133-
foreach (var dataColumn in dataTableColumns)
134-
if (!(dataRow[dataColumn.ToString()] is DecimalValue))
135-
dataColumn.StringType = typeof(string).FullName;
139+
{
140+
foreach (var dataColumn in dataTableColumns)
141+
{
142+
if (dataRow[dataColumn.ToString()] is not DecimalValue)
143+
dataColumn.StringType = typeof(string).FullName;
144+
}
145+
}
136146
}
137147

138148
/// <summary>

0 commit comments

Comments
 (0)