There seems to be no point of using encapsulation - php

Two simple, classes, one checks length and returns true of false. Second checks if first class returned true or false and returns message depending on that. Now, my question is, what difference does it make whether I put my variables as public, protected or private(note: I know what they are).
Why would I do it, who, if I put my variables as public can access it?
I know what encapsulation is and how it tells to encapsulate all class members, but there seems to be no point really.. If it was IRL I can understand that yeah someone might take something off of my house, so I should keep them all locked.. but in programming doesn't seem to make any sense..
http://www.codeproject.com/Questions/161855/Encapsulation-and-why-we-must-use-it
This guy tells anyone can access class members, but who're these anyone? I thought PHP runs in server and access to it is restricted by default. Nobody beside you can access/edit the file..
class Length_class{
public $bus;
public $returned;
function __construct($bus){
$this->bus = $bus;
if($this->bus < 10){
$this->returned = false;
}else{
$this->returned = true;
}
}
}
class Length_class_extended extends Length_class{
function display_length(){
if($this->returned){
return "Length is $this->bus";
}else{
return "Length is $this->bus";
}
}
}
$Length_class_extended = new Length_class_extended(10);
echo $Length_class_extended->display_length();

Maybe it doesn't make sense in this little piece of code. But an actual application is way bigger than that with much more classes (and people) working on it.
The security that encapsulation provides is not about someone hacking your code. It is about someone that you know that is going to use your code and you want to say what he may or may not access.
You use encapsulation to specify what your class is and what it should do. It helps you with defining the responsibilities of your classes. And helps other developers to be aware of it without the need of knowing how you implemented that.
Well-encapsulated code provides painless (or at least a lesser pain) class modifications.

The primary reason for using access modifiers is when you provide the class for someone else to use. With encapsulation the other programmer can use your class within his code without ever needing to know what goes on inside your class.
He will have a list of methods to use and will only interact with the class through this interface. This forces him to use the method 'correctly' in a way that won't break either his program or the functioning of your class.
It may not seem relevant to you if you are the only person using the code and it is a relatively straightforward project, and it is perfectly possible to write functioning code with every member public - it is however good practice and worth doing anyway. It forces you to write in a 'good' style with real encapsulation and may save you a headache later on by stopping you from misusing your own class if you want to reuse the code in a wide variety of situations.

Related

Am I setting myself up for failure using a static method in a Laravel Controller?

I am quite new to OOP, so this is really a basic OOP question, in the context of a Laravel Controller.
I'm attempting to create a notification system system that creates Notification objects when certain other objects are created, edited, deleted, etc. So, for example, if a User is edited, then I want to generate a Notification regarding this edit. Following this example, I've created UserObserver that calls NotificationController::store() when a User is saved.
class UserObserver extends BaseObserver
{
public function saved($user)
{
$data = [
// omitted from example
];
NotificationController::store($data);
}
}
In order to make this work, I had to make NotificationController::store() static.
class NotificationController extends \BaseController {
public static function store($data)
{
// validation omitted from example
$notification = Notification::create($data);
}
I'm only vaguely familiar with what static means, so there's more than likely something inherently wrong with what I'm doing here, but this seems to get the job done, more or less. However, everything that I've read indicates that static functions are generally bad practice. Is what I'm doing here "wrong," per say? How could I do this better?
I will have several other Observer classes that will need to call this same NotificationController::store(), and I want NotificationController::store() to handle any validation of $data.
I am just starting to learn about unit testing. Would what I've done here make anything difficult with regard to testing?
I've written about statics extensively here: How Not To Kill Your Testability Using Statics. The gist of it as applies to your case is as follows:
Static function calls couple code. It is not possible to substitute static function calls with anything else or to skip those calls, for whatever reason. NotificationController::store() is essentially in the same class of things as substr(). Now, you probably wouldn't want to substitute a call to substr by anything else; but there are a ton of reasons why you may want to substitute NotificationController, now or later.
Unit testing is just one very obvious use case where substitution is very desirable. If you want to test the UserObserver::saved function just by itself, because it contains a complex algorithm which you need to test with all possible inputs to ensure it's working correctly, you cannot decouple that algorithm from the call to NotificationController::store(). And that function in turn probably calls some Model::save() method, which in turn wants to talk to a database. You'd need to set up this whole environment which all this other unrelated code requires (and which may or may not contain bugs of its own), that it essentially is impossible to simply test this one function by itself.
If your code looked more like this:
class UserObserver extends BaseObserver
{
public function saved($user)
{
$data = [
// omitted from example
];
$this->NotificationController->store($data);
}
}
Well, $this->NotificationController is obviously a variable which can be substituted at some point. Most typically this object would be injected at the time you instantiate the class:
new UserObserver($notificationController)
You could simply inject a mock object which allows any methods to be called, but which simply does nothing. Then you could test UserObserver::saved() in isolation and ensure it's actually bug free.
In general, using dependency injected code makes your application more flexible and allows you to take it apart. This is necessary for unit testing, but will also come in handy later in scenarios you can't even imagine right now, but will be stumped by half a year from now as you need to restructure and refactor your application for some new feature you want to implement.
Caveat: I have never written a single line of Laravel code, but as I understand it, it does support some form of dependency injection. If that's actually really the case, you should definitely use that capability. Otherwise be very aware of what parts of your code you're coupling to what other parts and how this will impact your ability to take it apart and refactor later.

Why cant i just use public property and not be looked down at

I see (and write) a lot of code like this:
class MyClass
{
private $_myProperty;
public function setMyPropert($myProperty)
{
$this->_myProperty = $myProperty;
}
public function getMyProperty()
{
return $this->_myProperty;
}
}
Since we are taught that class properties should always be private.
However, i really just want to do this in the above scenario:
class MyClass
{
public $myProperty;
}
Thats much less code and easier to read. But other developers would look down on this code and most likely it would fail code reviews etc. Even if not, i would still never do this for fear of someone else seeing it and making judgement.
Why though? Is this something that is just ingrained in developers of oop code? Or is there another reason that I'm missing, perhaps related to testing, future maintenance or other non obvious technical reason. I am talking specifically in a scenario where the getter/setter does noting more that get/set.
If you are doing nothing in your getters and setters, then yes, you may as well just make the property public. But setters are typically used to check the value to make sure it's valid:
public function setFoo($foo) {
if (!is_string($foo)) {
throw new InvalidArgumentException('No you foo-l!');
}
$this->foo = $foo;
}
It's a good idea to do that to ensure the integrity of the class, that's what encapsulation is for. And even if you're not doing this checking now, you may be adding it in the future after you have fixed the 3rd bug resulting from something setting invalid values. If you then suddenly start switching to method calls instead of property assignment, you'll have a hard time retrofitting all your code that's setting properties.
Best start with actual encapsulation as early as possible.
This really comes down to the open/closed principle:
software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification
In this context, the principle means that the members of a class should be private by default.
It might seem like, in some cases, you can just declare a public member. You can, but it's still true that you shouldn't do it as a rule. It's partly just avoiding bad habits -- exposing all a class's members to everyone is just sloppy.
It's also a question of signalling your intent: if someone sees a public member, what do they think? There's no immediate way of knowing if the author intended for the member to be public, or if they just didn't really know what they were doing.

private methods and variables in PHP usage [duplicate]

This question already has answers here:
What is the difference between public, private, and protected?
(16 answers)
Closed 9 years ago.
I have been thinking about the usage of private variables and methods in php.
I am not going to talk about a class of car or anything like that. I want to talk about an own script.
What is the difference between using public or private for the programmer and the owner of the script.
if the script is a calculator, and I am the only one who will meinten the code in the future. when do I have to use private variables of methods. How this is going to change anything in the script?
Also, If it's about touching the variable ? if anyone tries to change the value, and he couldn't because of the private thing. He will go directly to change it using the setters ?
I need a good example that I can see private methods or variables have good benefits for programmer or the end user.
I was programming some scripts, and a guy told me to not use var in classes. I asked him why ? he said that you have to use public or private .. and asked why ?
Why to use setter if there is a way to change the variable directly?
Why to use getter if there is a way to change the variable directly?
First of all, when you're developing strong-OO classes, you should be exposing as little of the internal semantics of your class as possible (obviously without affecting functionality).
Some variables are only valuable inside the context of the class itself, and would make no sense to a developer using the class. Making the variable public allows anyone using the class to change such a variable at will, despite the fact that they may not know what it's used for. In PHP this can be a particular problem when you don't even have type safety to at least mitigate the damage that can be done.
Consider this: You have a class which wraps around some I/O operations. Let's call it FileReader
class FileReader {
public $_handle;
public function __construct($filepath) {
$this->_handle = fopen($filepath, 'r');
if ($this->_handle === NULL) {
throw new Exception("Unable to open the file for reading");
}
}
// ... the rest of the class
}
Now you can see that the class opens up a handle to a file. By making the $_handle variable public, you've exposed it to any and all people working on your class. They don't need to know about the raw file handle you have open, they just want to use your nice class to perform some read operation. However, it IS public; not only can they see it, but they can change it. This is bad, especially when your other code assumes that the $_handle variable is valid.
$reader = new FileReader();
$reader->_handle = "I hope this doesn't break anything. /trololol";
$reader->someOperation(); // oh no! Our file handle has just been changed to something completely wrong, this is now going to the break the class.
Such ridiculous scenarios can be avoided entirely by making the variable private in the first place. For more (and better) example of what each access modifier does, and when to apply them see this answer.
Now, onto getters and setters. In your question, you seem to assume that all getters and setters are written the following way:
class Foo {
private $_bar;
public function getBar() {
return $this->_bar;
}
public function setBar($newBar) {
$this->_bar = $newBar
}
}
In which case, you're absolutely right there is no difference between that and changing the $_bar variable to be public in the first place.
However, getter and setter methods give you control over how your variables are being set by an external developer, so you can instantly detect when they're going to make a boo-boo and avoid undefined behaviour later on. For example:
class Foo {
private $_bar;
public function getBar() {
return $this->_bar;
}
public function setBar($newBar) {
// Now we're going to ensure that $newBar is always an integer
if (!is_int($newBar)) {
// not an integer, throw out an exception to let the developer know that somewhere is setting invalid input
throw new Exception("Expected an integer value for 'Bar'");
}
$this->_bar = $newBar;
}
}
This is not only making your class far more robust, but also making the life of the developer using your class a hell of a lot easier. Rather than having to debug an extremely weird issue somewhere later on when the class attempts to use the corrupt value of $_bar, they can easily tell from a stack trace where the corrupt value was set from and fix it at the source.
There is plenty of documentation about variable access and getter/setter methods out there, and it applies to a whole range of languages so don't be afraid to look up articles that were based on C++/C#/VB.NET, they all roughly translate to the same material.
The end user doesn't see the code, so there's no (dis)advantage there.
For the programmer, declaring things that aren't needed outside the object as private is just a good programming practice and a protection mechanism. Technically, if you're a perfect programmer, and you don't care about how your code looks, using private will provide you no benefits. However, private members enforce the black box model -- you only care about what the object does, not about how it works (when looking at it from the outside). In the end, if for any reason you (or somebody else) needs/wants to use your code, they'll know what methods and properties to use/invoke in order to get the functionality the object has, without modifying the internal values the object needs to maintain. It may or may not give you any advantage -- it's just about how the code looks like. That's what good programming practices are for, and they are usually followed because experience says they tend to minimize errors.
As for var, it was deprecated. Meaning it could (and will) be removed in the future.
Public, Private and Protected only matter in PHP if they are part of a function, or part of a class.
If you wanted to set a variable once and "lock it" so the value couldn't be changed later you can define it or set it as a const (constant).
public scope to make that variable/function available from anywhere,
other classes and instances of the object.
private scope when you want your variable/function to be visible in
its own class only.
protected scope when you want to make your variable/function visible
in all classes that extend current class including the parent class.
See here: http://php.net/manual/en/language.oop5.visibility.php

Abstract class - children type

I'm trying to design some class hierarchy and I got "stuck" at this part.
Lets say that I have following classes
abstract class Video
{
const TYPE_MOVIE = 1;
const TYPE_SHOW = 2;
abstract public function getTitle();
abstract public function getType();
}
class Movie extends Video
{
// ...
public function getType()
{
return self::TYPE_MOVIE;
}
}
class Show extends Video
{
// ...
public function getType()
{
return self::TYPE_SHOW;
}
}
In the diffrent part of the system I have (Parser) class that encapsulates creation of
movie and show objects and returns obj. to the client.
Question: What is the best way to get a type of a obj. returned from parser/factory class, so that client can do something like
$video = $parser->getVideo('Dumb and Dumber');
echo $video->getTitle();
// Way 1
if($video->getType == 'show') {
echo $video->getNbOfSeasons();
}
// Way 2
if($video instanceof Show) {
echo $video->getNbOfSeasons();
}
// Current way
if($video->getType == Video::TYPE_SHOW) {
echo $video->getNbOfSeasons();
}
Is there a better way than my solution (read as: does my solution suck?)?
Is there a better way than my solution (read as: does my solution suck?)?
Your solution does not suck, per se. However, whenever someone is trying to determine the subtype to perform some actions, I tend to wonder; why? This answer might be a little theoretical and perhaps even a little pedantic, but here goes.
You shouldn't care. The relationship between a parent and a child class is that the child class overwrites the behaviour of the parent. A parent class should always be substitutable by it's children, regardless which one. If you find yourself asking: how do I determine the subtype, you're usually doing one of two things "wrong":
You're attempting to perform an action based upon subtype. Normally, one would opt for moving that action to the class itself, instead of "outside" of the class. This makes for more manageable code as well.
You're attempting to fix a problem you've introduced yourself by using inheritance, where inheritance isn't warranted. If there is a parent, and there are children, each of which are to be used differently, each of which have different methods, just stop using inheritance. They're not the same type. A film is not the same a tv-serie, not even close. Sure, you can see both on your television, but the resemblance stops there.
If you're running into issue number 2, you're probably using inheritance not because it makes sense, but simply to reduce code duplication. That, in and on itself, is a good thing, but the way you're attempting to do so might not be optimal. If you can, you could use composition instead, although I have my doubts where the duplicated behaviour would be, apart from some arbitrary getters and setters.
That said, if your code works, and you're happy with it: go for it. This answer is correct in how to approach OO, but I don't know anything about the rest of your application, so the answer is generic.
I'd go with way 2. It abstracts you the need to add another constant at Video in case you may want to add class SoapOpera extends Show (for instance).
With way #2, you are less dependent on constants. Whatever information you can gain without hardcoding it, means less problems to likely happen in the future in case you want to extend. Read about Tight an Loose Coupling.
I think the second option is better, using instanceof. This is in general common to all OOP design and not just PHP.
With your first option, you have specifics about derived classes in the base class, and thus must modify the base class for each new derived class you add, which should always be avoided.
Leaving the base class as-is when adding new derived classes promotes code reuse.
If there is a "right" way, and everything is subjective in coding of course (as long as it doesn't adversely impact performance/maintainability ;) ), then it's the second way as "Truth" and "Brady" have pointed out.
The upside of doing things the way you're doing them now (class constants in the abstract) is that when you're working with other developers it can provide hints as to how you expect the abstract class to be interacted with.
For instance:
$oKillerSharkFilm = Video::factory(Video::MOVIE, 'Jaws', 'Dundundundundundun');
$oKillerSharkDocumentary = Video::factory(Video::DOCUMENTARY, 'Jaws', 'A Discovery Shark Week Special');
Of course, the downside is that you have to maintain the "allowable extensions" in the abstract class.
You could still use the instanceof method as demonstrated in your question and maintain the list of allowable extension in the abstract predominantly for control/type fixing.

Independent getter/setter methods, or combined?

While working on a project, I've been making some changes and browsing around existing framework API docs for insight.
While perusing the Kohana docs, I noticed that the getters/setters of any given class are typically combined:
public function someProperty($value = null){
if(is_null($value){
return $this->_someProperty;
}
$this->_someProperty = $value;
return $this;
}
Rather than:
public function setSomeProperty($value){
$this->_someProperty = $value;
return $this;
}
public function getSomeProperty(){
return $this->_someProperty;
}
Is there any value in doing this (the former), beyond lessening the method count of a given class? I was always under the understanding that methods (functions in general) should be more descriptive of an action. Do other experienced developers cringe, even a tiny bit, when they see this?
I was just surprised to see a popular framework use such conventions (I haven't used Kohana of course)
I consider this bad practise because it violates CommandQuerySeparation. Setting a value is changing state (Command). Getting a value is asking for state (Query). A method should not do both, but one thing only.
Also, it's not really obvious what a method does when it's just called username, e.g. does not have a verb, like get or set. This gets even worse in your example, because the return value is either the object itself or the property value, so its not consistent.
Moreover, getters (and setters) should be used sparingly as they will quickly convolute your API. The more getters and setters you have, the more knowledge about an object is required by collaborators of that object. If you find your objects asking other objects about their internals, chances are you misplaced the responsibilities.
jQuery goes the same way as Kohana. However I think it's better to create separate methods for setting and getting. It's more obvious what the method does and I think it's more practically in code-completition in your ide. For example you type set and you get a list of all Properties you can set.
Another disadvantage is: what if you want to set a value really to null? This wouldn't work since the null is the identifier for returnin the value, you are restricted in setting specific values...
So it's nice, since you'll have to write less, but hey what are three letters (set/get) in front of your methods?
Despite the fact that Kohana uses such unusual technique for the OOP, I think you should follow coding conventions at first. But of course it's better to use separate getters and setters for every property in your classes. So, if it's possible to use them not breaking the conventions - just do it and you won't be wrong ;) . You can also read here about good habits in PHP OOP - http://www.ibm.com/developerworks/opensource/library/os-php-7oohabits/ if you've doubted about using some OOP technics. Hope that it'll help :)
I'd rather believe they had a reasonable explanation for doing it this way. For example, for easier implementation of ArrayAccess. Only way to know for sure is to ask them directly.
To answer your question, yes I cringe when I see the first method. Goes against OOP principles.
Why not do it like this?
public function someProperty($value = null)
{
if (func_num_args() === 1) {
$this->someProperty = $value;
return $this;
} else {
return $this->someProperty;
}
}
This would imo be the only correct way to implement a combined getter/setter
If you do it everywhere it is a good way, but than it really needs to be for everything, maybe the programmers of this framework are used to is, (it's a bit jquery alike)
However it would confuse me
For setting and getting I always use setters and getters:
public function __set($key, $value) {
// assign value $value to $this->key
}
public function __get($key) {
// return value of this->key
}
For the sake of argument,
The combined approach does offer some benefits:
Avoids __get and __set magic while still emulating a public property. (I would not ever recommend using magic for these situations anyway)
Using thing() is less verbose than using getThing() setThing().
Even though the methods will be doing more, they can still be considered as "doing one thing()", that is handling the thing(). Properties also do more than one thing. They allow you to set and get values.
It's argued that the thing() doesn't give a verb. However, we can assume that a thing() without a verb means that we use it like a property (we get and set it). For interfaces, we can say that a thing() with no argument is readonly and a thing($arg) with an argument is read/write. Why should we be shy from adopting this? At some point we adopted the idea of adding getters and setters didn't we?
If you are using a web-based language (like PHP), then chances are you might be using jQuery as well. JQuery is already doing this sort of thing() and it has worked out well.
Using func_num_args(), as mentioned already, helps achieve this approach perfectly.
Personally, I've already taken a good portion of risks in my current apps at this point so I'm probably going with the old tried-and-true getters and setters (see the section "Finding the Balance" of Jimmy Bogard's post in regards to getters/setters for data operations). And I suppose we are already trained to look for these get/set prefixes (as well as our IDE's) to see what properties we can work with in a class. This is a discussion I would be open to returning to at some point.

Categories