<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Daniel</title>
    <description>The latest articles on DEV Community by Daniel (@danielbenzie).</description>
    <link>https://dev.to/danielbenzie</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F147463%2F5b5b56dd-b022-4b40-b66a-214f416cd16e.jpeg</url>
      <title>DEV Community: Daniel</title>
      <link>https://dev.to/danielbenzie</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/danielbenzie"/>
    <language>en</language>
    <item>
      <title>Handling Account Balances in Financial Applications</title>
      <dc:creator>Daniel</dc:creator>
      <pubDate>Thu, 27 Oct 2022 18:50:15 +0000</pubDate>
      <link>https://dev.to/danielbenzie/handling-account-balances-in-financial-applications-2f1o</link>
      <guid>https://dev.to/danielbenzie/handling-account-balances-in-financial-applications-2f1o</guid>
      <description>&lt;p&gt;&lt;em&gt;In software engineering, correctness is defined as an application behaving as intended for its expected use cases. Correctness is always important but never more so than when dealing with accounting data. I have been lucky enough to build software that has processed millions of pounds in payments, and these are some of the patterns &amp;amp; principles applied used to calculate and track account balances.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;When building financial software, one of the tasks you undertake will be modelling how to calculate and store balances. An initial approach might include an attribute on an Account model, updated when a transaction occurs. Similar to the below:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The above is not a good solution because it breaks data normalisation. The balance of an account should equal the sum of transactions. Storing the calculated value (as the source of truth) will cause issues if the calculation becomes out of sync, and this will happen in an environment with lots of concurrent requests.&lt;/p&gt;

&lt;p&gt;Race conditions occur when a system attempts to perform two or more operations simultaneously. In our case, we have a Read-Modify-Write race condition. This happens when two processes read a value and write back a new value. If you imagine multiple processes executing this, you should be able to see we have a race condition.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;When we run the above code concurrently, you will see the potential for the processes to read the account balance simultaneously; therefore, once the execution finishes, the account_balance will be incorrect.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Executor A reads account balance = £100&lt;/li&gt;
&lt;li&gt;Executor B reads account balance = £100&lt;/li&gt;
&lt;li&gt;Executor B adds £50 funds. account_balance = £150&lt;/li&gt;
&lt;li&gt;Executor A adds £50 funds. account_balance = £150&lt;/li&gt;
&lt;li&gt;Executor A saves the account model with attribute account_balance = £150&lt;/li&gt;
&lt;li&gt;Executor B saves the account model with attribute account_balance = £150&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As you can see, with concurrent requests, the order of execution cannot be guaranteed. Executor B read the account’s current balance as 100 before Executor A had added the funds. The result is the account_balance is short by £50. This issue only gets worse as the system scales.&lt;/p&gt;

&lt;p&gt;The first step in solving this problem will be to adjust how we check the current balance of an account. We will need to maintain a transaction log. Every time a credit or debit happens, we will write a record to this log with the details. We sum all transactions from the log for any given account to calculate the current balance.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;&lt;em&gt;This process does have a scaling issue because each time a transaction is added to the log, it increases the compute resources required to calculate the balance. You can alleviate this by implementing a statement system. Where you store the calculated balance at intervals (monthly works). You take the latest stored balance and sum the transactions since, to calculate the current balance.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The above code eradicates the possibility of concurrent requests causing the system to under-calculate the balance of an account at any one time. If we queried during the execution flow, we would have returned the correct balance, and after both requests finish, it will return £200.&lt;/p&gt;

&lt;p&gt;However, it does not solve all of our problems. A classic problem in accounting is preventing overspend. Overspend happens when a request comes into an application to debit an account for funds. The application must first check if funds are available to process the request. Suppose concurrent requests to debit an account enter the system. In that case, we face a familiar situation where both checks may validate and write a debit transaction to the log, causing an overspend.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The overspend problem is applicable as long as there are balance constraints which should cause a debit transaction to be rejected, even if the system should also allow for negative balances (overdrafts).&lt;/em&gt;&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;Account ID has a balance of £100.&lt;/li&gt;
&lt;li&gt;Executor A requests to debit the account for £70.&lt;/li&gt;
&lt;li&gt;Executor B requests to debit the account for £50.&lt;/li&gt;
&lt;li&gt;Executor B checks the balance of the account. The sum of transactions equals £100 credit. It can proceed.&lt;/li&gt;
&lt;li&gt;Executor A checks the balance of the account. The sum of transactions equals £100 credit. It can proceed.&lt;/li&gt;
&lt;li&gt;Executor B writes a debit transaction to the log.&lt;/li&gt;
&lt;li&gt;Executor A writes a debit transaction to the log.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;After the above processes have exited, the account balance may be £-20, allowing an unauthorised overspend on the account despite the explicit check to prevent this. Each goroutine calls svc.CalculateBalance(), but they may complete this check simultaneously (although before writing the transaction log).&lt;/p&gt;

&lt;h2&gt;
  
  
  Solution
&lt;/h2&gt;

&lt;p&gt;There are several layers to solving the above (including constraints at the database level); however, I will discuss one we can implement within the application.&lt;/p&gt;

&lt;h2&gt;
  
  
  Distributed locks
&lt;/h2&gt;

&lt;p&gt;A distributed lock will ensure only one goroutine at a time can access a resource (like a mutex but in a distributed environment). We are thoughtful about where we place the lock to guarantee only a single transaction is processed (per account) at any time.&lt;/p&gt;

&lt;p&gt;One way to get and hold a distributed lock is via Redis — the example below.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;In the code above, we first define a key. We can use this key whenever we wish to limit an aspect of our account execution flow to a simultaneous execution. Once the key is defined, we attempt to acquire a lock on it. If another goroutine already has the lock, we will wait for the specified duration (whilst continually retrying to acquire it).&lt;/p&gt;

&lt;p&gt;Limiting the scope of our lock key by injecting the account ID ensures we maintain good throughput across the system. If, for example, we had used a generic lock key like ‘account-transaction’, we would only be able to process a single withdrawal at any time for ALL accounts.&lt;/p&gt;

&lt;p&gt;Once we have acquired the lock, we can safely continue with the withdrawal request because no other goroutine can access funds in the account.&lt;/p&gt;

&lt;p&gt;We have also deferred the lock’s release to guarantee it is released, even in the event of an application error in our function. There is also a timeout set on the lock, ensuring that even if our node was killed (and could not execute the defer function), we will still release the lock after a set amount of time.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Distributed locks are only a single aspect of the controls you need when designing a system that calculates balances. Still, by implementing the above, you will be developing safer, more scalable software.&lt;/p&gt;

&lt;p&gt;As all of the example code was executed in a single process, I could have used a Mutex; however this will not work in distributed applications.&lt;/p&gt;

</description>
      <category>go</category>
      <category>distributedsystems</category>
      <category>fintech</category>
    </item>
    <item>
      <title>Validation and the Single Responsibility Principle in Object Orientated Programming</title>
      <dc:creator>Daniel</dc:creator>
      <pubDate>Tue, 10 May 2022 16:08:43 +0000</pubDate>
      <link>https://dev.to/danielbenzie/validating-objects-and-the-single-responsibility-principle-in-oop-1j4a</link>
      <guid>https://dev.to/danielbenzie/validating-objects-and-the-single-responsibility-principle-in-oop-1j4a</guid>
      <description>&lt;p&gt;When writing software, you will spend a large portion of time creating code that takes an object, validates it and then performs some actions. One of the core tenets of SOLID code is the Single Responsibility Principle, and this means there should be a separation of the code that validates the object and the code that executes the action.&lt;/p&gt;

&lt;p&gt;An example scenario might be: &lt;em&gt;User A submits payment of £100 to User B.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;On the surface, this seems very simple and can be implemented using the following logic. &lt;em&gt;&lt;em&gt;The examples in this post will be PHP but apply to any object-orientated language&lt;/em&gt;&lt;/em&gt;&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;We use a &lt;strong&gt;PaymentManager&lt;/strong&gt; to transfer the requested funds between two users from the above code. In this scenario, the &lt;strong&gt;PaymentRequest&lt;/strong&gt; object holds the information about the origin/destination and funds sent.&lt;/p&gt;

&lt;p&gt;Whilst this meets the criteria of moving the funds, there are checks that the system needs to conduct before executing such a request in the real world. Some of the checks could include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Is the origin account active?&lt;/li&gt;
&lt;li&gt;Is the destination account active?&lt;/li&gt;
&lt;li&gt;Does the origin account have available funds to cover the payment amount?&lt;/li&gt;
&lt;li&gt;Is the PaymentRequest amount valid? e.g. it is not logical to pay an amount of zero (or less)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The criteria listed are crucial to the application, and as a result, it may be tempting to conduct these checks similar to the below:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;This code works, but it violates SRP as the function is now validating the request and calling the payment manager. As the business requirements get more complex, this class will continue to grow and become difficult to maintain. &lt;/p&gt;

&lt;p&gt;For example - functionality has been added to the platform, enabling users to block one another. As a result, a user should not be able to send funds to a user who has blocked them. This would require an additional, conditional statement to be added to the function.&lt;/p&gt;

&lt;h2&gt;
  
  
  Validation Classes
&lt;/h2&gt;

&lt;p&gt;A much better way of handling this scenario is to abstract the validation logic away from the execution. This can be achieved by implementing the below:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The validation logic has been extracted to its own class. This separates the code nicely and ensures we will not be forced to update this class every time rules are changed or added. It also has the benefit of making our unit tests much easier to write. To test the &lt;strong&gt;MakePaymentJob&lt;/strong&gt; we can mock the &lt;strong&gt;validate()&lt;/strong&gt; method as true or false and test whether our &lt;strong&gt;paymentManager-&amp;gt;makePayment()&lt;/strong&gt; is called.&lt;/p&gt;

&lt;p&gt;The validation class itself functions as below:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;In addition to extracting the rules to a validation class, I moved each rule to a private method. The descriptive naming of the method provides better context and improves readability whilst creating an excellent base for writing unit tests. I wrote a post about how we might test code like this previously - you can check it out &lt;a href="https://danielbenzie.com/how-to-write-more-testable-code-d08e434b93d2" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Improvements
&lt;/h2&gt;

&lt;p&gt;The validation pattern above is vastly improved over the original code; however, it could still do with a few adjustments. For example, returning false from a failed validation attempt provides no context for the calling client why the request failed. If the paymentRequest failed because the user did not have enough funds, this is something we would want to communicate to the user.&lt;/p&gt;

&lt;p&gt;We can achieve this by making minor adjustments to the PaymentValidator class.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The above is a crude demonstration - when running validations across a codebase it would be better to create validation methods for common assertions. In the example above it is a simple greater than conditional. There could easily be an agnostic method in a validation namespace to handle standard rules. Classes wishing to implement rules can then inject the required rules.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;There are plenty of ways to handle the actual validation of the objects, but the important part is to ensure this logic is separate. It will make extending the rules much easier in the future and increase the testability of your code.&lt;/p&gt;

</description>
      <category>solid</category>
      <category>testing</category>
      <category>oop</category>
      <category>php</category>
    </item>
    <item>
      <title>Solutions for storing state in a database</title>
      <dc:creator>Daniel</dc:creator>
      <pubDate>Tue, 19 Apr 2022 16:08:55 +0000</pubDate>
      <link>https://dev.to/danielbenzie/solutions-for-storing-state-in-a-database-4n5i</link>
      <guid>https://dev.to/danielbenzie/solutions-for-storing-state-in-a-database-4n5i</guid>
      <description>&lt;p&gt;When designing an application, you will often need to model 'state'. State, in this sense, is related directly to a single entity. An example may be:&lt;/p&gt;

&lt;p&gt;I have an order, and the possible status' of the order can be:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Pending&lt;/li&gt;
&lt;li&gt;Paid&lt;/li&gt;
&lt;li&gt;Dispatched&lt;/li&gt;
&lt;li&gt;Delivered&lt;/li&gt;
&lt;li&gt;Cancelled&lt;/li&gt;
&lt;li&gt;Refunded&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The order may only be associated with a single state at any time. It would not make logical sense for an order to both be &lt;strong&gt;&lt;em&gt;delivered&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;returned&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Transitioning between these states will drive the behaviour of your service. For example, when an order transitions to &lt;strong&gt;&lt;em&gt;dispatched&lt;/em&gt;&lt;/strong&gt;, it is an ideal time to notify the customer of the delivery tracking details.&lt;/p&gt;

&lt;p&gt;When modelling this type of solution, engineers are often tempted by the simplicity of having a single column on the original entities table to describe the current state. This can be achieved in a few different ways.&lt;/p&gt;




&lt;h2&gt;
  
  
  First Solution (and the worst)
&lt;/h2&gt;

&lt;p&gt;As we just discussed, the easiest solution is to add a column to the Orders table. This column can store the current state of order.&lt;/p&gt;

&lt;p&gt;It can be achieved by storing the state as a string:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE `orders` (
 `id` INT unsigned NOT NULL AUTO_INCREMENT,
 `customer_id` INT unsigned NOT NULL,
 `order_value` INT NOT NULL,
 `state` VARCHAR NOT NULL,
 `created_at` DATE NOT NULL,
 `updated_at` DATE NOT NULL,
 PRIMARY KEY (`id`)
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This isn't good for a lot of reasons. The most obvious one is that the application can submit any string to the state column, even one that has not been designed for in the application. This can break the application and cause problems for the service.&lt;/p&gt;

&lt;p&gt;We could solve that issue by making the state column an enum and only allowing expected values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ALTER TABLE orders ADD state enum('pending','paid',...);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is still a bad solution.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We have to run an ALTER on the table every time we wish to add new states.&lt;/li&gt;
&lt;li&gt;We cannot store additional metadata about the state as we are limited to a single column with a specific string stored.&lt;/li&gt;
&lt;li&gt;It can be challenging to disable values. What if the store is no longer offering refunds?&lt;/li&gt;
&lt;li&gt;ENUM datatype is not standard SQL and is not supported by many ORM.&lt;/li&gt;
&lt;li&gt;It is complicated if we wish to output the list of possible values for state in our application.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Slightly Better Solution
&lt;/h2&gt;

&lt;p&gt;It is clear from the previous approaches that having a single column denoting the state is not ideal. The next logical solution we could design is creating an order states table and referencing it from the orders table via a foreign key.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE `order_states` (
 `id` INT NOT NULL AUTO_INCREMENT,
 `key_name` VARCHAR NOT NULL,
 `created_at` DATE NOT NULL,
 `updated_at` DATE NOT NULL,
 PRIMARY KEY (`id`)
);
INSERT INTO order_states (key_name)
  VALUES('pending', 'paid',...);
ALTER TABLE orders 
ADD CONSTRAINT FK_OrderState 
FOREIGN KEY(state_id)
REFERENCES id(order_states);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This solves some of the previous issues. There is no need to run ALTER on the table when adding new states, and any additional metadata that needs to be stored against the state can be added as a new column in the order_states table. If a state needs to be disabled/removed, it is easy to select orders by state_id, and we also get the protection of valid states via foreign key constraints.&lt;/p&gt;

&lt;h2&gt;
  
  
  Best Solution
&lt;/h2&gt;

&lt;p&gt;The solution we just implemented has solved most of our problems but we have issues with the visibility of an entities state over time. Because the order is assigned a state via a single FK reference it means we only have information about the current state of the order. If the order is currently in a state of &lt;strong&gt;&lt;em&gt;Cancelled&lt;/em&gt;&lt;/strong&gt; there is no easy way for me to tell when it was &lt;strong&gt;&lt;em&gt;Paid&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;We can solve this by adding another pivot table.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE `order_state_history` (
 `id` INT NOT NULL AUTO_INCREMENT,
 `order_id` INT unsigned NOT NULL,
 `order_state_id` INT NOT NULL,
 PRIMARY KEY (`id`)
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In addition to creating this table we will remove the state_id column from the Orders table.&lt;/p&gt;

&lt;p&gt;This pivot table works as follows: Any time you wish to change the state of an order you &lt;strong&gt;INSERT&lt;/strong&gt; a new record into this table. You never need to &lt;strong&gt;UPDATE&lt;/strong&gt; any rows here. You will also likely never need to &lt;strong&gt;DELETE&lt;/strong&gt; any rows (unless you are purging records).&lt;/p&gt;

&lt;p&gt;The current state of an order is the most recent record in this table (associated with the &lt;em&gt;order_id&lt;/em&gt;)&lt;/p&gt;

&lt;p&gt;You can get the order with its latest state by using the query below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT orders.*, order_state_history.*
FROM orders O
JOIN order_state_history OSH1 ON (O.id = OSH1.order_id)
LEFT OUTER JOIN order_state_history OSH2 ON (O.id = OSH2.order_id AND (OSH1.created_at &amp;lt; OSH2.created_at OR (OSH1.created_at = OSH2.created_at AND OSH1.id &amp;lt; OSH2.id)))
WHERE OSH2.id IS NULL;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Drawbacks&lt;/strong&gt;&lt;br&gt;
It would not be objective if I did not at least point out some of the drawbacks of the above solution.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Additional pivot table required linking Order to State&lt;/li&gt;
&lt;li&gt;Selecting data from Orders requires a more complex query (including JOINs)&lt;/li&gt;
&lt;li&gt;You will end up having to store additional rows for each order. Worst case is Orders * count(possible_state_values)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;The last solution discussed is more robust because it is &lt;strong&gt;INSERT&lt;/strong&gt; only. We do not need to worry about race conditions. &lt;/p&gt;

&lt;p&gt;If we receive a stream of updates, we simply write each record in the order we receive it. It also ensures we have a complete historical record of an order and the states it held.&lt;/p&gt;

&lt;p&gt;This makes it trivial to look at the data set and ask questions like:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How many orders did I dispatch between 1/12/2021 and the 31/12/2022&lt;/li&gt;
&lt;li&gt;What was the total value of orders refunded during August&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These questions would have been impossible to answer with the other solutions because we did not retain the history of state movements - only the current one.&lt;/p&gt;

&lt;p&gt;The additional code to be written is minimal, and any performance hit from using JOINs is trivial when using proper indexing.&lt;/p&gt;

&lt;p&gt;Any concerns about the additional data stored can easily be rectified by running a simple query to remove unneeded state history items. In pseudocode terms - &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Delete all order_state_history items IF created_at &amp;gt; 1 year ago AND&lt;/li&gt;
&lt;li&gt;order_state_history_id &amp;lt; MAX order_state_history_id for any given record&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Running a query like this would remove historical items (more than one-year-old) but retain the latest state for each Order (as this will remain important)&lt;/p&gt;

&lt;p&gt;In conclusion, it is a much better and more complete way of managing the state in your application and should be utilised where plausible.&lt;/p&gt;

</description>
      <category>database</category>
      <category>mysql</category>
      <category>state</category>
      <category>architecture</category>
    </item>
    <item>
      <title>How to build high-performance engineering teams</title>
      <dc:creator>Daniel</dc:creator>
      <pubDate>Thu, 20 Jan 2022 14:26:08 +0000</pubDate>
      <link>https://dev.to/danielbenzie/how-to-build-high-performance-engineering-teams-3m13</link>
      <guid>https://dev.to/danielbenzie/how-to-build-high-performance-engineering-teams-3m13</guid>
      <description>&lt;p&gt;When building a tech business, one of the keys to success will be a great engineering team. After all, they are responsible for making the product. Teams that ideate, collaborate and iterate create excellent products.&lt;/p&gt;

&lt;p&gt;It is crucial to create an environment that allows these teams to thrive. Unfortunately, there is no out of the box framework that you can apply, but there are some basic principles that you can follow to help along the way.&lt;/p&gt;

&lt;h2&gt;
  
  
  Autonomy and Curiosity 
&lt;/h2&gt;

&lt;p&gt;The best engineering teams are autonomous. They should not be viewed as a resource to ‘be used’, but integrated with the business, so solutions are built together.&lt;/p&gt;

&lt;p&gt;To achieve this, you will need curious people in your engineering team. They will have used the product and be able to pick out pain points. One of the best ways to get engineers into this way of thinking is to have time set aside during onboarding to use the product and view user feedback.&lt;/p&gt;

&lt;p&gt;By empowering engineering teams to take ownership of the product, you get a much better ROI.&lt;/p&gt;

&lt;h2&gt;
  
  
  Delivering value to users
&lt;/h2&gt;

&lt;p&gt;The team should focus on the value delivered to the user, not by building technology and figuring out how to apply it later. The best way to do this is to work from the user backwards. Some companies even use feature voting to let users give technical teams direct feedback.&lt;/p&gt;

&lt;p&gt;Once the value proposition has been established focus should be on making the initial implementation as simple as possible.&lt;/p&gt;

&lt;p&gt;Try to tie feature work to metrics by utilising &lt;a href="https://www.atlassian.com/blog/productivity/how-to-write-smart-goals" rel="noopener noreferrer"&gt;SMART&lt;/a&gt; targets, this has additional benefits beyond the obvious&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It will “gamify” the work&lt;/li&gt;
&lt;li&gt;Engineers will be able to use the ‘measurable’ part to see their impact on the business&lt;/li&gt;
&lt;li&gt;You will begin collecting useful metrics&lt;/li&gt;
&lt;li&gt;You can share these metrics with other areas of the business&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Developer experience
&lt;/h2&gt;

&lt;p&gt;You now have a great team and a backlog full of tickets that will deliver actual value to customers, it is time to execute.&lt;/p&gt;

&lt;p&gt;When iteratively building products, the team will be producing a lot of code in small batches. The development pipeline itself should be as efficient and automated. A &lt;a href="https://www.lambdatest.com/blog/benefits-of-ci-cd/" rel="noopener noreferrer"&gt;great CI/CD pipeline&lt;/a&gt; is essential to this and will help deliver higher quality code at an increased pace.&lt;/p&gt;

&lt;p&gt;Some other things you can look at in your teams to improve the developer experience:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Agree on code style guidelines (and enforce these in your CI/CD suite)&lt;/li&gt;
&lt;li&gt;Project scaffolding&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Good&lt;/strong&gt; Documentation&lt;/li&gt;
&lt;li&gt;Defined processes for pull requests/code reviews&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The development team should maintain a refined backlog of stories to improve the developer experience. They will also be responsible for balancing this work alongside product delivery goals.&lt;/p&gt;

&lt;p&gt;Finally, the team should be tracking key metrics like time to build, time to first commit and time to first release. These metrics will allow the team to measure the changes that genuinely improve the experience.&lt;/p&gt;

&lt;h2&gt;
  
  
  Open collaboration
&lt;/h2&gt;

&lt;p&gt;A good engineering team will have a group of people that are happy giving open and honest feedback and this should happen as often as possible between all members of the team regardless of seniority.&lt;/p&gt;

&lt;p&gt;The teams time will be spent on solving problems (or figuring out which problems to solve) so it is imperative that everybody feels comfortable making suggestions. Ideas should be defended with facts and no one should be interrupted.&lt;/p&gt;

&lt;p&gt;Unfortunately, the team may not always reach a consensus, in this situation, it is important that the decision-maker (usually a tech lead) picks an option. The team then works towards this goal, there should be no vetoing, foot-dragging or hesitation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In summary, every team is a unique blend of personalities and there is no one size fits all approach. Some of the above might work for you and some of it won’t. The important thing is to &lt;strong&gt;measure&lt;/strong&gt; the impact of any changes and iterate.&lt;/p&gt;

</description>
      <category>engineering</category>
      <category>management</category>
      <category>teams</category>
    </item>
    <item>
      <title>Tips for writing highly readable code</title>
      <dc:creator>Daniel</dc:creator>
      <pubDate>Mon, 29 Jul 2019 15:27:01 +0000</pubDate>
      <link>https://dev.to/ddarrko/tips-for-writing-highly-readable-code-dga</link>
      <guid>https://dev.to/ddarrko/tips-for-writing-highly-readable-code-dga</guid>
      <description>&lt;h1&gt;
  
  
  What is readable code
&lt;/h1&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;You are writing for humans. Not the machine.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The above should always be at the forefront of a developers mind when designing a system. Assuming your are writing syntactically correct code that functions the machine could not care less about how it is structured, but the developers who work on it later (and that could still be you) certainly will!&lt;/p&gt;

&lt;p&gt;"Good code" is highly subjective because whats constitutes as such varies from developer to developer, project to project and year to year. That being said there are still common strategies and guidelines we can adhere to make our lives easier in the future.&lt;/p&gt;

&lt;p&gt;I'll go through some more specific examples below but in general:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Follow the project style guidelines (if it doesn't have any, suggest some)&lt;/li&gt;
&lt;li&gt;Write testable code&lt;/li&gt;
&lt;li&gt;Think SOLID&lt;/li&gt;
&lt;li&gt;Use common design patterns (where appropriate)&lt;/li&gt;
&lt;li&gt;Be consistent with file/class naming.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Some examples
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Be descriptive
&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;This example is extremely basic and I expect most people write like this by default.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;First off - be descriptive with your class, method names and variables. Don't have vars called $i or $model.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Becomes&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h3&gt;
  
  
  Abstract (complex) conditionals
&lt;/h3&gt;

&lt;p&gt;Complex conditionals are hard to read and "break the flow" when reading through code. &lt;/p&gt;

&lt;p&gt;Consider the following example:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Becomes&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;I am actually a fan of abstracting conditionals wherever possible. Even if they are relatively simple. They help make your code more testable and by naming your method appropriately you convey the purpose of the conditional in a really nice succinct way.&lt;/p&gt;

&lt;h3&gt;
  
  
  No magic numbers
&lt;/h3&gt;

&lt;p&gt;Magic numbers are hard coded values that implicitly define logic. Not only does it require us to investigate the code-base to see what the value represents it could also change over time. If a magic numbers value changes we will be required to change it in multiple locations which can lead to inconsistencies.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Becomes&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h2&gt;
  
  
  Review
&lt;/h2&gt;

&lt;p&gt;It's easy to over complicate your code but as long as we remember we are writing for humans we can make a much nicer code-base for everyone.&lt;/p&gt;

</description>
      <category>php</category>
      <category>codestyle</category>
      <category>readablecode</category>
    </item>
    <item>
      <title>How to write testable code</title>
      <dc:creator>Daniel</dc:creator>
      <pubDate>Mon, 15 Jul 2019 10:27:53 +0000</pubDate>
      <link>https://dev.to/danielbenzie/how-to-write-more-testable-code-oi7</link>
      <guid>https://dev.to/danielbenzie/how-to-write-more-testable-code-oi7</guid>
      <description>&lt;p&gt;&lt;em&gt;This is something I put together for the engineering team at Howsy. Hopefully it will be of some assistance for others. The examples are in PHP but can be abstracted to any OOP language&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Unit Testing?
&lt;/h2&gt;

&lt;p&gt;It’s simply a test that runs against an individual ‘unit’ or component of software. We are testing the smallest possible implementation of a class/method. A unit test does not rely on any dependencies (other classes/libraries or even the database)&lt;/p&gt;

&lt;p&gt;Read more about unit testing &lt;a href="http://softwaretestingfundamentals.com/unit-testing/" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why is it important?
&lt;/h2&gt;

&lt;p&gt;I mean we could just stick with integration tests right? They are easy to write, however ...&lt;/p&gt;

&lt;p&gt;The goal of any Software Project is to produce a maintainable, extensible codebase which meets business requirements. Writing effective unit tests help us to ensure we are writing SOLID code. &lt;/p&gt;

&lt;p&gt;Read more about solid &lt;a href="https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  How can we write more testable code?
&lt;/h2&gt;

&lt;p&gt;I have taken a very simple class and it is typical of some of the code I have seen over the years.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ToActive&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;transition&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nv"&gt;$accountId&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$account&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$accountId&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;canTransition&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$accountId&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;setState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'active'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;save&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;canTransition&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;Account&lt;/span&gt; &lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;bool&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$validator&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ToActiveValidator&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$validator&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;validate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On the surface the class appears to work. It finds an account from the DB, calls a validation method in another class and returns true/false. Based on the result the Account may or may not be updated.&lt;/p&gt;

&lt;p&gt;Although this class works it is &lt;strong&gt;impossible to unit test&lt;/strong&gt; due to two different dependencies being instantiated rather than injected. The two offending pieces of code are&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nv"&gt;$account&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$accountId&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nv"&gt;$validator&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ToActiveValidator&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As they are in the body of our methods they will be called during unit testing. This will cause us to rely on the responses from other classes in order to run a test. This makes any resulting tests we write for this class not true unit tests.&lt;/p&gt;

&lt;p&gt;We can refactor this class very easily to make it more easily testable and therefore more extensible and loosely coupled.&lt;/p&gt;

&lt;h2&gt;
  
  
  Refactoring
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ToActive&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nv"&gt;$validator&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

   &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;AccountInterface&lt;/span&gt; &lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;StateTransitionValidatorInterface&lt;/span&gt; &lt;span class="nv"&gt;$validator&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
   &lt;span class="p"&gt;{&lt;/span&gt;
       &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;account&lt;/span&gt;   &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
       &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;validator&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$validator&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="p"&gt;}&lt;/span&gt;

   &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;transition&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
   &lt;span class="p"&gt;{&lt;/span&gt;
       &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;validator&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;validate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;account&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
           &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;account&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;setState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'active'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;save&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
       &lt;span class="p"&gt;}&lt;/span&gt;
   &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see from the above we are now injecting dependencies. &lt;/p&gt;

&lt;p&gt;Our class does not care about the concrete implementation of the Account or the Validator - only that they adopt the required interfaces. This again makes our code more loosely coupled. In the future maybe we may completely change the StateTransitionValidator implementation or even add additional validators. Our code is now less tightly coupled and therefore more testable.&lt;/p&gt;

&lt;h2&gt;
  
  
  Now let’s get to testing
&lt;/h2&gt;

&lt;p&gt;Looking at the class we have one public method. We should not be trying to test private methods as they are implementation details. If you find your class has too many private methods or feel that they need testing it is a sure fire sign that your class could do with splitting out into smaller components.&lt;/p&gt;

&lt;p&gt;There are two paths within the public method - the validation passes and we save the entity or the validation does not pass and we don't save it. &lt;/p&gt;

&lt;p&gt;I will write the test assuming the validation passes first. We are going to be mocking our dependencies (something not possible with the original class architecture).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;testToActiveWithPassingValidationShouldTransition&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="cd"&gt;/** @var Mockery\MockInterface|Account $account */&lt;/span&gt;
   &lt;span class="nv"&gt;$account&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Mockery&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;Mock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;class&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;shouldReceive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'setState'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;with&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'active'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;andReturn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;once&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
   &lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;shouldReceive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'save'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;andReturn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;once&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

   &lt;span class="cd"&gt;/** @var Mockery\MockInterface|ToNotActiveValidator $validator */&lt;/span&gt;
   &lt;span class="nv"&gt;$validator&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Mockery&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;mock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ToActiveValidator&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;class&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="nv"&gt;$validator&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;shouldReceive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'validate'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;with&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;andReturn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;once&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

   &lt;span class="nv"&gt;$service&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ToActive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$validator&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="nv"&gt;$service&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;transition&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;testToActiveWithFailingValidationShouldNotTransition&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="cd"&gt;/** @var Mockery\MockInterface|Account $account */&lt;/span&gt;
   &lt;span class="nv"&gt;$account&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Mockery&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;Mock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;class&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;shouldReceive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'setState'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;with&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'active'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;andReturn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;never&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
   &lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;shouldReceive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'save'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;andReturn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;never&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

   &lt;span class="cd"&gt;/** @var Mockery\MockInterface|ToNotActiveValidator $validator */&lt;/span&gt;
   &lt;span class="nv"&gt;$validator&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Mockery&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;mock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ToActiveValidator&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;class&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="nv"&gt;$validator&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;shouldReceive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'validate'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;with&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;andReturn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;once&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

   &lt;span class="nv"&gt;$service&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ToActive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$account&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$validator&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="nv"&gt;$service&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;transition&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Breaking it down
&lt;/h2&gt;

&lt;p&gt;First of all we use &lt;a href="https://github.com/mockery/mockery" rel="noopener noreferrer"&gt;Mockery&lt;/a&gt; to mock our account class. &lt;/p&gt;

&lt;p&gt;We tell our mock that we will call the method setState with an argument of active. We also assert that this function will be called exactly once (this is our actual test assertion)&lt;br&gt;
We also assert that the save() method will be called exactly one time.&lt;/p&gt;

&lt;p&gt;We also mock our concrete validator class. We tell our mock that the validate method shall be called once and that it will always return true. &lt;/p&gt;

&lt;p&gt;The tests will pass and you can see we have done so without actually relying on our dependencies. These were mocked and injected into our class with all of their methods returning exactly what we defined in our test.&lt;/p&gt;

&lt;h3&gt;
  
  
  Testing the reverse
&lt;/h3&gt;

&lt;p&gt;We also want to test the second path (what if the validation returns false, business rules dictate we should therefor not transition the object)&lt;/p&gt;

&lt;p&gt;Take a look at the second test and you can see our test is pretty similar only now we are forcing the validator to return false. As such our assertions have changed and we now expect setState and Save to never be called on our account object.&lt;/p&gt;

&lt;h2&gt;
  
  
  What we achieved
&lt;/h2&gt;

&lt;p&gt;The original code was hard to test and tightly coupled. The refactor has allowed us to make the code more testable but a great side affect of this is that the code is also now more flexible.&lt;/p&gt;

&lt;p&gt;Let me know if you have any questions in the comments!&lt;/p&gt;

</description>
      <category>php</category>
      <category>unittesting</category>
      <category>refactoring</category>
    </item>
  </channel>
</rss>
