I prefer approach with simple DSLs definition, when it makes code simpler or more readable. Also "pipeline-style" expressions are awesome.
In your case it can be written like this:
var str =
new StringBuilder()
.AppendIf(condition1, "one")
.AppendIf(condition2, "two")
.AppendIf(condition3, "forty two")
.ToString();
With an extension method.
public static class StringBuilderExtensions
{
public static StringBuilder AppendIf(
this StringBuilder @this,
bool condition,
string str)
{
if (@this == null)
{
throw new ArgumentNullException("this");
}
if (condition)
{
@this.Append(str);
}
return @this;
}
}
Approach is suitable here, if conditions are repeated. For example arg1 != null
, arg2 != null
, then AppendIfNotNull
can be used.
Otherwise, think twice, because it looks quite similar to initial implementation, requires additional code, can be slower because of additional null checks and method invocations, and also you should create an AppendIf
overload for every Append
one.
AppendIf(string, bool)
, but not sure if this is an improvement at all – Precautioussb.Append(condition1 ? "One" : "");
but I'm not sure it's any better. – Bullet(confition1 || condition2)
– Alrich