Global variable or parameter?

Is it correct that homeitem should be declared inside the OnLoad method and overgiven to all the render methods instead of just declaring it as a global variable and accessing it by all the render methods?

public partial class Default : Page
    /// <summary>
    /// Initializes the module.
    /// </summary>
    /// <param name="e">
    /// The event arguments.
    /// </param>
    protected override void OnLoad(EventArgs e)
        var homeItem = Sitecore.Context.Database.GetItem(Sitecore.Context.Site.StartPath);

        // some code...

        this.RenderCallToActionItems(homeItem, isHomeItem);

        if (isHomeItem)
            webcam.Visible = true;

        // some more code...

I’d just like to know what is correct / standard so I can stick to that!


From what I see here you are more asking about making homeItem a function variable or a class field, neither of which amount to a global variable.

Now, from your code it does seem that the homeItem is drawn from a global state of sorts, so I would answer your question with more questions ?.

  • How often does the original data change ? If it never change then you can safely make it a class level field. If it will change then it`s probably best to just get it every times you need it (leave it as a function variable as is now). Now reading the code, if your variables are named properly I doubt the start path would change much once the app starts.

  • How costly is it to get the value ? that is, is calling Sitecore.Context.Database.GetItem(Sitecore.Context.Site.StartPath); something that is expensive do to (memory, CPU, latency etc). If no then you could call it each time you need it, provided it won’t change between calls (see first question).

Lastly, the concept of GlobalVariable is quite clear in the programmer world and very much frowned uppon. Most for very good reasons but that does not necessarily mean that it should be banned either. This is why I interpreted your GlobalVariable more as a private field for your class than a true global variable.

So basically here the best advice available on this whole page IMHO are the wise words of @RobertHarvey: Know what you need, know your system, get possible solutions and the right one should just emerge. Most of all, stay curious and never get religious about code.

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *