Skip to content

Commit d847016

Browse files
committed
Maintaining parentheses around a ternary operation operand in a string concatenation / Extra test coverage over pathentheis maintenance, re: issue #12
1 parent 308556d commit d847016

File tree

3 files changed

+44
-1
lines changed

3 files changed

+44
-1
lines changed

ReadableExpressions.UnitTests/WhenTranslatingMathsOperations.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,5 +238,16 @@ public void ShouldTranslateAPostDecrementExpression()
238238

239239
Assert.AreEqual("i--", translated);
240240
}
241+
242+
[TestMethod]
243+
public void ShouldMaintainRelevantParentheses()
244+
{
245+
Expression<Func<int, int, int, int>> mather =
246+
(i, j, k) => (i + j) * k;
247+
248+
var translated = mather.Body.ToReadableString();
249+
250+
Assert.AreEqual("((i + j) * k)", translated);
251+
}
241252
}
242253
}

ReadableExpressions.UnitTests/WhenTranslatingStringConcatenation.cs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,5 +77,28 @@ public void ShouldTranslateAnExplicitMixedTypeThreeArgumentConcatenation()
7777

7878
Assert.AreEqual("str1 + i + l", translated);
7979
}
80+
81+
// See https://github.com/agileobjects/ReadableExpressions/issues/12
82+
[TestMethod]
83+
public void ShouldMaintainTernaryOperandParentheses()
84+
{
85+
Expression<Func<bool, string, string, string>> ternaryResultAdder =
86+
(condition, ifTrue, ifFalse) => (condition ? ifTrue : ifFalse) + "Hello!";
87+
88+
var translated = ternaryResultAdder.Body.ToReadableString();
89+
90+
Assert.AreEqual("(condition ? ifTrue : ifFalse) + \"Hello!\"", translated);
91+
}
92+
93+
[TestMethod]
94+
public void ShouldMaintainNumericOperandParentheses()
95+
{
96+
Expression<Func<int, int, int, string>> mathResultAdder =
97+
(i, j, k) => ((i - j) / k) + " Maths!";
98+
99+
var translated = mathResultAdder.Body.ToReadableString();
100+
101+
Assert.AreEqual("((i - j) / k) + \" Maths!\"", translated);
102+
}
80103
}
81104
}

ReadableExpressions/StringExtensions.cs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,16 @@ private static string GetStringValue(Expression value, TranslationContext contex
193193
}
194194
}
195195

196-
return context.Translate(value);
196+
var stringValue = context.Translate(value);
197+
198+
switch (value.NodeType)
199+
{
200+
case ExpressionType.Conditional:
201+
stringValue = stringValue.WithSurroundingParentheses();
202+
break;
203+
}
204+
205+
return stringValue;
197206
}
198207
}
199208
}

0 commit comments

Comments
 (0)