Results 1 to 14 of 14

Thread: [RESOLVED] private and public methods?

  1. #1

    Thread Starter
    Lively Member {yak}'s Avatar
    Join Date
    Aug 2005
    Posts
    119

    Resolved [RESOLVED] private and public methods?

    Hi,

    Say I have a class, and within the class a method, how do you determine if you declare the method public or private? I always thought you're suppose to declare them private, but, if so, when you want to call that method from another class, you've got to have a public method to call the private one?
    I just want to make sure i'm doing everything the right way.
    Code:
    public class foo
    {
    	public foo()
    	{
    	
    	}
    	
    	private string yak(string strVar)
    	{
    		// do something
    	}
    	
    	// now i want to call the method from another class, therefore I have to create a public method to call the private?
    	
    	public string yakbar(string strSo)
    	{
    		return yak(strSo);
    	}
    }
    Any tips? Thanks
    {yak}

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: private and public methods?

    If you are defining a function purely for the internal use of the class then you would declare the method private. If you need to call it from outside the class then you would declare it public. Public methods will often call other private methods, but you would almost never define a public method that does nothing other than call a different private method. The exception to this would be if the public and private methods had different arguments. The public method could call the private method using some default values for the extra arguments while internally it could be called with other values. You would normally overload a method name in this case.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Lively Member {yak}'s Avatar
    Join Date
    Aug 2005
    Posts
    119

    Re: private and public methods?

    Thank you for the reply
    I remember reading somewhere that you should declare everything in a class private, but it didn't make sense to me to make a public method to call a private one. Now that you have cleared that up, it makes sense that public methods can call other private methods that are not exposed.
    Again thanks for the reply. Another question I've been wondering. Say you do have a public method, that's being called, and it takes 2 parameters, is it safe to just call the method like so:
    Code:
    Class1 c = new Class1();
    c.MyMethod("param1", "param2");
    Or, should you always use get{} and set{} to set the values before you use them in the methods?
    I'm trying to make sure i've got all the right ideas before I get further down the road, and realize i've done everything completley wrong.

    Thanks;
    {yak}

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: private and public methods?

    I'm not 100% sure what you mean. Get and set are only relevant when talking about properties. A property has a get and/or a set method within it which are not exposed publicly. A beauty of a property is that it behaves pretty much like a variable publicly, but like a method or methods privately. This serves to simplify your type's interface while providing additional flexibility internally.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5

    Thread Starter
    Lively Member {yak}'s Avatar
    Join Date
    Aug 2005
    Posts
    119

    Re: private and public methods?

    Sorry for the confusion, I must be confused myself I think I see where properties are used now, but let me see if i'm correct. You use properties when you want to set the values of private variables within your class, from another? Meh:
    Code:
    public class Class1
    {
       private int x;
       public int xx
       {
    
          get
          {
          	return x;
          }
    
          set
          {
          	x = value;
          }
    
       }
       // now x will be used somewhere else in here...
    }
    
    
    Class1 c = new  Class1();
    c.xx = 10;
    But even so with that, couldn't you just create a constructor that would initialize the number for you? I guess what I'm getting at is, I want to make sure I'm doing everything in best practice.
    Many thanks!
    {yak}

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: private and public methods?

    A public property is used in .NET in the majority of cases where a public variable would have been in other languages, or two methods in Java. You can certainly use a constrcutor to set a private variable but without the public property you could not set it after the object had been created. Also, a property does not have to refer to a specific, single variable, plus it can do other processing as well. For instance, lets say you had a Person class that had a private variable of type DateTime that stored a date of birth, which was exposed via a public property. You could provide a second property of type TimeSpan that returned the person's age by calculating it from the date of birth and the current date:
    Code:
    public class Person
    {
        private DateTime m_DateOfBirth;
    
        public DateTime DateOfBirth
        {
            get
            {
                return this.m_DateOfBirth;
            }
            set
            {
                // Remove the time portion.
                this.m_DateOfBirth = value.Date;
            }
        }
    
        public TimeSpan Age
        {
            get
            {
                return DateTime.Today.Subtract(this.m_DateOfBirth);
            }
        }
    }
    Note that the Age is calculated on demand, and it is read-only because there is no setter.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  7. #7
    Hyperactive Member Sgt-Peppa's Avatar
    Join Date
    Mar 2003
    Location
    Munich - Germany
    Posts
    476

    Re: private and public methods?

    Quote Originally Posted by {yak}
    Thank you for the reply
    I remember reading somewhere that you should declare everything in a class private, but it didn't make sense to me to make a public method to call a private one. Now that you have cleared that up, it makes sense that public methods can call other private methods that are not exposed.
    Again thanks for the reply. Another question I've been wondering. Say you do have a public method, that's being called, and it takes 2 parameters, is it safe to just call the method like so:
    Code:
    Class1 c = new Class1();
    c.MyMethod("param1", "param2");
    Or, should you always use get{} and set{} to set the values before you use them in the methods?
    I'm trying to make sure i've got all the right ideas before I get further down the road, and realize i've done everything completley wrong.

    Thanks;
    If you call a method like that it is perfectly OK. Just make sure to check those Parameters in your method and throw an Argument / Argument null Exception if they are not correct.
    Keep Smiling - even if its hard
    Frankie Says Relax, wossname Says Yeah!
    wossname:--Currently I'm wearing a gimp suit and a parachute.
    C# - Base64 Blog

  8. #8

    Thread Starter
    Lively Member {yak}'s Avatar
    Join Date
    Aug 2005
    Posts
    119

    Re: private and public methods?

    Quote Originally Posted by Sgt-Peppa
    If you call a method like that it is perfectly OK. Just make sure to check those Parameters in your method and throw an Argument / Argument null Exception if they are not correct.
    Thanks, Thats another question I was goign to ask, but you answered them both In the method, do you check to see they are of the right type, and if they empty? Or since you declare them as strings when you create the method, that will take care of it?
    {yak}

  9. #9
    Hyperactive Member GlenW's Avatar
    Join Date
    Nov 2001
    Location
    Gateshead, England
    Posts
    479

    Re: private and public methods?

    I tend to find I use 'private' the most, then 'internal' and then 'public'.

  10. #10

    Thread Starter
    Lively Member {yak}'s Avatar
    Join Date
    Aug 2005
    Posts
    119

    Re: private and public methods?

    Quote Originally Posted by jmcilhinney
    A public property is used in .NET in the majority of cases where a public variable would have been in other languages, or two methods in Java. You can certainly use a constrcutor to set a private variable but without the public property you could not set it after the object had been created. Also, a property does not have to refer to a specific, single variable, plus it can do other processing as well. For instance, lets say you had a Person class that had a private variable of type DateTime that stored a date of birth, which was exposed via a public property. You could provide a second property of type TimeSpan that returned the person's age by calculating it from the date of birth and the current date:
    Code:
    public class Person
    {
        private DateTime m_DateOfBirth;
    
        public DateTime DateOfBirth
        {
            get
            {
                return this.m_DateOfBirth;
            }
            set
            {
                // Remove the time portion.
                this.m_DateOfBirth = value.Date;
            }
        }
    
        public TimeSpan Age
        {
            get
            {
                return DateTime.Today.Subtract(this.m_DateOfBirth);
            }
        }
    }
    Note that the Age is calculated on demand, and it is read-only because there is no setter.
    Great example. OK, before I've seen this, to set a private variable and then use it within another class:
    Code:
    private string strMyString;
    // now set the string somewhere in this class
    
    // then make a method to return the string, so you can use the strMyString value in another class
    public string GetString()
    {
        return this.strMyString;
    }
    I don't have .NET here to test things out, but instead of doing that, would you use a property, like you did, and just use get? Like so:
    Code:
        public string TheString
        {
            get
            {
                return this.MyString;
            }
        }
    And then In my other class I would be able to call TheString, and get the value of MyString? Again, I don't have .NET installed on this computer to test, I want to make sure I'm getting the right idea.

    Thanks guys
    {yak}

  11. #11
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: private and public methods?

    Quote Originally Posted by {yak}
    In the method, do you check to see they are of the right type, and if they empty? Or since you declare them as strings when you create the method, that will take care of it?
    The arguments are of the type declared in the method definition. If you try to pass arguments that are not of that type an exception will be thrown, so there is generally no need to check the type. An exception to this would be if you declare the argument as a base type and then pass derived types from your code. An example would the "sender" argument in an event handler, which is declared as type Object but will always be some more specific type.

    As for properties, you are quite correct. Before the advent of properties you would have used two methods, e.g. GetString and SetString, to retrieve and assign to your private variable, e.g. myString. This is exactly what is done in Java. Internally, the property works in exactly the same way, because whenever the property is used either the "get" or "set" method will be called. Like I said, externally a property is like a variable but internally it is like a method or methods.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  12. #12

    Thread Starter
    Lively Member {yak}'s Avatar
    Join Date
    Aug 2005
    Posts
    119

    Re: private and public methods?

    Awesome, thanks alot, both of you!

    I'm affraid i've have yet another question
    I have a Sql connections class, which holds my sql connections, now say in one of my classes, I'm going to use those connections, in a method or something. Do I create a new instance of the sql class in each method that i'm going to be using it? Or When should I create it?

    Code:
    public string SqlMethod()
    {
    	sql s = new sql();
    	s.Open(); // and other methods that are in there
    }
    
    // but now i'm going to do some oether sql things in a different method
    // do I create a new sql class in here also? or wheres the best place
    
    public string SqlMethod2()
    {
    	sql s = new sql();
    	s.Open();
    	// and so on...
    }
    Any advice?
    {yak}

  13. #13

    Thread Starter
    Lively Member {yak}'s Avatar
    Join Date
    Aug 2005
    Posts
    119

    Re: private and public methods?

    Bah! My bad, I'm going to make a few of the methods in the sql static, so I wont need to create a new instance of the class each time.
    jmcilhinney's post a few threads down helped my decision
    {yak}

  14. #14
    Frenzied Member StrangerInBeijing's Avatar
    Join Date
    Mar 2005
    Location
    Not in Beijing
    Posts
    1,666

    Re: [RESOLVED] private and public methods?

    Dont know if you should make a method like that static.

    You might want to use instances of the class to connect to different datasources. I'm sure others will soon post with more reasons.

    Just started getting into the habbit of using static methods too, and must say, It's really handy!
    Install and Configure Eclipse For both Java and PHP development
    Accessible Ajax/jQuery Forms Degrade gracefully with JavaScript Disabled

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width