Другой вариант, который я нашел, это сделать ${format("cluster-%02d", var.cluster_id+0)}
. Добавление нуля дает действительное число, а затем %02d
работает правильно. Но использование %02s
чище.
No - it's generally considered best practice to declare a variable as late as you can, preferably setting it at the point of declaration. The only time when I don't do that is when I have to set a variable conditionally, or it's set in a more restrictive scope:
String name;
using (TextReader reader = ...)
{
// I can't declare name here, because otherwise it isn't
// accessible afterwards
name = reader.ReadToEnd();
}
Reasons for declaring at the point of first use where possible:
I would use
XmlDocument doc = xmlDocuments[3];
Declare variables where they are used.
Это разные стили, и ни один из них объективно не лучше другого. Это дело вкуса. Вы можете сначала объявить переменную, а затем присвоить ей значение:
XmlDocument doc;
doc = xmlDocuments[3];
Или вы можете сделать и то, и другое в том же операторе:
XmlDocument doc = xmlDocuments[3];
Однако эта форма:
XmlDocument doc = null;
doc = xmlDocuments[3];
Чтобы присвоить нулевую ссылку переменной, а затем немедленно заменять его другой ссылкой, совершенно бессмысленно.
The declaration and assignment should ideally be paired for code legibility. In fact ReSharper will pick up any exceptions to this and suggest that they be joined.
Как указывали другие, первый стиль может быть полезен, если вам нужно объявить переменную вне области цикла, если или что-то еще. Но в большинстве случаев я думаю, что этот стиль - пережиток старых времен Visual Basic 6 (и ранее), когда вам всегда приходилось объявлять переменную перед использованием in.
Старый VB не поддерживал ваш второй стиль и, следовательно, первый стиль по-прежнему популярен ...
If the variable 'doc' is assigned right after it is declared then no, I don't see any reason why you would want to do that. In any case, it certainly is not my style.
Мне нравится думать о переменных как о «совместно используемых» или «не совместно используемых», поскольку некоторые переменные необходимо использовать в нескольких местах в классе или методе, а некоторые - только один раз. , В первом случае я объявляю их все в верхней части соответствующего блока, а во втором - прямо перед тем, как использовать.
Все зависит от того, где вам нужно их использовать.
Случай 1:
Xyz xyz = new Xyz; // Declared at the top.
// Loads of unrelated code in-between...
xyz.abc();
// More unrelated code in-between...
xyz.def(stuff);
Случай 2:
// Loads of unrelated code above...
Xyz xyz = new Xyz; // Declared in a 'block'.
xyz.abc();
xyz.def(stuff);
xyz.destroy();
// More unrelated code below...
Я в основном согласен с Джоном (Не говоря уже о том, что обычно мне приходится соглашаться с ним: -).
у вас есть варианты:
1.
//Do something...
XmlDocument doc = xmlDocuments[3];
//use doc
//Do something...
2.
//Do something...
XmlDocument doc = null;
doc = xmlDocuments[3];
//Use doc
//Do something...
3.
//Do something...
XmlDocument doc = null;
//...Do something with other variables etc...
doc = xmlDocuments[3];
//Do something...
//Use doc
4.
//Do something...
XmlDocument doc = null;
//...Do something with other variables etc...
doc = xmlDocuments[3];
//Use doc
//Do something...
5.
//Do something...
XmlDocument doc = null;
doc = xmlDocuments[3];
//Do something...
//Use doc
6.
//Do something...
XmlDocument doc = xmlDocuments[3];
//Do something...
//use doc
Надеюсь, вы понимаете, что вариант 1.
Лучше всего сохранить объявление, определение и инициализацию «вместе» насколько возможно. Вариант 1 - это пример объявления, определения и инициализации, выполненных вместе в одной строке. Вы можете сжать его и дальше:
var doc = xmlDocuments[3];
Словарь (не зависящий от языка):
Надеюсь, это поможет.
I would go with
void Foo()
{
XmlDocument doc;
//Do other code here
//Create doc
doc = xmlDocuments[3];
}
As doc may not be being used till later on in the method. It makes more sense to create doc just before it is used. Easier to read (less scrolling).
I prefer to use this one:
XmlDocument doc = null;
//blah blah
doc = xmlDocuments[3];
I just want assign and use 'doc' when it is required..
If I want use it right after assignment I go for
XmlDocument doc = xmlDocuments[3];
I'm always trying to declare and assign variables on the same row if possible, so in this case I would try to use the second option. Fewer lines of code, less declared variables to keep in mind when reading the code also. In the end I think it's all about the coding rules you and your team uses though. We've had coding rules which says to declare all local variables in the beginning of the method, so I've seen both programming styles.