Design Patterns

Design Patterns, Flyweight, Java, OOP, structural design patterns

Design Patterns: Flyweight

In this article, we are going to delve into another Structural Pattern and it is called Flyweight. Let’s start with the definition from Gang of Four Book.

[quote name=”GoF”]Facilitates the reuse of many fine-grained objects, making the utilization of large numbers of objects more efficient.[/quote]

Flyweight pattern is used to reduce the number of objects that are created. So, memory usage is decreased as well. Apart from that, a new keyword is not needed in order to create the same object again and again.

Every time that an object is created, it is stored, and if the same object is asked, then Flyweight gives it back to you. Otherwise, a new object is created and stored for future usage.

This pattern uses intrinsic and extrinsic properties.

What are intrinsic and extrinsic properties

Intrinsic properties help us make the object unique, whereas extrinsic properties are set by the client to perform a specific operation.

When do we have to use Flyweight Pattern

In case that we need to create many objects that are very similar and these objects cost a lot to be generated, it is a very good opportunity to reduce memory and increase performance by using the Flyweight Pattern.

Example

Let’s suppose that we are making a platform game. The star of the game has to kill all the enemies. Enemies are generated at the run time and they are very similar.

Using the new keyword in order to create a new enemy at the run time is too expensive. Our game is going to lack in memory and become slow if we are not careful.

It is time to create some enemies with the Flyweight design pattern.

We start with the Enemy interface.

The Next class implements the Enemy interface.

Let’s create different types of weapons.

It is time to create a Factory class. This class returns an existing enemy if an enemy of a given type exists. Otherwise, it creates a new enemy, stores it in hashTable for future usage, and returns it.

Let’s run an example.

Output:

You can download the source code from GitHub.

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.

composite, Design Patterns, Java, OOP, structural design patterns

Design Patterns: Composite

The Composite is another design pattern that belongs to the Structural Patterns family. We use this pattern when we want to group components inside a larger component. In other words, we can build a hierarchy of objects.

A definition by GoF:
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

A basic structure of Composite pattern:
Component

  • Declares an interface for objects in the composition.
  • Implements the default behavior for the interface common to all classes.

Leaf

  • It implements the behavior for objects in the composition.

Composite

  • It stores child components and defines the behavior for components having children.

Client

  • Manipulates objects in composition through the Component interface.

Structure

A composite pattern is made easily. We just create an interface or abstract class which is going to contain all methods for “Composite” and “Leaf” classes. Then, we just need to implement our classes which are going to contain some operations of Component.

When we use Component Pattern

We use it when we want to represent hierarchies of objects.

Example

Let’s get an example with a real hierarchy. We are going to represent the pride of lions. It is a perfect example that we can see how the hierarchy works.

So, we have an interface “Panthera” and three classes that are going to implement the Panthera interface. These classes are going to implement only some operations of the Panthera interface each time.
MaleLion and FemaleLion classes are “composite” and have children in their hierarchy.

CubLion class is a “Leaf” class because it implements only the behavior for objects in composition and it doesn’t have children objects.

Let’s start with the Panthera interface.

MaleLion FemaleLion and CubLion classes are following.

Now we are ready to build our first pride of lions.

Output:

You can download the source code from GitHub.

Decorator, Design Patterns, Java, OOP, structural patterns

Design Patterns: Decorator

Hi guys, one more design pattern, and today I am going to continue with a Structural Pattern. In particular, I will introduce you to the Decorator design pattern. Sometimes this pattern is also known as Wrapper.

A decorator is a pattern that adds new features to an existing object without altering anything from the original object.

When do you have to use a Decorator?

  1. When we want to add functionalities in an object but not to an entire class dynamically and transparently.
  2. When we want to add functionalities that are not common to every object.
  3. When it doesn’t need to extend from a class because we don’t want to inherit a bunch of useless methods.

How to use it

Maybe the first way that comes to everyone’s mind in order to add new functions is through inheritance. The truth is that it is not the best option because you inherit a whole class that maybe you don’t need. You cannot control very well how and when you need a decorator.

A decorator offers a better solution to this problem. It gives us the ability to enclose an object that we want to add more functionalities to, to another object which is going to append the desire features. The decorator conforms to the interface of the object that we want to enhance.

Why the Decorator Pattern?

I have already given you some very important reasons why you have to use this pattern and how. There is one more thing. This pattern is an excellent example of the open/closed principle.

The open/closed principle says an object must be open for extensions but closed for modifications.

Example

It is time to get an example. I am going to create a sword, it is a common word and I want to decorate this sword with some magical powers. So, I am going to transform a common sword to an Excalibur sword.

I start with an interface named Sword.

Let’s implement this interface.

If we run this code and call the attributes() method we get the following output.

Now let’s try to decorate this object with new features and giving it the magical power. I start with an abstract class named SwordDecorator that implements the Sword interface.

As you can see this abstract class not only implements the Sword but has-a sword so as to append new actions in the desire object.
Let’s continue with ExcaliburSword that extends SwordDecorator.

So, this class takes as an argument a common sword and transforms it into an Excalibur sword by adding a magical power which is to blind its enemies and its power is increased from 1 which is a common sword to 10!

Let’s run this code

Output:

You can download the source code from GitHub.

Other useful resources:

code.tutsplus.com

behavioral pattern, Design Patterns, Java, template method

Design Patterns: Template Method

Hi guys, I am going to continue with behavioral design patterns and today I will introduce you to the Template Method pattern.

Template Method pattern provides a template method that defines a set of steps (it calls other methods) and the implementation of steps (methods) can be formed in sub-classes if a step has varied implementations. If not, then it’s a good practice to implement this step in the superclass.

According to Gang Of Four Book :

Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm structure.

As you can imagine, in order to create a template method pattern, an abstract class is mandatory. We can use an abstract class in order to create the template method with the steps, we can create steps if they are stable and also create abstract methods for steps that are changing depending on circumstances.

Why the Template Method Pattern?

  • When there is an algorithm with steps that may vary.
  •  Because we can avoid duplicate code and we can use inheritance through a subclass in order to use the same code.
  •  We can create a skeleton of an algorithm that helps us to simplify the complexity.

It is very easy to create a template design pattern, so, it would be better to continue with an example.

EXAMPLE

Let’s start with a simple example. We have some users who have access to a platform to fill out a test. After test completion, we extract some scores. So, we have to create a system that computes the score in two different scenarios.

At first, we will create an abstract class named Scoring with 3 methods. The first one is always a standard method “computeScore()” that returns the sum of the 2 other methods. The computation1() and computation2() methods are abstract and we are going to implement two different scenarios.

Let’s continue with the first scenario. We create a class Scenario1 which is a subclass of the Scoring abstract class.

Continuing with the second scenario and Scenario2 class.

As you can see, we have two totally different implementations of computation1() & computation2() methods in our classes. These computation approaches do not have an impact in real life, I just wrote the first thing that came to my mind.

Now we are ready to call these 2 classes.

Output:
The score from scenario 1 is: 70.0%
The score from scenario 2 is: 38.0%

Caveat: As you can see, we have an abstract class, and we extend this class in order to implement some methods. We are able to use another abstract class which is going to extend the first abstract class and so on.

When you catch yourself to act like that then STOP immediately or be careful. Do not use more than two abstract classes. In my opinion, do not use more than one abstract class because you are going to lose instead of gaining something from inheritance.

The reason is simple. The code becomes hard for debugging, you add more complexity and complexity is never good, difficult to maintain the code, and even more difficult to add new functionalities. Also, it’s a good practice to restrict the usage of this pattern because it doesn’t fit very well with the open/closed principle.

Also, you can read this article so as to get a better insight into why the Template Method pattern is a bad practice.

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.

creational patterns, Design Patterns, Game Development, Java, OOP, Software Engineering

Design Patterns: Prototype

The prototype is a design pattern that belongs in the “creational patterns” category. This pattern is used in order to avoid the usage of “new” operator, especially in the case there is a need to create new objects at run-time.

So, there is the possibility to clone an object instead of using the “new” operator in order to get a new object. This new object is very different from the initial object, but the new one keeps the state of the old object.

To be more precise, before cloning an object, we have to create one. That means we have to get an instance of the class using the new operator as it’s already known. Continuing, we are ready to get more instances of the object just by cloning it.

In order to clone an object, the object must always do implements Cloneable interface.

The advantage of using cloning is less costly than creating a new one with a “new” operator.

Also, an object which is Cloneable is able to be cloned every time during code execution. Usage of Cloneable is suggested on this occasion and can improve the execution time.

Equally important and useful is when a class consists of more than one state. So, it’s preferable to create instances for every single state and clone each one of them instead of using the “new” operator.

Continuing, we will see an example of using a prototype design pattern. You can download the source code from GitHub.

Prototype Example

We will use the same example that we used in Object Pooling design pattern.

So, we will have a class that it’s going to create a dot.

This class is named DotPrototype and implements Cloneable Interface as I said earlier.

You can see the source code of DotPrototype below.

As you can see this class takes only two arguments which depict a dot. Also, it accepts the dot’s color.

At the end of the class, there is a function named clone() which gets overridden.

This function calls parent function clone() returning a new instance of an object. In case that class doesn’t implement Cloneable interface then we get an exception message.

The next step is to create another class and we will implement all states of the DotPrototype class there. And we will put these states in a Hashtable in order to get one, easily and fast.

We are going to create 3 instances of DotPrototype and each one will have a different color. So, Hashtable is going to keep 3 instances, red dot, yellow and green dot.

Source code of DotSpawner

After that, we have to initialize DotSpawner class giving the command below.

DotSpawner is a static class.

We are almost ready, the last thing that we have to do is to call getDot(“Color that we have instantiated”) to get the desired instance and call clone().

So, we get a new different object but with the same state.

Output : 

prototype design pattern

Conclusion

In order to use the clone method, the class must implement Cloneable interface.

It’s useful to use a prototype pattern when there is a need to create new instances of an object during execution time. Also, when a class has many states to implement.

Using clone is faster than using the “new” operator.

Last but not least, you can see the resources below that I found very useful.

gameprogrammingpatterns.com

sourcemaking.com

oodesign.com

wikipedia.org

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.

View More