Software Development

Value Object vs Entity

What is Value Object, what is Entity and why should we care? Let’s take two examples, Currency and Person.

But before we start, let me give you an answer right away. Currency is value object and Person is entity.

Why?

Currency is something that has clear value that does not change easily. For example, Dollar is a currency and his ISO code is USD. It’s always going to be USD and that’s not changing any time soon. When we initiate the new dollar we want to be able to reuse that object all the time from now on in our application, because they should all be the same. We don’t distinguish between each dollar.

On the other hand each person is unique. When we create a new Person object, we have distinguishable properties like, name, age, birth day, picture, etc…

This is the first characteristic of recognizing what should be Value Object and what should be Entity. Value object is object that can be kept immutable.

Next, the object is value object if it’s conceptualy composing related attributes as an integral unit. Since this is a bit complicated definition let’s take an example and continue with currency. Let’s say we have a bank transaction. Each bank transaction has it’s currency.  Transaction is clearly an entity because each transaction is unique with unique id. We can make currency just one more attribute of transaction like this:

class Transaction
{
    protected $id;
   
    protected $senderAccountId;

    protected $recipientAccountId;

    protected $amount;

    protected $currency;
}

We can do this and it would be perfectly OK solution. The problem that we have here is that we will need to validate currency. If we know that objects should be responsible for validating itself, does it feel OK to You to have Transaction object be responsible for validating ISO code of currency? I didn’t think so. Btw, in this example amount should be extracted to a value object – Money. If we do that, Currency should not even be connected to transaction at all. Let’s see concrete example of this:

class Money
{
    protected $amount;
    
    protected $currency;

    public __construct($amount, Currency $currency)
    {
         $this->amount = $amount;
         $this->currency = $currency;
    }
}

class Currency
{
    protected $isoCode;

    public function __construct($isoCode)
    {
        $this->validate($isoCode);
        $this->isoCode = $isoCode;
    }
    
    private function validate($isoCode)
    {
        // if false throw InvalidArgumentException
    }
}

Value objects do behave as basic types in may cases but not in all. If you would do this you would get results that are not the same as if you would use basic types instead.

$currency = new Currency('EUR');
$newCurrency = new Currency('EUR');

echo $currency == $newCurrency; // TRUE
echo $currency === $newCurrency; // FALSE

To avoid this we can just implement a simple equals method that would check if ISO code is equal.

One of the most important characteristic of value object, as we already said, is immutability. The question is how to achieve this?

I will try to explain again with an example. We have money value object with dollar currency and we want to add some money on top of it. We create new money value object with amount we want to add and currency. What would happen if that currency is euro. The request should fail.

class Money
{
    public function add(Money $money)
    {
        if (!$money->getCurrency()->equals($this->currency)) {
            throw new \InvalidArgumentException();
        }
        return new self(
            $money->getAmount() + $this->amount,
            $this->currency
        );
    }
}

This way we can be sure that immutability will be guaranteed. Each time two instances of Money are added, new instance of Money is returned. It will always be free of side-effects which is also one of the most important characteristic of value objects.

When testing value objects we need to take care that we also test immutability and side-effects free behavior. Let’s test our add method in Money class.

class MoneyTest extends TestCase
{
    /** @expectedException \InvalidArgumentException **/
    public function testAddShouldFail()
    {
        $money = new Money(10, new Currency('USD');
        $money->add(new Money(10, new Currency('EUR');
    }

    public function testAddShouldSuccessed()
    {
        $money = new Money(10, new Currency('USD');
        $money->add(new Money(10, new Currency('USD');
        $this->assertEquals(20, $money->getAmount());
    }

}

Using value object is highly recommended as it helps you plan conceptually your application. It’s important part of Domain Driven Design.

If you have questions, leave a comment or hit me up on twitter @housefrommars

​Read More
Software Development

Don’t write good comments, write good code

When a new programmer comes to our team, one of the first questions we are being asked by her or him is how come we have no comments in our code. So we have to tell the same story all over again. If I am personally asked I would give the answer that if you had to comment a function or class, that meant that you had given up on its quality, accepted defeat and then have to use English to describe functionality instead of writing clean and clear code.

Header comments

It is not only the issue about the method or class description comments. I come across a lot of “header comments” as the ones that follow:

/**
* Author: Bobby Newport
* Date Created: 31.12.2017.
* Phone: +49 111 1111 111
* Email bobby.newport@sweetums.com
*
* I created this class while I was in the shower
*/

Every single line here is unnecessary. The information like author and date created is information that we have in our source control. We do not care who created the file ( which we also can see in VSC ) when we can see who wrote each and single line with git blame ( praise ). Phone and e-mail are redundant because what could you do with e- mail and phone of author. You could call them and say their code is bad!? Also I do not care about your personal comments, such as the way you felt when you created some piece of code, whether you were angry or sad if method turned out the way it did or something similar.

I did personal comments in code all the time before. It was my way of therapy. At the time, I thought I needed to unwind in that way because project I was working on contained a lot of bad codes and I gave my contribution to that by writing more bad codes and I was writing personal comments by which I was justifying myself in my own perspective.

I would write comments like these:

/** I hate this function */

/** This function is beyond repair */

/** When I'm done with this class I'm also gonna be done with this career */

/** Just kill me */

I am aware of the fact that I behaved like an idiot. Comments like those do not give any value to the code. Instead of hating my life, I should probably try and fix that part of code that was responsible for my feelings.

Point is not to do this. No-one cares. Do not complain, especially in your code comments. Instead, do something about it and fix it. Those kinds of comments really makes you unprofessional in the eyes of other experienced developers. You do not want that.

Description comments

Description comments are very common. I think (looking at just programming side of things) they are even worse than personal comments. As I said before, when developer needs to use English to describe behavior of code, that means that he had given up on using computer language to do the same. Less experienced developers often do this. They rely on comments to express behavior of source code, instead of using actual code.

There is simple and easy rule you can follow to fix this. If you feel that you need to write comment to describe something, then stop, look at the code and refactor. Refactor until you do not have the need to write a comment anymore. Simple enough.

There is argument for comments. They should be present as a way of documentation of what code suppose to do. Wrong! We do not care what code is supposed to do. We only care what code is actually doing.

There is an argument that comments should be present to explain to future programmer why the old one created that particular function and what his thought process was. Even though this can be controversial, I do not agree that this is necessary. It can sometimes even be counterproductive. Again his thought process should be clear from the code he wrote or at least we can see his source control history. Also to write good comments, you have to be a good writer. It is really not that easy to effectively communicate with your colleagues through comments.

There is an issue that writing and maintaining code is also very expensive. Now you have to worry about changing not only code, but comments as well. Each time you write some new code or have some new idea you have to update the comments. Yeah, that is not going to happen. You will forget eventually to update comment and then you will have misleading description.

This is why I think thought process comments are something you should also avoid.

Docs comments

The only comments I think you should write ( yes, there are good comments ) are not really comments at all in practice, but technically they do belong in this category. I am talking about documentation comments.

/**
* @param Object $object
* @param Clojure $clojure
* @returns array $result
*/

There is nothing wrong with this, especially if you are using language that is not strictly typed, these things help you keep parameters types as well as return types correct.

If your feel your code is too complex to understand without comments, your code is probably just bad
24 Jul 2008 – Coding Horror

What do you think? Do you write comments in your code and why? You can leave a comment here, which is not as bad as leaving comments in code.

​Read More
Software Development

Architectural Styles Explained in PHP

You can decide on many architectural approaches and styles when starting new PHP application. This will be very superficial overview of different architectures, but it will be enough for you to start thinking about different ways you can structure your application. I picked four to talk about. Three will be in this post and the last one “Command Query Responsibility Segregation” deserves its own post.

One of those four you should never use, let us try and guess which one.

Good Ol’ Days

Yes. You guest it. The good old days architecture is that one that should not be used. Nevertheless it should be mentioned here. This is the old way of writing PHP application. People often call this approach as PHP 4 way of coding. That’s too generous. Because this type of coding is more of PHP 3 style.

You see back then, there were no classes in PHP and separation of concerns were alien concepts among the PHP community.

Let’s see one example of application written this way.

<?php
 
$connection = mysql_connect('localhost', 'db_user', 'db_password');
 
if (!$connection) {
    die('Could not connect to database');
}
 
mysql_select_db('db_name', $connection);
 
$errorMessage = null;
 
if (isset($_POST['submit'])) {
    $sql = sprintf(
        "INSERT INTO posts (title, body) VALUES ('%s', '%s')",
        mysql_real_escape_string($_POST['title']),
        mysql_real_escape_string($_POST['body'])
    );
    $result = mysql_query($sql, $connection);
 
    if (!$result) {
        $errorMessage = 'There was an error when we tried saving the post';
    }
}
 
$result = mysql_query("SELECT id, title FROM posts", $connection);
 
?>
 
<html>
<head>Posts</head>
<body>
    <?php if ($errorMessage) : ?>
        <span class="error-msg"><?=$errorMessage; ?></span>
    <?php else: ?>
        <span class="success-msg">Post created successfully</span>
    <?php endif; ?>
<table>
    <tr>
        <th>Title</th>
        <th>Actions</th>
    </tr>
    <?php while ($post = mysql_fetch_assoc($result)) : ?>
        <tr>
            <td><?=$post['title']; ?></td>
            <td>
               <a href="update_post?id=$post['id']">Edit</a>
               <a href="delete_post?id=$post['id']">Delete</a>
            </td>
        </tr>
    <?php endwhile; ?>
</table>

As you can see html and logic is mixed together. We call this “Big Ball Of Mud“.
These days, there are still applications that use this style of coding. One major problem here is also that this uses mysql_real_escape_string to escape parameters, which is proven to be unsafe, so the risk of sql injection is high.

Application like this is the main reason why so many communities look down on PHP and even this is now history. Some developers still use this style of programming when beginning their new projects, which is directly hurting PHP community.

Let’s talk about some newer architecture.

Layered Architecture

This was major improvement because it introduced separation of concerns. As a consequence code became reusable and maintainable.

Rule for layered architecture is that each layer must be tightly coupled with the layers beneath it. What layered architecture tries to solve is problem of mixing different components of an application. To go back to our previous example, blog post view representation should be completely independent of blog post as conceptual entity.

The reason this is good is that blog post as an entity can be visually represented by one or more views, as opposed to being tightly coupled to a specific representation.

We know this type of architecture by more famous title ‘Model-View-Controller Pattern’.

Model manages data and logic for business rules.

Controller job is to organize interactions between other layer and trigger actions on model depending on user inputs and send messages to view in order to refresh the representation.

View has a responsibility to provide visual representation of model and provide a way to trigger changes on Model state.

So now let’s take a look at simple code example extending on our previous code snippet, for this architecture.

// Model

class Post
{
    private $title;
    private $body;
 
    public function __construct($title, $body)
    {
        $this->title = $title;
        $this->body = $body;
    }
 
    public function getTitle()
    {
        return $this->title;
    }
 
    public function getBody()
    {
        return $this->body;
    }
}
 
 
class PostRepository
{
    private $db;
 
    public function __construct()
    {
        $this->db = new mysqli('localhost', 'db_user', 'db_password', 'db_name');
    }
 
    public function save(Post $post)
    {
        try {
            $stmt = $this->db->prepare(
                'INSERT INTO posts (title, body) VALUES (?, ?)'
            );
 
            $stmt->execute([
                $post->getTitle(),
                $post->getBody()
            ]);
        } catch (\Exception $e) {
            throw new CustomException($e);
        }
    }
}

Model is now represented by Post and PostRepository. But we have another Post representation. It’s Post service.

Services are when the real magic happens. Its job is to orchestrate the behavior of Post.

class PostService
{
    public function createPost($title, $body)
    {
        $post = new Post($title, $body);
        $postRepository = new PostRepository();
 
        $postRepository->save($post);
 
        return $post;
     }
}

As you can see Application services are the ones that make things happen.

// Controller

class PostController
{
    public function create(Request $request)
    {
        if (Validator::isValid($request)) {
 
            $postService = new PostService();
            try {
 
                $postService->save(
                    $request->request->get('title'),
                    $request->request->get('body')
                );
 
                $this->showCustomMessage('Post has been created successfully');
            } catch (CustomException $e) {
                $this->showCustomMessage('Post can not be created');
            }
        }
    }
 
    return $this->view('post-view.html');
}

View is presented by some of the template languages. The most popular are Twig, Blade, etc… You can represent it by plain php and html. Recommended way is to use some of the languages for that, but it is not vital.

There are some risks when applying this architecture. You can see that in PostRepository we are directly placing infrastructural details. That is violating Separation of Concerns. How to fix that?

Hexagonal Architecture

Hexagonal Architecture (Ports and Adapters) was defined by Alistar Cockburn in his book Hexagonal Architecture. It depicts application as a hexagon, where each side represents a port one or more adapters. Port is a connector with a pluggable adapter that transforms an outside input to something the inside application can understand, and vice-versa. It can also emit message and transform to whatever outside can understand.

[video_page_section type=”youtube” position=”default” image=”https://housefrommars.com/wp-content/uploads/2017/10/hexagonal.png” btn=”light” heading=”” subheading=”” cta=”” video_width=”1080″ hide_related=”false” hide_logo=”false” hide_controls=”false” hide_title=”false” hide_fullscreen=”false”]https://www.youtube.com/watch?v=K1EJBmwg9EQ[/video_page_section]

This all sounds complicated but let us apply it to our example from before and solve infrastructural details being placed in our model directly and make it more clear that way.

In order to retrieve blog posts from the database, we need a Port in this case that is going to be PostRepository. Remember this is Port because we will need to communicate with outside, in this case it is database.

interface PostRepository
{
    public function byId($id);
    public function add(Post $post);
}

This interface exposes Port that the application will retrieve information about blog posts through. Now we need adapter for this.

class MySqliPostRepository implements PostRepository
{
    private $db;
 
    public function __construct(mysqli $db)
    {
        $this->db = $db;
    }
 
    public function byId($id)
    {
        $stmt = $this->db->prepare("SELECT * FROM posts WHERE id = ?");
 
        $stmt->execute([id]);
 
        return $stmt->fetch();
    }
 
    public function add(Post $post)
    {
        $stmt = $this->db->prepare("INSERT INTO posts (title, body) VALUES (?, ?)");
        $stmt->execute([$post->getTitle(), $post->getBody()]);
    }
}

Now our PostService looks like this.

class PostService
{
    private $postRepository;
 
    public function __construct(PostRepository $postRepository)
    {
        $this->postRepository = $postRepository;
    }
 
    public function create($title, $body)
    {
        $post = new Post($title, $body);
        $this->postRepository->add($post);
    }
}

You can see now that we can easily change database without the need to change our model domain. If we decide, we can create RedisPostRepository and just replace it, if we decide to.

This post is being heavily influenced by Domain Driven Design in PHP which is awesome book. You should definitely check it out here.

​Read More
Software Development

Five basic things developers do wrong when building API

First thing that is important, when making API and what developers often forget, is versioning.

Why is versioning important?

Well, let’s consider this: You have built your application around some API and of course now you are heavily depend on it. Consider that you have your methods that fetches some JSON from path that you have as constant in your code, and other methods that parse that JSON the way you need it. So, what happens when API developers decide that they will change everything and make new version of their API.

If they did their job right, you wouldn’t notice anything. Why? Because they will not change a single thing on version of API you are using.

Let’s say you are fetching some API data from this url:

https://api-provider.com/V1/payments

If they changed anything they don’t mess with this path, but instead make a new version and push breaking changes there. Now url will look something like this:

https://api-provide.com/V2/payments

This way you can still use old API version and you get to decide when to switch to the newer one, only when you make all required changes, so that your application continue to work normally. Always have API versioning included. Even though this is basic thing, I come across APIs that do not have it, on regular basis. Do not do the same mistakes as they did.

API Documentation

This is something that I know a lot of developers do not want to do, but it is part of their job. By not having good documentation, you are undermining all good code you wrote, because no one is going to know how to use your API.

Write documentation with the goal of not get any support tickets or emails. If you ever get ticket or email with some questions that means that you are missing some documentation part and that you should immediately update it and add whatever your customer has just asked you to. Yes, even if that question is something stupid (of course there are stupid questions ). If some question doesn’t belong to any category of your documentation and you do not know in which section to put it, just have FAQ section in your document in which you can put all inputs you get from clients and customers.

Also, by having good documentation you are seen as very competent and professional, and your service that you provide will be more successful and trustworthy.

HTTP Status Codes

This one is a bit controversial, but let us get it out there.

It is wrong to return HTTP Status Code 200 (OK) with error message as a response. HTTP Status codes tell application how to react to request. So if we return code that says that everything went OK, even if we have just had an error, it means that we are not using HTTP the way it is intended to be used.

I know that some of you will say that HTTP status codes have nothing to do with business logic of API and technically request is OK, there were no errors on server or request was not bad. Nevertheless, you should know that HTTP is an application protocol, and HTTP status codes should reflect that. Also this by not using HTTP code as they are intended to be used, you are breaking REST, as 2xx is considered to contain response that have that resource as return object. So if we are not getting resource back and instead we are getting error response, you cannot have 2xx HTTP status code.

Testing Environment

Consider you are doing an integration of your service with some API. Let us say that it is payment system. Therefore you would have to test everything twice before releasing it to the production, because we are dealing with people’s money, so we want to be double sure everything works as intended. There is a big list of all the things that can go wrong, but you have no way to testing that.

Let’s say this there are 4 scenarios for payment result:

  • Payment can be successful
  • Payment can be refused ( for different reasons each of which have unique code and message )
  • Request is bad ( unsupported currency, invalid amount, etc…)
  • Fraud detected on Credit Card

We can test three out of this four scenarios. Our API provider did not prepare fraud detection scenario. We can never get that error message, response is different and different parsing and actions need to be done. Because of this reason, we now have untested integration.

So when you are building an API, always consider to be client friendly and implement test service that will cover all possible scenarios.

In our example that would be simply solvable by having dedicated number of a test card, so we client sends the request for payment with that card, it would respond with fraud detection error.

Consistency

By consistency I mean two things.

First thing is not to mix return types for different API endpoints. I had “pleasure” of integrating system that had authorization using SOAP and the rest was done in JSON. Why would you do that? Would you want somebody to do that to you? No? Then do not do that. Be consistent. It is not a problem to have entire service in SOAP, just have everything in that one.

Second thing you should be consistent is to use property names consistently. Do not have property name api_key (underscore) in one endpoint and apiKey (camel case) in another. Just the other day we had one API use property merchantPassword in one request and then merchantPass in another. That sort of thing just shows that you are being lazy, inconsistent and unprofessional.

Do not be stupid on small things like consistency and lose your reputation as good API provider.

If you disagree with me or have something to add please leave a comment and I will try to respond to anyone that is in the mood to talk.

Also I am writing a book about Legacy Projects so if you want to check that out click here.

​Read More
Software Development

Logging everything

You are gonna make bugs and they are gonna end in production. That is the fact. Now the question is did any of You ever had to read bug report from customer about what they did to produce that bug? Most of the time is a mess isn’t it? You can’t relay on that. You need your own trace of steps of what customer did in order to solve the issue quick. Hence we introduced logging.

​Read More
Software Development

Don’t overthink, Ship!

I hate my code. It’s true. I never wrote a single line of code that I liked the day after. You could ask a question that if I hate my code so much, how do I have the nerves to release anything to the world? And that’s the thing. I don’t overthink. Because if developers would overthink in general, nothing would be pushed to the production.

​Read More
Software Development

Making your first Test

So You decided that it’s time to start doing TDD. Everyone is talking about it, everyone is recommending it. But now the difficult part comes in. You have a task to make a website. How to write your first test?

​Read More
Software Development

Why start with Test Driven Development

If You are anything like me, the most difficult part of some process is the start. When I want to do something for the first time, I always have difficulties beginning, and because of that a lot of my side-projects I had never started doing. So the technique to fight against that is to start from bare minimum and build on that, step by step.

​Read More