Hello all,
A question I have been thinking about for a while - would Stackoverflow users commonly implement significant functionality in a constructor (specifically in classes derived from the System.Web.UI.Page class) , or should we keep the logic here as simple as possible and instead implement functionality in OnPreInit (using the constructor to simply instantiate objects/values that are required for the functionality in the rest of the page to function)? Is there a "best-practice" approach to this scenario?
The background to this question:
The system that I am working on has a fairly deep page hierarchy - there are about 10 chained page objects that the actual page derives from:
-- System.Web.UI.Page ----- CustomPage1 : System.Web.UI.Page -------- CustomPage2 : CustomPage1 ---------- etc
Each page adds a specific piece of functionality, and often there is either a dependancy on code run within the custom page constructor, or the functionality itself is directly run during construction.
The example that best illustrates my question is the page that loads custom objects from our database to the page so they are available during the page lifecycle - during page construction connections are made to the database and then public properties are populated with the correct values.
To my mind this is better done from the OnPreInit event, mainly because we have greater flexibility to perform some page level checks (e.g. should we want to prevent this functionality being called) before the parent logic is run (given that in a constructor the order of execution will construct the parent classes before the child class). From an OO perspective as well OnPreInit seems to be a more appropriate area to implement this functionality - page construction should deal with construction of the page, setting any default values, etc and then OnPreInit would be used to perform any functionality that was required during the lifecycle of the page.