Modding:General Best Practices: Difference between revisions
Add named arguments section |
Fill out named arguments section |
||
Line 41: | Line 41: | ||
=Named arguments= | =Named arguments= | ||
When interacting with Qud's C# API, prefer using [https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments#named-arguments named arguments] to fill out optional parameters. | |||
For example, consider <code>XRL.UI.Popup.AskString()</code>: | |||
<syntaxhighlight lang="csharp"> | |||
// namespace XRL.UI | |||
// public class Popup | |||
public static string AskString( | |||
string Message, | |||
string Default = "", | |||
string Sound = PROMPT_SOUND, | |||
string RestrictChars = null, | |||
string WantsSpecificPrompt = null, | |||
int MaxLength = 80, | |||
int MinLength = 0, | |||
bool ReturnNullForEscape = false, | |||
bool EscapeNonMarkupFormatting = true, | |||
bool? AllowColorize = null | |||
) | |||
</syntaxhighlight> | |||
Without named arguments, calling the function may look like | |||
<syntaxhighlight lang="csharp"> | |||
using XRL.UI; | |||
var response = Popup.AskString( | |||
"How are you doing?", | |||
"Okay", | |||
Popup.PROMPT_SOUND, | |||
null, | |||
null, | |||
80, | |||
0, | |||
true, | |||
true, | |||
true | |||
); | |||
</syntaxhighlight> | |||
With named arguments for intentionally-set optional parameters, calling the function may look like | |||
<syntaxhighlight lang="csharp"> | |||
using XRL.UI; | |||
var response = Popup.AskString( | |||
"How are you doing?", | |||
Default: "Okay", | |||
MaxLength: 80, // note: same as current default | |||
ReturnNullForEscape: true, | |||
AllowColorize: true | |||
); | |||
</syntaxhighlight> | |||
This provides a couple of related benefits: | |||
# '''Flexibility and resilience.''' By specifying only the arguments you want to set, your code will adapt to changes in default values and many common parameter list changes (e.g. the addition of a new optional parameter or the reorganization of optional parameters). | |||
# '''More sensible errors.''' If the parameter list changes in a way that cannot be automatically resolved (e.g. the removal of a parameter you set), the error message will generally include the name of your argument instead of the index (or worse, continuing to compile with the argument going to the wrong parameter). | |||
# '''Documentation.''' By naming arguments, you provide clarity to future readers of your code (including yourself) as to its intended purpose. | |||
'''Avoid including positional arguments after named ones!''' Calling <code>void Foo(int A, string B, bool C)</code> like <code>Foo(A: 0, "blah", C: false)</code> will cause cryptic errors if the parameter list gets reorganized. | |||
= Save migration = | = Save migration = |