473,811 Members | 1,788 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

OOP clarification

348 Contributor
Hey everyone. I'm back in search of a better understanding of OOP. I feel like these past couple of months have paid off for me because I am at a point where I am really beginning to understand how this all works. I'd like to get some clarification on a few things first.

My questions stem from wanting to use private members and methods. I know that there is a reason for making methods and members public and private and honestly I'm still not totally clear as to when to use one over the other. I have been refactoring some of old classes and in looking at them, I was mortified. I figured that when I was redoing them that I should try and stick with private members and methods where possible because that's a good thing I guess.

I had download an app a while back that used 5 classes. Each class was like 1500 lines or so and the code looked clean to me. I figured that was a good way to program. I started to do the same thing but after looking over some of my classes, I quickly noticed that my classes were nothing more than functions instead of objects.

In refactoring this code, I separated out the methods that required functionality inside the class and set my constructor to call a main method that would do what was needed and then return out the values I needed. I just want to make certain that I understand correctly before I continue any further.

If I have a class like so:

Expand|Select|Wrap|Line Numbers
  1. class Hello{
  2.     public  $out;
  3.     private $text;
  4.  
  5.     public function __construct($text)
  6.     {
  7.         $this->text = $text;
  8.         $this->sayHello();
  9.     }
  10.  
  11.     private function sayHello()
  12.     {
  13.         $text = $this->text;
  14.         $var = 'Hello, my name is: ' . $text;
  15.         return $this->out = $var;
  16.     }
  17. }
  18.  
  19. $hello = new Hello('Tom');
  20. echo $hello->out;
To me, this seems like the correct way to write a class. I am returning out the values that I want. The way I was doing it in the past was to call the method directly and didn’t seem right.

Does this look correct? I have a few more questions but I'll wait on those for now to see what the feedback is on this. I'll also show you how I was doing before.

Thank!

Frank
May 19 '09 #1
51 3587
Dormilich
8,658 Recognized Expert Moderator Expert
I wouldn't have named the method "sayHello" because it's not 'saying' (aka printing/outputting) anything, but generally it's right. personally, I don't see the necessity of every method having a return value (esp. when you have printing methods) though if possible I let it return true/false.

on the other hand, you're not using the return value…

some simplifications I'd make
Expand|Select|Wrap|Line Numbers
  1. class Hello
  2. {
  3.     public  $out;
  4.     private $text;
  5.  
  6.     public function __construct($text)
  7.     {
  8.         $this->text = $text;
  9.         $this->out = $this->sayHello();
  10.         // $this->sayHello();
  11.     }
  12.  
  13.     private function sayHello()
  14.     {
  15.         return 'Hello, my name is: ' . $this->text;
  16.         // $this->out = 'Hello, my name is: ' . $this->text;
  17.     }
  18. }
for this simple class there could even be more improvements, like omitting Hello->out and using sayHello() or even __toString() for output
May 19 '09 #2
fjm
348 Contributor
@Dormilich
Ok, I understand that. Thanks. :)

In your example where you said that you would shorten it to sayHello(), isn't this acting more like a simple function than a class? This was the way that I was using it before. Because I had so many of these types of methods in a single class and would call them directly, I couldn't keep the methods private.

I know that in your example you are using the constructor to call the sayHello method but what if you have more than 1 or even 10 of these type of methods that require one or two variables? What do you do? How do you call them?

$foo = new MyClass();
echo $foo->myMethod($var) ;

My example above requires that the myMethod() method remain public. Is this not a big deal? Also, say that I have 20 of these exact type of methods in the class that each expect one or two variables passed. It seems to me that if I am passing variables directly into the methods that I should forgo the class and just use a function. No? I don't see the difference or the advantage in using your sayHello() example over a simple function.

Thanks for the help Dormi. :)
May 19 '09 #3
Dormilich
8,658 Recognized Expert Moderator Expert
@fjm
well, yea, but do you want to handle any output through properties? (that may work for 1 or 2, but what about undefined/several different outputs?)

@fjm
methods are not supposed to be solely private, what use would the object then have (and what use would the interface have)?

private methods are good, if you need tasks done that shouldn't be initialized from the outside (like e.g. connecting to a database or loading a configuration)

@fjm
???

@fjm
no

@fjm
not every method expects a variable input, often you can use the properties to pass around variables.

in fact your example could be handled better by a function. but there are situations, where objects are better. I can think of writing an batch mail where the email addresses are stored in a DB.

OOP is more than using private methods. you also have (to name some):
- data encapsulation (prevents globals running wild)
- inheritance (share code, re-usable)
- patterns for common tasks (e.g. Singleton, Observer, Factory)
- magic methods (kind of event handling)
May 19 '09 #4
Atli
5,058 Recognized Expert Expert
Hi.

A couple of things I'd like to comment on...

First.
I think your assumption that methods should preferably be private is not really correct.

Private members are only accessible from within the class itself, so any functionality or data you want accessible from the outside should (obviously) not be made private.
Private members should complement the public once, but never be a requirement. Ideally, you should be able to inline ALL private functions into the public functions without having to change how the outside code uses the class.

It's best to design classes in a way that allows you to redesign the entire interior of the class without having to change the publicly declared functions and variables. (Check out interfaces to see what I mean)

Second.
The way in which you designed your example class is very odd, really.
It has no public functions, which basically just makes it a complex array with a constructor.

Objects are meant to be more than just a collection of variables or a collection of anonymous functions. Arrays and normal functions work fine for that.

Class members should work together.
Public members being the controllers; the way the outside interacts with it.
Private members providing functionality for the public functions; the internal mechanism that the outside doesn't need to be bothered with.

Consider this alteration to your original example:
(Sorry about the doc blocks... can't seem to not add them :P)
(Edit... turns out I could :D)
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. class Hello {
  3.     private $name;
  4.      private $language;
  5.  
  6.     public function __construct($name, $language="enUS") {
  7.         $this->name = $name;
  8.         $this->language = $language;
  9.     }
  10.  
  11.     public function sayHello() {
  12.         echo "<h3>", $this->createHello(), "</h3>";
  13.     }
  14.  
  15.     public function getHello() {
  16.         return "<h3>". $this->createHello() ."</h3>";
  17.     }
  18.  
  19.     private function createHello() {
  20.         if($this->language == "isIS") {
  21.             return "Halló, ég heiti {$this->name}.";
  22.         }
  23.         else { // Defaults to enUS
  24.             return "Hello, my name is {$this->name}.";
  25.         }
  26.  
  27.     }
  28. }
  29.  
  30. // Say it in english
  31. $eng = new Hello('Tom');
  32. $ice = new Hello('Atli', 'isIS');
  33.  
  34. $eng ->sayHello();
  35. echo "<center>", $ice->getHello(), "</center>";
  36. ?>
I've implemented both a "sayHello" and a "getHello" function, both using the "createHell o" function to provide the message.

As the "createHell o" function was only ever meant to be used by the other class functions, it is made private; inaccessible to the outside.
The other two, meant to provide functionality to outsiders, are public.

I've also added the ability to change languages of the message.
The "createHell o" function is the only function that is actually aware there is a language choice (besides the constructor), but because of the cooperation between the functions, the effect is shared between them.

This also means that if I ever need to change the message, I only ever need to change it in one place.
Likewise, if I ever need to change the way the hello message is printed, that is in one place, rather than scattered all over your outside code, as it would have been with your example.

Do you see what I'm trying to say?
May 19 '09 #5
fjm
348 Contributor
@Dormilich
Is this not acceptable?

Originally Posted by fjm
I know that in your example you are using the constructor to call the sayHello method but what if you have more than 1 or even 10 of these type of methods that require one or two variables? What do you do? How do you call them?
I am under the impression that each class should have a single function (and not in the literal sense). Let me give you an example. I have a class with two methods. The first method gets data from a database then internally passes the values to the second method where the data is checked then returned to the main script. In the constructor, I call the first method which starts the process. My thoughts are that the class should only do one thing. You can feed it the var(s) and it returns what you need.

Expand|Select|Wrap|Line Numbers
  1. class Hello{
  2.     public  $out;
  3.     private $text;
  4.  
  5.     public function __construct($text)
  6.     {
  7.         $this->text = $text;
  8.         $this->sayHello();
  9.     }
  10.  
  11.     private function sayHello()
  12.     {
  13.         $text = $this->text;
  14.         $var = 'Hello, my name is: ' . $text;
  15.         return $this->out = $var;
  16.     }
  17.  
  18.     public function doSomething()
  19.     {
  20.         $val = 'Do something here';
  21.         return $val;
  22.     }
  23. }
  24.  
  25. $hello = new Hello('Tom');
  26. echo $hello->out;
In my original example, I added a doSomething method. Let's just say that this class was for nothing more than to say hello. I know that it isn't useful and I could come up with a better example but it conveys my point I think.

So, with this new public method, say that I wanted to call that method. I first have to create an instance but the constructor is looking for a var that has nothing to do with this doSomething method. How would I work this? Do you see what I mean?

private methods are good, if you need tasks done that shouldn't be initialized from the outside (like e.g. connecting to a database or loading a configuration)
Yes, I am seeing exactly what you mean. A good example of this would be a login script where the users' password should be made private.
May 20 '09 #6
fjm
348 Contributor
Heya Atli. I'm glad that you joined in to help. :)

@Atli
OK. I understand this acutally. I was just thinking that maybe it would be better to make methods private where possible for added security but I see that isn't always a good thing or even realistic especially after seeing your example.

@Atli
OK, I understand that. I guess my question is what if a public method really has nothing to do with any of the other methods? Let's say that you have several methods that just draw data from the database and the sql requires a var for the WHERE statement. We would have to pass that variable into the method. I guess what I am trying to say here is that I am not seeing much difference between a regular function and a public method where the public methods sole purpose in life is to return data from a database. Now, if that public function actually called a private function for something, I could see it. Am I wrong? Thanks for the link on interfaces, I will check that out.


@Atli
OK. This goes back to what I was saying about the constructor. Instead of using a public method to do this, I thought the constructor was supposed to handle this which was why I designed it that way.

@Atli
If I'm understanding you right, you're saying that instead of using the constructor to interact with the private methods, I should be using public functions. Yes?

I think that maybe your example is even better than mine because it illistrates my point even better. In your example, if you wanted to use another public method that has NOTHING AT ALL to do with any of the other methods, what do you do? Do you make another class for it? Say for example that you wanted to have another function that said goodbye but instead of using the person's first name, you would be required to use their last name. I know, I know... it's a really dumb example but it makes the point. :) Would you use a new class for this or use this same class?

I understand what you are saying, more so now then ever before. That's why I'm nitpicking here. I'm honestly getting this for a change. :)
May 20 '09 #7
fjm
348 Contributor
Atli,

I have been doing a bit more reading on this and have looked over the link on interface. Not certain exactly how that would help me out just yet but of course it's because I don't fully inderstand it yet. I will re-read it and look for some additional info on that.

Regarding post #5, in your example... Your private method acts as a mutator and the public getHello acts as an accessor, right?

Could we say that by having a mutator and accessor that we are encapsulating the data within the class? That's what it looks like to me. Am I right?
May 20 '09 #8
Dormilich
8,658 Recognized Expert Moderator Expert
@fjm
interfaces are a way for an outside developer to use your classes (think of the interface as API). conforming to an interface lets you use a class, without knowing the (internal) structure of this class.

when implementing an interface in a class definition, you make sure, that the required functionality is given (otherwise there will be an error).

an example may be found here

interfaces can also be used to check if an object has a (set of) public method you want to use later. (esp. when there are user defined classes involved)

(Atli can probably descibe that better…)
May 20 '09 #9
Atli
5,058 Recognized Expert Expert
OK, I understand that. I guess my question is what if a public method really has nothing to do with any of the other methods? Let's say that you have several methods that just draw data from the database and the sql requires a var for the WHERE statement. We would have to pass that variable into the method. I guess what I am trying to say here is that I am not seeing much difference between a regular function and a public method where the public methods sole purpose in life is to return data from a database. Now, if that public function actually called a private function for something, I could see it. Am I wrong?
Depends on how you look at it, and might well be a matter of personal preference.

Would the function be using any class variables?
Would it even be related to the class itself?

If both are false, then this function might indeed not belong to that class, but rather by itself or in a different class.
If only the second one is true, the you should consider making it a static method. (A method available even without creating an instance of the class.)

Like, say, in a classic animal class:
  • A method "speak" would be specific to an instance of the class, using the members for that instance. Clearly belongs to the class.
  • A method "getAllByTy pe" would not be specific to an instance, nor related in any way to any of the other members or methods. It should, however, belong to the animal class, as it does provide functionality relating to the class. (A perfect example of a static method.)
  • A method "setUpAminalDat abase", despite being somewhat related to the Animal class, provides no real functionality for the class itself. It should really belong to a separate, more database related, class... or just in a solo function somewhere.

I would imagine structuring a Animal class somewhat like:
Expand|Select|Wrap|Line Numbers
  1. class Animal {
  2.     /** Members **/
  3.     private $type;
  4.     private $name;
  5.  
  6.     /** Constructors / Destructors **/
  7.     public function __construct($type, $name, $insert=false){
  8.         $this->type = $type;
  9.         $this->name = $name;
  10.         if($insert) {
  11.             $this->addToDatabase();
  12.         }
  13.     }
  14.  
  15.     /** Instance methods **/
  16.     public function speak() {
  17.         echo ucfirst($this->getSound()), ", my name is {$this->name}, the {$this->type}. <br>\n";
  18.     }
  19.  
  20.     private function getSound() {
  21.         switch($this->type)
  22.         {
  23.             default: return "yum yum"; break; // Couldn't think of anything else :P
  24.             case "dog": return "woof woof"; break;
  25.             case "cat": return "meow"; break;
  26.         }
  27.     }
  28.  
  29.     public function addToDatabase() {
  30.         $sql = "INSERT INTO animals(name, type) VALUES('{$this->name}', '{$this->type}')";
  31.         return @mysql_query($sql) == true;
  32.     }
  33.  
  34.     /** Static methods **/
  35.     public static function getAllByType($type="dog") {
  36.         $sql = "SELECT name FROM animals WHERE type = '{$type}'";
  37.         if($result = @mysql_query($sql)) {
  38.             $output = array();
  39.             while($row = mysql_fetch_assoc($result)) {
  40.                 $output[] = new Animal($type, $row['name']);
  41.             }
  42.             return $output;
  43.         }
  44.         else {
  45.             return array();
  46.         }
  47.     }
  48. }
  49. ?>
To be used like:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. // Create a dog and a whale
  3. $cat = new Animal("cat", "Michell"); // Not added to the DB
  4. $whale = new Animal("whale", "Bob", true); // Added to the DB
  5.  
  6. // Get all dogs already in the database
  7. $dogs = Animal::getAllByType("dog");
  8.  
  9. // Make em all speak
  10. foreach($dogs as $_dog) {
  11.     $_dog->speak();
  12. }
  13. $cat->speak();
  14. $whale->speak();
  15. ?>
The method "getAllByTy pe" there being a key part of the class, despite the fact that it is detached from the rest of it, and that it only really performs a simple database query.
In your example, if you wanted to use another public method that has NOTHING AT ALL to do with any of the other methods, what do you do? Do you make another class for it? Say for example that you wanted to have another function that said goodbye but instead of using the person's first name, you would be required to use their last name.
Even if the method does nothing but take a name and echo it back to you in a "You have been logged out, $lastname. Goodbye." sort of way, If it is related to the class (a User class, in this scenario), then it should belong to it.
Even tho it may seem pointless to add this to the class, it may become imporant later on.

Imagine if, after using this goodbye method in 200 pages, the requirements are changed. You are now required to print a language specific message depending on the language set in the constructor. It's a simple change if the method was in the class from the start. Not so simple if it was a rogue function.

OK. This goes back to what I was saying about the constructor. Instead of using a public method to do this, I thought the constructor was supposed to handle this which was why I designed it that way.
The constructor is only supposed to handle the initialization of the class; making sure all the members are set and ready to be used by the methods.
Likewise, destructors are meant to unset members and free resources.

This includes tasks like opening/closing database connections and running security algorithms. Anything not meant to be accessed by the outside, but needs to be run every time the object is created.

You can of course go beyond that if you want to, but be very careful. Bloated constructors are never good.
Providing a public method is usually better, and much cleaner.

It's also common to use constructor parameters as shortcuts to execute commonly used methods. (Like I do in the Animal example above.)

I have been doing a bit more reading on this and have looked over the link on interface. Not certain exactly how that would help me out just yet but of course it's because I don't fully inderstand it yet. I will re-read it and look for some additional info on that.
Using Interfaces isn't vital, nor really needed, in any one class.
Especially not since the class itself serves as a blueprint for how the class is meant to be used.

Interfaces are used to describe a group of classes, who are all meant to provide the same... well, interface to be used by other parts of the code.

Kind of like cars... They all share the same interface. A wheel, a gear shift, pedals, etc..
We can always be sure every car is built around this same basic interface, even tho they all implement it differently beneath the surface, and most of them add additional functionality on top.

This is exactly what interfaces do for classes. They ensure that classes provide at least the methods specified in the Interfaces they implement.
They help maintain the integrity of the classes from a design perspective, but add little to how the classes themselves are actually built or used.
(Any class built upon an interface could simply remove the implements keyword and function exactly the same afterwards.)
May 21 '09 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

3
2212
by: Wes | last post by:
I am trying to secure different files, mostly pdf, so only the person suppose to see the file that was designed for that individual can see it. I am using sessions to secure the actual web pages, but now I am trying to secure non-php files. Here is where I need some help/clarification. I was told to save the files outside the Web accessible directories. Is this the directory before /www/ so would look like /home/domain/ and I would...
4
2896
by: Shea Martin | last post by:
Which of the following do I use delete instead of just delete. //1.) // not sure about this one, as char is of size 1 char *str = new char; //2.) //not sure about this one, as it is a primitive int *array = new int;
3
4080
by: John D. Sanders | last post by:
I have just upgraded MySQL from version 3.23 to version 4.1.8 and now I am getting the following error when I try to run a script that worked: install_driver(mysql) failed: Can't load '/usr/lib/perl5/vendor_perl/5.8.0/i386-linux-thread-multi/auto/DBD/mysql/mysql.so' for module DBD::mysql: libmysqlclient.so.10: cannot open shared object file: No such file or directory at /usr/lib/perl5/5.8.0/i386-linux-thread-multi/DynaLoader.pm line 229....
2
4553
by: Ethan | last post by:
This is a clarification of a previous message, which was not expressed very well. I have a set of checkboxes near the bottom of the page and a function that checks or unchecks all of them. But when the function runs, the window scrolls to the top of the page. How can I set my checkboxes but leave the window's scroll position exactly where it is? Or at least have it scroll to the bottom (where the checkboxes are). I've tried using...
9
2586
by: Adam | last post by:
Hi, I am having problems having an include file rendered in my browser (IE6). The include file contains <A href> tags to be used as a navigation bar in the footer of a .html file. I am using dreamweaver and the included html appears as expected in the 'Design View' but does not get rendered in the browser.
3
1420
by: ma740988 | last post by:
Consider the 'C' source. void myDoorBellISR(starLinkDevice *slDevice, U32 doorBellVal) { doorBellDetected = doorBellVal; } void slRcv() { starLinkOpenStruct myOpenStruct;
3
2426
by: solomon_13000 | last post by:
> Wonthaggi Civic Theatre 'WCT' Case Study > > The town of Wonthaggi has a theatre which is owned and > operated by the local council, it is called the > Wonthaggi Civic Theatre (WCT) and a wide variety of > shows are presented there, for example plays, music > and talks. The management has decided to build a > computer system for WCT to handle ticket sales, keep > track of the work done by staff and record all shows > presented in the...
0
288
by: chanchito_cojones | last post by:
Hi there, I was searching the net for some guidance in putting together a query that would select random records from the main table. I came across this and it works like a charm. SELECT TOP 5 * FROM tablename ORDER BY Rnd(IsNull(fieldname)*0+1);
8
1849
by: Sai Kit Tong | last post by:
In the article, the description for "Modiy DLL That Contains Consumers That Use Managed Code and DLL Exports or Managed Entry Points" suggests the creation of the class ManagedWrapper. If I need to build multiple mixed mode dll's used by a consumer application, do I have to implement multiple ManagedWrapper's (each embedded in indiviudal DLL project) and call all of them in my consumer application?
2
2925
by: ravir | last post by:
Hi, I am new to this group. I am working in Perl and shellscripts. I have a clarification regarding perl grep and pattern matching. I am writing a perl script to automate the process of code review upto some level so that the reviewer and developer's time can be reduced during the code review. In my script, I am using pattern matching and grep in many places. So, my clarification is : Is it fine to make use of grep to find a pattern in a...
0
9728
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10648
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10389
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10402
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7670
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5554
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5692
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4339
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3867
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.