functions vs properties

Last post 07-17-2009 7:54 PM by WPHC. 31 replies.

Sort Posts:

  • functions vs properties

    06-30-2009, 12:34 AM
    • Member
      13 point Member
    • WPHC
    • Member since 06-27-2008, 6:42 PM
    • Posts 195

    Correct me if I am wrong but has functions in asp.net 2.0 been replaced by methods?


    Could you please give me the community view as to which is better?


    a function(method)? or a property? in order to retrieve a value of something?  the example is below



    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    /// <summary>
    /// Summary description for GlobalFunctions
    /// </summary>
    public class GlobalFunctions
    {
        //public const string dbConnectionString = ConfigurationManager.ConnectionStrings["homeMadeConnection"].ConnectionString;
    	public GlobalFunctions()
    	{
    		//
    		// TODO: Add constructor logic here
    		//
    	}
    
        public static string dbConnectionString
        {
            get { 
                    return  ConfigurationManager.ConnectionStrings["homeMadeConnection"].ConnectionString;
                }
        }
     
    
    }
    


    Just say that I wish to call a function that returns teh connection string value? and instead of always writing ConfigurationManager.etc.etc i just want to call a function


    Which is better? a property? or a function? or a constant?


    Thanks heaps

    http://www.wolfpack.net.au/notwebsite/forums/HCsignature2.jpg
  • Re: functions vs properties

    06-30-2009, 6:41 AM
    • Participant
      1,007 point Participant
    • Dr_no
    • Member since 08-09-2008, 7:22 PM
    • Egypt
    • Posts 170

     Hi,

    I did not undersatnd you, do you mean the difference in performance ?

    The properties is compiled to CIL as methods. In your case, get_dbConnectionString() as it is just a getter

    But properties are the getters and setters in .NET flavour, it makes it easy to developers to read and write the code ..

    myLabel.Text = "Just \"Mark my post As Answer\" , if it helps you";
  • Re: functions vs properties

    06-30-2009, 7:56 AM
    • Member
      156 point Member
    • babu27
    • Member since 05-25-2009, 1:22 PM
    • Bangalore
    • Posts 38

    it sounds like you want to know which one is better to use.

    see here no problem you can use function, property or constant what ever you want to use.

    Regards,
    ..Babu
  • Re: functions vs properties

    06-30-2009, 8:30 AM
    • Member
      741 point Member
    • Rimbik
    • Member since 02-25-2009, 6:09 AM
    • Mumbai, India
    • Posts 257
    ---

    For your answer:

    When to use Properties?
    1. Something like 'GetUserName', here u just returning a value
       so better to have a property with Getter only (has proper meaning)

    2. Do not write complex logic (untill and unless needed) in property even for getter.

    3. If you have complex business logic then go with Function

    4. With property, there is a concept called 'Lagy Loading' good for coding.

    5. Keep your property short and simple (Method can be complex)

    6. Finally do not write more than 50 lines in a single method.

    Soumen, India

    Budhi Hin Tanu Janike, Sumirau Pavan Kumar
    Bal budhi Vidya dehu mohe,Harahu Kalesa Vikar
  • Re: functions vs properties

    06-30-2009, 10:14 AM
    • Star
      14,226 point Star
    • JeffreyABecker
    • Member since 10-04-2004, 8:27 AM
    • Philadelphia, PA
    • Posts 2,909

    WPHC:


    Which is better? a property? or a function? or a constant?


    Whatever's the appropriate code-construct for the situation.  The performance difference between reading a property and reading a field is so negligable its irrelevent.  Saying "All our buisness objects are going to use fields because they're faster" while your application is doing massive un-indexed disk access is exactly what Knuth was talking about when he said "Premature optimization is the root of all evil".

  • Re: functions vs properties

    06-30-2009, 6:12 PM
    • Member
      13 point Member
    • WPHC
    • Member since 06-27-2008, 6:42 PM
    • Posts 195

    Thank you all for your responses.


    The issue is not with performance.


    I will try to clarify my question - "which way would be considered best in the example provided - when calling the database connection string?"


    a property? a method? a function? a constant?

    would it better to be in a home made class or in the global.ascx?(if thats possible)

    http://www.wolfpack.net.au/notwebsite/forums/HCsignature2.jpg
  • Re: functions vs properties

    07-01-2009, 7:38 AM
    • Star
      14,226 point Star
    • JeffreyABecker
    • Member since 10-04-2004, 8:27 AM
    • Philadelphia, PA
    • Posts 2,909

    The direct answer: use a property if theres only ever one db for your app, a method if you have multiple dbs.

    The better solution is to only ever create connections in one place in your application.  So rather than having a GetConnectionString() method, you'd have a GetConnection() method.  Personally I skip connections too and have an abstraction layer on top of that.  I cant discribe the joy of never, ever, having to construct parameters, set db timeouts, manually set  the command type or really worry about managing ado stuff.

    public class DbParameter
    {
        public string Name {get; set;}
        public object Value {get; set;}
        public DbType Type {get;set;}
    }
    public interface IDbManager : IDisposable
    {
        DataSet Exec(string procName, params DbParameter[] args);
        DataSet ExecDynamicSql(string sql, params DbParameter[] args);
        object Scalar(string procName, params DbParameter[] args);
        object ScalarDynamicSql(string sql, params DbParameter[] args);
        void NonQuery(string procName, params DbParameter[] args);
        void NonQueryDynamicSql(string sql, params DbParameter[] args);
    }


    Then on top of that, I have a factory and a few extension methods which use the anonymous objects as dictionaries approach from Asp.Net MVC.

    so I end up with something like:

    using(IDbManager db = DbManagerFactory.GetDb())
    {
        DataSet ds = db.Exec("myproc", new {MyobjectsId= 12345});
    }



    as opposed to something like:

    Create a connection
    Create a Command
    set the command text
    set the command type
    create a parameter
    set the parameter's name, value and data type
    add the parameter to the command's parameter collection
    create a data adapter
    set the data adapter's command & connection
    create a dataset
    use the data adapter to fill that data set

  • Re: functions vs properties

    07-01-2009, 3:46 PM
    • Member
      606 point Member
    • TheDirtyBird
    • Member since 04-06-2008, 2:15 PM
    • Alabama
    • Posts 226
            try
            {
                using (SqlConnection cn0 = new SqlConnection(ConfigurationManager.ConnectionStrings["CS"].ToString()))
                {
                    cn0.Open();
                    SqlCommand cmd0 = new SqlCommand("SELECT * FROM [Users] WHERE UserName = '" + txtUserName.Text + "' AND Password = '" + txtPassword.Text + "'", cn0);
                    SqlDataReader rdr0 = cmd0.ExecuteReader();
                    rdr0.Read();
                    UserID = Convert.ToInt32(rdr0["UserID"]);
                    Role = rdr0["Role"].ToString();
                    Authorize = rdr0["Authorize"].ToString();
                    Disabled = rdr0["Disable"].ToString();
                    NOL = Convert.ToInt32(rdr0["NumberOfLogins"]);
                    rdr0.Close();
                    if (Authorize == "False")
                    {
                        ErrorMsgLabel.Text = "Your account has not been authorized.";
                    }
                    else
                    {
                        if (Disabled == "True")
                        {
                            ErrorMsgLabel.Text = "Your account has been disabled.";
                        }
                        else
                        {
                            DateTime ExpiryDate = DateTime.Now.AddDays(1);
                            //UserID Cookie
                            HttpCookie rstCookie = new HttpCookie("rstCookie");
                            rstCookie.Value = UserID.ToString();
                            rstCookie.Expires = ExpiryDate;
                            Response.Cookies.Add(rstCookie);
                            //Role Cookie
                            HttpCookie rstCookie2 = new HttpCookie("rstCookie2");
                            rstCookie2.Value = Role;
                            rstCookie2.Expires = ExpiryDate;
                            Response.Cookies.Add(rstCookie2);
                            SignInFlag = "CookieSuccess";
                        }
                    }
                    if (SignInFlag == "CookieSuccess")
                    {
                        NOL++;
                        SqlCommand cmd = new SqlCommand("UPDATE [Users] SET [LastLogin] = getdate(), [NumberOfLogins] = @NumberOfLogins WHERE [UserID] = '" + UserID + "'", cn0);
                        cmd.Parameters.Add("@NumberOfLogins", SqlDbType.Int);
                        cmd.Parameters["@NumberOfLogins"].Value = NOL;
                        cmd.ExecuteNonQuery();
                        SignInFlag = "Success";
                    }
                    cn0.Close();
                }
            }
            catch
            {
                //ErrorMsgLabel.Text = "Login failed!";
                SignInFlag = "Failed";
            }


     

  • Re: functions vs properties

    07-01-2009, 7:28 PM
    • Member
      13 point Member
    • WPHC
    • Member since 06-27-2008, 6:42 PM
    • Posts 195

    Dear Jeffery and Birdman...


    Thank you for the code....


    Although I appreciate the code, both code samples are about 60 miles above my current level of .Net 2.0 knowledge :( - and the code does not make sense to me.


    Although I have been a programmer for a fair while -- doing things the old way - getting a hold of the way new things are doing is a little slow on my end..


    I understand the concept of what you are trying to get too - 3 tier archietecture. - any database always connecting to it from the same source code...(i hope?)


    Thanks again..





    http://www.wolfpack.net.au/notwebsite/forums/HCsignature2.jpg
  • Re: functions vs properties

    07-01-2009, 7:30 PM
    • Member
      13 point Member
    • WPHC
    • Member since 06-27-2008, 6:42 PM
    • Posts 195

    btw i also like this statement



    The direct answer: use a property if theres only ever one db for your app, a method if you have multiple dbs.


    and think that its the correct answer but I dont want to mark it as the right one because I am not sure of your reasons behind it


    http://www.wolfpack.net.au/notwebsite/forums/HCsignature2.jpg
  • Re: functions vs properties

    07-02-2009, 10:23 AM
    Answer
    • Star
      14,226 point Star
    • JeffreyABecker
    • Member since 10-04-2004, 8:27 AM
    • Philadelphia, PA
    • Posts 2,909

    A little more explaination about my direct answer.  I've worked with a couple applications where we connect to multiple databases.  If you're writing one of those types of applications, having a single property which exposes a connection string is obviously not going to cut it since it can only ever expose a single connection string.  You can however send parameters into a method telling it which connection string to return.


    I think what I was really trying to get at is that a good abstraction around your data access, 3 tier architecture or not, is worth its file-size in gold.  ADO.Net is a very low-level api for data access.  Avoid using it directly.  The whole implementation for my abstraction is 275 lines including documentation and disclaimer of copyright. I'm more than willing to go through it bit by bit and explain.  I'm not saying you have to, or even should use this.  But something like this will save you a ton of coding. 

  • Re: functions vs properties

    07-03-2009, 12:45 AM
    • Member
      13 point Member
    • WPHC
    • Member since 06-27-2008, 6:42 PM
    • Posts 195

    Thank, if you wouldnt mind explaining the code - that would be wonderful...


    but before you begin i must let you know that i am not overly confident in my .net skills


    i have a reasonable understanding of C#.....but not advanced..



    Can we start by explaining what an interface is? (in your own words)


    #
      public interface IDbManager : IDisposable
    #
        {
    #
            /// <summary>
    #
            /// Executes a procedure returning the results as a DataSet
    #
            /// </summary>
    #
            /// <param name="procName">The name of the stored procedure</param>
    #
            /// <param name="args">the argument name/value pairs for the procedure</param>
    #
            /// <returns>the resuts as a data set</returns>
    #
            DataSet Exec(string procName, params DbParameter[] args);
    #
     
    #
            /// <summary>
    #
            /// Executes some sql returning the results as a DataSet
    #
            /// </summary>
    #
            /// <param name="sql">the sql to be executed</param>
    #
            /// <param name="args">the argument name/value pairs for the sql</param>
    #
            /// <returns>the resuts as a data set</returns>
    #
            DataSet ExecDynamicSql(string sql, params DbParameter[] args);
    #
     
    #
            /// <summary>
    #
            /// Executes a stored procedure and returns a single result
    #
            /// </summary>
    #
            /// <typeparam name="T">The type of the result</typeparam>
    #
            /// <param name="procName">the name of hte procedure</param>
    #
            /// <param name="args">the argument name/value pairs for the procedure</param>
    #
            /// <returns></returns>
    #
            T Scalar<T>(string procName, params DbParameter[] args);
    #
     
    #
            /// <summary>
    #
            /// Executes some sql returning a single result
    #
            /// </summary>
    #
            /// <typeparam name="T">The type of the result</typeparam>
    #
            /// <param name="sql">the sql to be executed</param>
    #
            /// <param name="args">the argument name/value pairs for the sql</param>
    #
            /// <returns></returns>
    #
            T ScalarDynamicSql<T>(string sql, params DbParameter[] args);
    #
     
    #
            /// <summary>
    #
            /// Begins a transaction.
    #
            /// </summary>
    #
            void Begin();
    #
     
    #
            /// <summary>
    #
            /// Commits a transaction.
    #
            /// </summary>
    #
            void Commit();
    #
            /// <summary>
    #
            /// Rolls a transaction back.
    #
            /// </summary>
    #
            void Rollback();
    #
        }







    http://www.wolfpack.net.au/notwebsite/forums/HCsignature2.jpg
  • Re: functions vs properties

    07-03-2009, 3:10 PM
    • Star
      14,226 point Star
    • JeffreyABecker
    • Member since 10-04-2004, 8:27 AM
    • Philadelphia, PA
    • Posts 2,909

    An interface in .net is really a contract between two pieces of code.  The type that implements the interface promises that it will expose specific methods, properties and events.  The compiler then enforces that the consuming code can only call those methods in the documented way.  from the perspective of the C# type system you can think of an inteface as a purely abstract class.  You can never call new directly on an interface.  Since C# does not support multiple inheritance in the same way that C++ does, interfaces are core to the inheritance model for .Net.  One important thing about interfaces is that they cant contain, nor are they meant to imply, anything about implementation.  They are abstractions to the core.  In the case of my example, it would matter very little if someone subsititued a different database so long as they properly implemented the interface.

  • Re: functions vs properties

    07-03-2009, 6:13 PM
    • All-Star
      90,654 point All-Star
    • SGWellens
    • Member since 01-02-2007, 9:27 PM
    • Twin Cities, MN
    • Posts 7,398
    • Moderator
      TrustedFriends-MVPs

    I don't think I've seen these mentioned:

     

    • Properties must return/take a type, functions can have void return types.
    • Functions can take parameters, properties cannot take parameters (accept for the value of the type).
    • If you serialize an object, properties are serialized, functions are not.

     

    So properties and functions are completely different.

     

     

    Steve Wellens

    My blog
  • Re: functions vs properties

    07-03-2009, 7:26 PM
    • Member
      13 point Member
    • WPHC
    • Member since 06-27-2008, 6:42 PM
    • Posts 195

    Thank you steve for your response,


    I understand those items you mentioned - i was asking which was the best way to call a database string but i think im onto a revolutionary item with the post above yours....

    http://www.wolfpack.net.au/notwebsite/forums/HCsignature2.jpg
Page 1 of 3 (32 items) 1 2 3 Next >