Programming

Design Patterns, Java, OOP, Programming, Proxy, structural design patterns

Design Patterns: Proxy

Hi guys, Today’s pattern is named Proxy and comes under the Structural family’s patterns.

This design pattern helps us to surrogate another object in order to change and control its behavior.

The definition of Proxy design pattern from the GoF book.

Provide a surrogate or placeholder for another object to control access to it.

The Proxy design pattern is very easy in use. We can use it in many ways, creating an expensive object on-demand, controlling access to the original object, and performing additional actions when an object is accessed.

Create an object on demand

Sometimes, we need to create an object only if it is necessary especially in the case that object is expensive. So, we don’t want to load it in memory until the first access.

Control access to an object

We can use it easily in order to control access to an object. For example, we want to provide full access to an object if the user is the Admin and a partially access when it is a simple user. Hold on, you will see an example using control access in a while.

Additional actions in object

Last but not least, we can use a proxy design pattern in order to add new actions to an object. For example, we can create a new instance of an object and lock this object behavior in order to be sure that no one can change its behavior.

Example

Let’s suppose that we have a system and there is a need to have users with privileges. The admin user is able to use all functionalities even delete, and a simple user has limited access to those functionalities.

We start creating an interface in order to define the commands.

Let’s implement those commands.

It is time to provide the right privileges to each user.

Create an example using the classes above.

Output:

You can download the source code from GitHub.

behavioral pattern, Design Patterns, Java, OOP, Programming

Design Patterns: Mediator

The mediator pattern belongs in the family of Behavioral Patterns. It contains the entire logic of how objects interact with each other. So, it helps us decouple objects.

What’s the problem

In case we have many objects that interact with each other, we end up with very complex and nonmaintainable code. That’s why it is a good case to use the Mediator design pattern.

There are many times that we have interaction among objects. We usually create a sufficient amount of objects allowing us to communicate with each other with the intention of building entities that act together for a specific reason.

When something happens to an object then another one has to do something or change its behavior.

Building a complex code allowing many objects (2 or more) to communicate with each other, you will end up with spaghetti code, nonmaintainable, and you will face a nightmare every time you want to find and fix a bug or to enhance the code.

This problem increases if you normally have a back and forth and complex interaction.

How do I solve this problem

The solution comes using the Mediator pattern. This pattern allows you to keep the whole logic of communication in one place (object) and every object used to interact with other objects now interacts only with the one which is aware of how to act on every occasion.

So, we can understand very quickly that objects are decoupled. The code is more simple than it used to be. That’s exactly what we try to achieve using OOP and design patterns.

Drawbacks

Using the Mediator pattern and keeping the whole interaction among objects in one place (object) means that we are going to move complexity from one place to the other.

It is very easy to turn the Mediator pattern into a mess if you don’t separate objects appropriately. Even if you want to use the same objects but somehow different, you have to keep each behavior in separate mediator objects.

So, there is a need to simplify the mediator if necessary.

How do I code the Mediator Pattern?

It is really easy to write code with a mediator pattern.

We start with classes that encapsulate mediators and instead of interacting with each other, they interact with the mediator.

Every time each class needs to interact with an object, it calls a method from the mediator and only the mediator knows what object needs to be called.

For the mediator, we just need an interface. It is a good practice to use an interface or an abstract class for the mediator. In this way, you are able to have different implementation of the mediator object.

Example

Greek public services are a mess. Each time a Greek citizen needs to use a public service, he faces a huge bureaucracy. So, a citizen has to transfer and get a bunch of documents from one public service to the other. In this case the Greek citizen is the mediator. He is the one who has to go and find the right document in a group of public services. This is wrong from many aspects but it is a reality.

Let’s start our example by implementing this situation but a little differently, in the right way. Instead of using citizen as an intermediary mean, we will create a mediator which is going to be aware of all public services and how to use them. So, the citizen can go and ask the mediator for something and it is going to interact with public services (objects) for the desirable result.

In the following example, a Greek citizen who wants to start a new company is represented.

We start with an interface for the mediator.

Let’s implement this mediator.

Now it’s time to implement the objects which are going to interact with the mediator.

The following code is representing the Greek citizen.

Let’s create a function which runs the code

Output:

You can download the source code from GitHub.

behavioral pattern, Java, observer pattern, OOP, Programming, Software Engineering

Design Patterns: Observer

An observer is a pattern that falls under Behavioral Patterns. It is used when there is one-to-many relationships between objects. So, when an object’s state is changed then all its dependent objects are notified automatically.

When do you have to use Observer

  • When a change to one object requires to notify other objects.
  • We don’t need to be aware of how many objects need to be changed.
  • We don’t want these objects tightly coupled.

How to use it

The concept behind the Observer pattern is simple. We have a subject that is going to keep track of the observers. Every time this subject changes, all its observers are notified automatically. The subject contains some methods that allow observers to be registered or unregistered.

When the state of the subject changes then the subject has to notify all the observers which are registered.

This pattern is so flexible that sometimes we want to change this behavior and let observers ask the subject for the state and if it is changed, then the observer acts appropriately.

Example

Let’s suppose that we are at a university and we want to update every student who is registered in a course. If the student is registered in a specific course then every time the state of the course is changed, registered students will receive a notification.

Start with the Subject interface

We will implement the Subject interface.

Let’s create one more interface named Observer

StudentObserver class is going to implement the interface above.

Last but not least StudentObserver we have one more class named Email, and as you can imagine we are going to use this class so as to send emails to students.

Now we are ready to use these classes.

Output:

You can download the source code from GitHub.

behavioral pattern, Design Patterns, Game Development, OOP, Programming

Design patterns: State

Hi guys, I made a decision to see a different category of design patterns and this category is behavioral design patterns.

What a behavioral design pattern is. The text following is from Gang of Four.

Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects. Behavioral patterns describe not just patterns of objects or classes but also the patterns of communication between them. These patterns characterize complex control flow that’s difficult to follow at run-time. They shift your focus away from the flow of control to let you concentrate just on the way objects are interconnected.

So, today we will see the State design pattern.

What a State design pattern is. The text following is from Gang of Four.

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

The state design pattern is one of those that is used widely in game development. It helps us to describe the different states of a game-changing object’s behavior but keeping objects loosely coupled.

For example, we have a character who is able to jump only if he is standing and not sitting, and he is able to sit only when he touches the ground.

If we try to implement this character’s behavior we will come out with a code of full “if,elseif” and multiple complex conditions that make our code ugly.

Let’s try to add some functionalities to our character, he is able to shoot only if he is standing or jumping but not when he is sitting.

As you can imagine our code is already quite complex and unwieldy in order to find a quick and easy way to add this functionality.

So, the code’s maintainability is almost unattainable, and also there are many bugs and unpredictable behaviors hidden.

For this reason, the State design pattern helps us to simplify our code. The code will be more readable and maintainable.

Let’s see the next example

Example

We will have a character with a gun. There will be 2 different behaviors of the gun. In this example, we will see only the gun’s behaviors.

So, the gun has 2 states. In the first one, the gun is loaded with ammo and ready to fire, and in the second one, it is empty of ammo.

Let’s start to design the code using the State pattern.

Interface GunState

Now, we will create the 2 classes that implement the GunState interface. ShotGunHasAmmo & ShotGunHasNoAmmo.

Finally, we implement the GunContext class in order to see a changed behavior when it changes state.

Run The code

Output:
Shotgun is in has ammo state
Shotgun is shooting. Left Bulets 2
Shotgun is shooting. Left Bulets 1
Shotgun is shooting. Left Bulets 0
Shotgun is in empty of ammo state
Shotgun is empty!
Shotgun is empty!
Shotgun is in has ammo state
Shotgun is shooting. Left Bulets 3
Shotgun is shooting. Left Bulets 2
Shotgun is shooting. Left Bulets 1
Append 2 bullets in Shotgun
Shotgun is shooting. Left Bulets 2
Shotgun is shooting. Left Bulets 1
Shotgun is shooting. Left Bulets 0
Shotgun is in empty of ammo state
Shotgun is empty!
Shotgun is empty!

You can download the source code from GitHub.

Design Patterns, Game Development, Java, OOP, Programming, Software Engineering

Design Patterns: Dependency Injection

What Dependency Injection is. Let’s imagine an object that does a specific function. Now let’s imagine a second object that takes the first object as an argument. This object cannot function or can function partially without the first one. When this happens, it’s called Dependency Injection.

Dependency Injection is a design pattern and we want to use it when an object is dependent on another object. Doing that, we are able to enhance our code with new functionalities without changing the existing code. So, our code is maintainable and extendable while allowing our program to be loosely coupled.

There are 3 ways to perform dependency injection.

The first one is called Constructor Injection. In this case, the class takes the dependent object through the constructor.

Sample Code:

Next is Setter Injection. In this case, a class that needs an external object to work takes it from a setter method. Thus, we can pass the dependent object as an argument only if there is a need for that. Dependency Injection is optional in this case.

Sample Code:

The third one is called Interface Injection. In this case, we create an interface class that has a function that takes as argument an object.

Sample Code:

Sample Code

It would be better if we continued with an example of how to use dependency injection.

We are going to create a character for a game who is modular and we can change various things like hair color, t-shirts, head size, etc. In our case, we will see only the head size as an example. So, the user will be able to change the character’s head to a big one or a regular one.

Let’s start with our interface class which is named Head.

The next two classes will implement the Head interface creating either a big head or a regular head.

The next step is to create a player who is going to take an object of BigHead or RegularHead classes as an argument.

Let’s start with the Player interface.

The class above implements the Player interface and it creates a player either with a big head or with a regular one, depending on the class that it will take as an argument.

Finally, we will create one more interface that we will use in order to implement Dependency Injection.

As we can see, each one of the two classes above creates a Player object depending on the argument.

The last method does a print in our screen.

Output:
Hi, I am the player with a big head !
Hi, I am the player with a regular head !

You can download the source code from GitHub.

Some Other Useful Resources

http://fabien.potencier.org/what-is-dependency-injection.html
https://www.martinfowler.com/articles/injection.html
http://www.procata.com/talks/phptek-may2007-dependency.pdf

http://www.javacreed.com/why-should-we-use-dependency-injection/
http://tutorials.jenkov.com/dependency-injection/dependency-injection-containers.html

creational patterns, Design Patterns, Factory, Game Developer, Game Development, Java, OOP, Programming, Software Engineering

Design Patterns: Factory

The factory is one more design pattern that comes under creational patterns. Thus, this pattern is able to make our code less complex and it gives us the opportunity to get an object without using the “new” operator. The factory is quite simple in use.

The factory is used when there is a need to hide the way that an object instantiated and it’s complex or many dependencies are needed.

Also, as Head First: Design Patterns book refers

[quote name=””]Instantiation is an activity that shouldn’t always be done in public and can often lead to coupling problems.[/quote]

You can read more about this subject in the resources below.

javaworld.com

Head First: Design Patterns

Design Patterns: Elements of Reusable Object-Oriented Software

In other words, using the factory, different types of objects can be created and returned without using the “new” operator or be interested in how this object can be instantiated.

Through factory class, an instance of another class can be taken.

Sample Code

Let’s start analyzing the code below. We are going to create a character who is able to use a gun or his punches. So, we will start implementing these classes. At first, we will create an abstract class for Gun.

Next 2 classes extend from Gun abstract class. ShotGun and Punch classes.

Now we are ready to create our character with ActionFigure class.

In case that, we use constructor without any argument then our character is going to use Punch class.

Last but not least, we will create factory class that returns the desirable figure to us.

This class contains 2 functions, the first returns an instance of ActionFigure without a gun and the second with a gun.

Also, this design pattern is called Static Factory due to the static functions in factory. The advantage is that we don’t have to instantiate the factory in order to use createFigurePunch() and createFigureShotGun() functions.

The drawback is that we are not able to subclass and change createFigurePunch() and createFigureShotGun() functions behavior.

In continuing, we call and get desirable instances from factory using the code below.

Output:

Action figure without gun created!

Figure is shooting : Punch

figure is shooting 3 times :

Punch

Punch

Punch

Action figure with gun created!

Figure with gun is shooting : Gun is shooting. Left Boolets 2

Figure with gun is shooting 3 times: Gun is shooting. Left Boolets 1

Gun is shooting. Left Boolets 0

Gun is empty!

Figure with gun is shooting : Gun is empty!

Figure with gun reloads gun: Figure with a gun is shooting: Gun is shooting. Left Boolets 2

Conclusion

To sum up, factory is a design pattern easy in use and simplifies the code’s complexity a lot. Using “new” operator is definitely a bad approach and we have to avoid using it. Factory helps to write a more clear code with less bugs.

You can download the source code from GitHub.

Android, Game Developer, Game Development, Java, LibGDX, OOP, Programming

LibGDX: AssetManager

Assets are one of the most significant and demanding things in a game. Images, music, sounds, fonts, skins are only some of the reasons that a game may respond slow and have bad behavior if they are not set up correctly.

It is acceptable to have a small delay while the assets are loading before the game starts, but from the time that the game has started, we do not want to have a lag or a delay. If so, then we face the danger of losing our users because the game becomes frustrating to them.

So, we must be very careful on how to handle our assets in our game. It’s not the only thing that we have to take into account when we develop a game but it’s sure a very important one.

It is a heavy process creating new objects at run-time, so, if we need to create new assets and dispose of some others then we face the danger of having lags or our game freezing.

We have to be very careful when we use the keyword “new” at run-time. For example, the LibGDX framework loads an image with the code below

Creating new objects is costly and has negative consequences in run-time gaming. Generally speaking, it is a good habit to evade having big constructors, synchronization calls during object construction. Instead, we can use Weak References.

Also, there are some design patterns like object pooling and prototype which we can use in order to avoid using new” keyword so as to generate new instances. You can take a look at these design patterns here and here.

Back to our subject, LibGDX provides us with the right tools to handle and use assets as efficiently as possible.

One of these tools (class) is AssetManager. It’s only a very useful class that helps us handle our assets. Every single one of the assets is loaded in memory once and we can use them as many times as we want.

It’s the best way to handle images, music, sounds, and more. Also, you can read why and how to use AssetManager in LibGDX documentation.

  • Loading of most resources is done asynchronously, so you can display a reactive loading screen while things load.
  • Assets are reference counted. If two assets A and B both depend on another asset C, C won’t be disposed of until A and B have been disposed of. This also means that if you load an asset multiple times, it will actually be shared and only take up memory once!
  • A single place to store all your assets.
  • Allows to transparently implement things like caches.

AssetManager usage is simple enough.

The first line makes a new object of AssetManager. The second line puts the image myImage.png which is a texture in the queue.

From the time we call finishLoading(), we start the loading process of the assets. The whole program is blocked until all assets are loaded.

Caveat. Method manager.load(“…”); doesn’t load any asset, instead, it puts every asset in the queue and when we call finishLoading(), it starts loading the assets.

Method get() returns an asset and we use casting in order to set image variable with an image from the manager.

Attention! Don’t use AssetManager as static.

According to the documentation, it is bad practice to use AssetManager as static due to the different lifecycles of a static and Android Activity. This approach may lead to bugs and memory leaks.

There are two ways to load assets using AssetManager. We have already seen the first using finishLoading() function. The second is update() method. Using this function we have a better control when assets are loading. We can use it with the function getProgress() which returns a percentage of loading.

Take a look in the next example of code

It is worth noting that we don’t need to use dispose() in each Texture or any asset AssetManager handles. The code is more elegant and we don’t need to write too many lines so as to dispose of each asset individually.

This whole process is very useful and a big improvement during code execution. It’s a big improvement when we have to create new instances of an asset in run-time.

Drawing With AssetManager

Continuing, we will see how we can use AssetManager with a good structure. Also, we will draw some images on our screen.

Starting with class Assets and we will declare the images paths.

AssetDescriptors

We can use get(“asset name”) method in order to get the asset and use it. It’s not the best practice, in case we want to change an asset with another one. Then we have to change each one point that we have already declared.

Another reason is when we just have a single string in get() we cannot be aware of what type of asset the get() is going to return.

So, LibGDX offers AssetDescriptor which handles situations like that.

LibGDX API Class AssetDescriptor<T> describes an asset to be loaded by its filename, type, and AssetLoaderParameters. Instances of this are used in AssetLoadingTask to load the actual asset.

Now we are ready to create a class named AssetDescriptors and we will declare every asset.

The next step is to create the right code in order to load assets in AssetManager and draw these assets on screen.

At this point, we are only going to see and analyze AssetManager and not the camera.

As we can see in the constructor we create a new instance of AssetManager.

Show() calls loadAssets() function. This function sets assets in a queue and after that, it calls finishLoading() function which blocks everything until all assets are loaded.

After that, we are ready to use all assets that are loaded in AssetManager.

Now we are ready to draw images (our assets) inside render() with the standard way, using batch.

You may have already noticed that in dispose() function we don’t dispose of every asset as we used to.

We just have to dispose of manager and all assets will be disposed of by the manager. Nice!

Using AssetManager with update()

In order to use update() method we have to remove the line below from loadAssets();

and add the code below in show() function after loadAssets() call.

You can find the whole source code in the file AssetManagerUpdateExample.java

AnnotationAssetManager

AnnotationAssetManager is another tool that comes with libgdx-utils library. It is a tool that simplifies the whole situation even more. As you can imagine we will use annotations.

Before we start we have to add the following lines in gradle file in order to download libgdx-utils library.

Now we are ready to go!

We will need one more class named AssetsAnnotation and we will use @Asset() in order to put assets in the queue. So, we don’t need to write the same code twice.

You may have already noticed that loadAssets() function is just 2 lines. We don’t need to load every single asset anymore, we just need to call AssetsAnnotation class.

Outputassetmanager examples

You can read more about AnnotationAssetManager here!

Conclusion

It is suggested to always use AssetManager in order to handle and load assets. In that way, assets are loaded once in memory and we use them as many times as we want.

Assets don’t need to be disposed of one by one. Instead of that, we just dispose the manager.

Also, it’s easy to handle our assets because they are located in one place.

The outcome is a more compact and elegant code and this leads to cleaner code. Also, there are fewer places to hide a bug.

It’s the best solution in case we have to create “new” instances of assets at run-time and not only!

You can find LibGDX examples in GitHub!

creational patterns, Design Patterns, Game Development, Java, Object Pooling, OOP, Programming

Design Patterns : Object Pooling

Object Pooling is a design pattern that belongs to creational design patterns. Creational design patterns are the ones that deal with object creation mechanism. This gives the program more flexibility in deciding which objects need to be created for a given use case.

Design pattern object pooling gives us the ability to load some instances before any object, so we are able to borrow any of the pre-loaded instances from the reusable pool class.

Using the keyword new to create multiple instances of the object every time, is costly. This cost is related to the time a new instance needs to be created.

The fact that we are able to borrow some instances of an object and return them back to the pool when we don’t need them is very useful.

Object pooling is usually used in games. For instance, in our game, there are some characters who have a gun and shoot. Every time that we use the keyword new to create a new bullet our game is becoming slower and doesn’t work as we would expect.

So, in this case, it is not only the right decision to use object pooling, but it’s mandatory.

Also, it’s a good practice to use it in our characters and some other points of our game.

Now we are ready to see a simple example of object pooling usage.

Using Object Pooling

Our game is simple, the user has to connect the dots so as to make something known to us, like an elephant, a man, flowers e.t.c.

The game is going to have a lot of levels, so, that means we will create and destroy dots all the time. So, it is a great chance to use object pooling pattern.

Let’s start with the Dot class.

As you can see this class creates only a dot. The code below creates the dot.

circle = new Ellipse2D.Float(posX, posY, radious * 2, radious * 2);

Additionally, a function named isColliding() checks if this dot intersects with a line.

The next step is to create an abstract Pool class. You can see the code below.

The constructor calls method init(). This method initializes the object with instances of Dot class.
Method addObj() is an abstract function. Also, there are 2 more methods, method size() returns the size of the object and the second removes all of the elements from objects.

DotPool class is extended by an abstract Pool class. Let’s take a look at the code :

Method addObj() adds a new instance in objects.

Method get() returns an instance of Dot if it exists, otherwise, it creates a new one. Also, it is a good practice, if there is not any available instance, to wait to get back one instead of creating a new one.

Method free(Object o) returns an instance to objects.

Last but not least, the Main class.

OUTPUT:

And this is the window that our code produces.

object pooling dot window

As you can see, Pool starts with 2 instances of Dot class. We get one instance and  1 remains in Pool. We get one more instance and we can see that size of the Pool is 0.

In the next step, we release the second instance back to the Pool, and Pool’s size is 1 again.

After that, we ask 2 more instances from Pool, but only one exists. So, Pool will create a new instance.

Now we release all the instances back to the Pool.

As you can see, Pool starts with 2 instances but in the end, it has 3. This has happened because we asked 3 instances and get() function is able to create a new instance if there is not any in Pool.

You can find the code in my GitHub account.

If there is any mistake or you have any questions, please let me know.

If you want to read more about creational patterns and object pooling you can read these books Design Patterns: Elements of Reusable Object-Oriented Software and Game Programming Patterns.

Design Patterns, OOP, Programming, Software Engineering

The OOP Concept

Object-oriented programming (OOP) is a way of writing code based on the concept of objects. Every object has its own arguments and functions.

If there is a need to code with OOP principles then we have to be in a continuous effort trying to describe everything into objects.

Before we continue on to how we have to think when we develop with OOP I would like to give you a very basic intro about some of the principles that we have to follow in order to build better software that is maintainable and easy to improve with new functionalities.

It’s a good practice to separate the code into small blocks of code. Every single block of code must be responsible for one task only. To achieve this goal we can use functions.

A function is a block of code that executes a specific task. We have to keep in mind and not break the rule that a function must execute only one task. This is the way that the complexity of the code will be reduced making the code reusable. Also, these small blocks of code mean fewer places for bugs to hide.

A function should not exceed 25 lines. It’s rare for a function to exceed 25 lines. We don’t need to count each line of function all the time. If a function exceeds the 1/2 of the screen it means that it may perform more than one task. So, we are able to break it in two or more functions.

If we don’t break the rule that a function must perform a single task then it’s almost certain that it will not exceed the top-up limit of 25 lines.

The name of the function is an important fact as well. The name has to describe what the purpose of the function is with one, two, or more words. It such a great help for everyone to understand what a function does without the need to read a whole block of code.

I would like to continue to write about some good practices that everyone has to follow for a better quality of code. Even that, it would not be enough. The best way to learn more about that is by reading the book named Clean Code by Robert Cecil Martin.

Every developer must read this book. Before reading anything else. If you have not read the book then stop what you are doing and go for it. It’s the best book in order to set the right bases for programming.

After this short analysis on how to improve your code quality, this is the right time to talk about OOP. As I said, we have to reduce the feature that we want to build in order to describe it as an object.

In order to do that, we have to think that an object is an entity or a class. Every class contains attributes and functions.

So we have to describe and build those attributes and functions. Every function has to perform only one action of the object. Functions are able to handle these attributes and change them sometimes. Let me give you an example.

Supposing that we want to build a game with people and dogs.

A dog is an entity that has 4 legs. This is an attribute. Also, the dog can execute tasks like barking, walking, or running. These tasks are functions. And each function performs only one of these tasks. Thus, we can make a dog.

Now we want to make a man. A man is an entity again with 2 hands and 2 legs. These are attributes as well. Some of his functions are to walk, run, and talk. As before, each of the tasks that a man can perform is a function in our class.

This way of thinking seems to be easy at first but in case we have a complex problem to solve then the code’s complexity is equally important. Even though, it’s certainly an efficient style of programming to build big applications.

There are many reasons why we want to use OOP.

It’s a really efficient way to build a reusable code. It’s certainly not so easy. We have to follow some rules like the rules that I described before. Alternatively, we will end up with a spaghetti code written in a class.

Another important reason is that developers are able to collaborate with each other more efficiently without so much communication. That means that they don’t need to waste their time describing and analyze the way in which something was built or what is the way that a new feature will be built.

To be successful, we need to use design patterns. Design patterns offer solutions to problems during development. It’s a framework that helps developers solve common problems.

Moreover, design patterns are able to solve communication problems among developers. If design patterns are known among the developer’s team, productivity and effectiveness are increased.

Writing code with design patterns it’s not so easy and requires a lot of practice and study. One of the best books is Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Ralph Johnson, Richard Helm, John Vlissides.

All of the above come true through some principles. These principles are encapsulation, inheritance, and polymorphism. According to this book these principles are :

ENCAPSULATION

The result of hiding a representation and implementation in an object. The representation is not visible and cannot be accessed directly from outside the object. Operations are the only way to access and modify an object’s representation.

In other words :

Encapsulation is the process of combining data and functions into a class. Attributes of the class are kept private and there are public getter and setter methods that are provided to manipulate these attributes. Thus, encapsulation makes the concept of data hiding possible.

INHERITANCE

A relationship that defines one entity in terms of another. Class inheritance defines a new class in terms of one or more parent classes.The new class inherits its interface and implementation from its parents. The new class is called a subclass or (in C++) a derived class. Class inheritance combines interface inheritance and implementation inheritance. Interface inheritance defines a new interface in terms of one or more existing interfaces. Implementation inheritance defines a new implementation in terms of one or more existing implementations.

POLYMORPHISM

The ability to substitute objects of matching interface for one another at run-time.

This was a quick review of what OOP is. It is really an immense subject, and we only just scratched the surface of it.

I will get back to the subject soon with more details when I present design patterns.

PHP, Programming

PHP Thoughts

As a programmer, I have been using PHP for over 4 consecutive years. Sometimes PHP tends to be an unappreciated programming language due to the exaggerated freedom it offers.

That’s the sense I caught on from Anthony Ferrara’s speech on PHP[world] in 2015. It is really an amazing presentation by Anthony Ferrara. You can watch the presentation in the video below.

So, I made the decision to present you with some of the most important parts as far as I am concerned, giving my opinion as well.

Through this presentation you are able to get the concept, to realize and gain a better insight of the PHP.

PHP Does Not Discriminate

I am quite certain that there are many times you are in front of a monitor reading insulting comments about PHP. PHP sucks, is slow, promotes spaghetti code etc.

Anthony Ferrara chose to start his presentation by saying that entire websites are dedicated to what PHP does wrong. Nevertheless, PHP is victorious, he maintains.

In my opinion, the truth is somewhere in between. Maybe the above comments are true but it doesn’t mean that PHP is doing everything wrong.

PHP is a language without a significant difficulty level of curve learning. Not only does PHP give the freedom to everyone to choose what they want to do, but also how they are going to do it. PHP serves everyone, from the most uninitiated programmer to the most senior. PHP doesn’t discriminate.

The fact that 80% of websites are written in PHP confirms Anthony Ferrara’s opinion.

It is appropriate either for small websites or big ones. For example, Facebook is written in PHP.

[section_title align=”center” text=”PHP is Forgiving”]

PHP is so simple that is not mandatory to be aware of how classes work, functions, or even what type of variable a function must return.

It forgives many mistakes by a programmer in opposition to other programming languages. It’s not required to declare a variable prior to use it. Is that right? NO, IT IS NOT.

The entire website is not going to stop working in case there is a little error in code. The functionality just breaks a little bit.

To be honest, PHP is one of the most helpful programming languages for every uninitiated programmer so as to get his first steps without focusing on the quality of his code. Anyway, when someone is at the very beginning is not able to write code with a good structure.

On the other hand, it matters for everyone to learn some things right from the beginning. For example, a variable must be declared before being used.

PHP Bends To Suit You

PHP doesn’t give one and the only way to follow on how to write your code. It just empowers you to do it. You are able to do it in your own way.

You may want to follow the procedural style. Go ahead. You may want to write your code with OOP technics, no problem at all. The functional style is not an exception.

The drawback, in this case, is that even though, you are able to choose the way that you want to work, there are many more languages more strict that allow everyone to do it better and more efficiently than PHP.

I am going to do some lessons for every one of the above programming styles in the future.

The Effect

Its advantage is its drawback at the same time. What sets PHP apart from other languages is also its Achilles’ heel.

It is a fact that there are uncountable tutorials and HOWTOs on almost everything on PHP. You are almost able to build an entire website just by copy-pasting from around the internet with subtle changes.

All the above have the effect of a significantly large number of programmers being at a low level and writing very bad code, without using any good standard. It really turns the code into a gloomy and blur one. It is impossible to be read by anyone who wants to improve or supplement a new feature in the code. Debugging truly becomes a headache.

Actually, reading a piece of this code is a challenge. Undeclared variables bolt out from everywhere, nonsense function names, or even functions that exceed 200 – 300 lines of code. Comments are nonexistent. Ohh!! What a nightmare.

This freedom and lack of restriction don’t urge programmers to write good code, maintainable, extended, and easy for everyone to see a bug and solve it without affecting the rest of functionalities.

That means if you use and develop your code carefully, it is not going to have negative consequences.

It really depends on how a programmer will choose to write his code and if he has the ability to build a correct structure of his code. This is applicable to all languages but more in PHP because it doesn’t offer you a certain way to write your code, But gives you all the tools and freedom to use it however you want.

With great power comes great responsibility.

PHP Driven By Contributors

PHP is driven only by contributors, and as Anthony Ferrara said, there is not any road map on how exactly PHP is going to be developed in the future.

HHVM + PHP

HHVM is an open-source virtual machine designed for executing code written in PHP and Hack. The VM is maintained by Facebook.

This is a positive fact for PHP and a big improvement. HHVM is generally faster than PHP7. Also, it supports full PHP 5 and partially PHP 7.

You can find more details about HHVM here.

A Quick Intro For PHP 7

PHP 7 has a lot of changes from its predecessor. One of the major changes that seem very interesting and essential for me is that the developer has the ability to choose if he wants to declare what type of variable the function is going to return. This feature is offered to you as an optional and not as a compulsory.

And yes, it’s true that PHP 7 is much faster than PHP 5.

Conclusion

To sum up, PHP is a language that provides everyone even the most amateur programmer with the ability to write code and enhance his productivity. Simultaneously its freedom can be turned into something destructive if the developer doesn’t have the experience and wisdom to keep his code into a structural pattern.

Also, PHP 7 has changed and become even better so as to help everyone to build a better code structure.

View More