<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pawel Szymura on Medium]]></title>
        <description><![CDATA[Stories by Pawel Szymura on Medium]]></description>
        <link>https://medium.com/@pawel.szymura?source=rss-c95198f5aad5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*t8Cv-vRWt7E0fZpsd3Go-Q.jpeg</url>
            <title>Stories by Pawel Szymura on Medium</title>
            <link>https://medium.com/@pawel.szymura?source=rss-c95198f5aad5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 00:14:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pawel.szymura/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Open Close Principle]]></title>
            <link>https://medium.com/@pawel.szymura/open-close-principle-2258d8481c43?source=rss-c95198f5aad5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2258d8481c43</guid>
            <category><![CDATA[open-closed-principle]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Pawel Szymura]]></dc:creator>
            <pubDate>Wed, 19 Aug 2020 07:00:51 GMT</pubDate>
            <atom:updated>2020-08-19T07:39:41.813Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding SOLID Principles: Open Closed</h3><p>That is the second article from the series about SOLID principles. This time I should give you more details about the Open Closed Principle. The element of software should be locked for modification but open to extension. Uncle Bob himself used to say: “<em>Good architecture reduces the amount of modified code to the absolute minimum. Ideally to zero</em>”.</p><h4>Major errors made during system expansion</h4><p>Thanks to SRP we know how to divide the system into smaller parts that can be easily extended. Easily? But how? Let’s imagine that Payroll Department wants to extend the PayCalculator class mentioned in the <a href="https://medium.com/@pawel.szymura/understanding-solid-principles-single-responsibility-d366d72e4c12">previous article</a> by implementing other methods of calculation. The basic form of calculation was hour-based calculation. The next step was adding the bonus calculation for sales department employees. In the next stage calculation for drivers and B2B co-workers was added changing at the same time the name of original method into ‘fullTimepay()’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*0Dplv4t9qz4d9m09iNNWCg.png" /><figcaption>Step 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*0Dplv4t9qz4d9m09iNNWCg.png" /><figcaption>Step 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*n5FpJbjpzi0XH8o-UmrBnw.png" /><figcaption>Step 3</figcaption></figure><p>Is such a development of the system correct? According to SOLIDS’s first principle everything seems to be well-defined — our class has only one actor — Payroll Department, and therefore — one source of changes. It turns out however that the complexity of choosing the right method of wages calculation more and more increases cyclomatic complexity. This method results in the necessity of making modifications in the class with every single change introduced. And what’s worse, there will be a need for “external” changes for other modules/classes to be able to use new methods.</p><p>According to Robert C. Martin’s recommendations the number of changes in the class and related code elements are far too high.</p><h4>Proper development</h4><p>Looking at the tasks that are carried out by the class it can be easily noticed that its main purpose is to calculate the wages of the employees by means of different algorithms. It is worth to pay attention to the fact that each algorithm is independent from others and there is a high probability of the occurrence of another algorithm (but it doesn’t really mean that such one must appear).</p><p>We use inheritance and polymorphism in such a scenario. While creating the frame of the class — the abstract class for instance — and its further implementations, we’ll obtain the following class scheme:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*cSwfJg9eqErXpIndN3We1Q.png" /></figure><p>The above scheme allows to achieve a very important feature. If we use the ‘factory model’ in the process of creating new classes inherited from PayCalculator it will become the only place in the system where the changes, expanding the system and its new functions, can be implemented. The classes related to payroll calculations will be blocked for any modifications and open to extensions. Furthermore, the system can be extended also with the classes that will not inherit straight from PayCalculator.</p><h4><strong>A bit more about architecture</strong></h4><p>While using the OCP in designing the payroll calculation we will have to create certain abstraction, a base class. It will be fixed and invariable during the whole life cycle of the system. There might be many different implementations but the said class would remain invariable.</p><p>The other modules in the system will depend on that invariable abstract. It will positively affect the stability and reliability of the system. It will be easier for testing (e.g. unit testing), and the need of introducing the changes will not be a threat to anyone.</p><h4><strong>Summary</strong></h4><p>The essence of OCP is to use the simplicity of its steering components whilst making the class expansion. Using the polymorphism and virtual methods, programming increases the functionality of the systems without the negative impact on the clarity and integrity of the classes. It all involves the use of best patterns and practices. It is worth mentioning that this process affects positively the whole architecture of the system, which becomes more resistant to changes, whilst the modules become more independent. And the cyclomatic complexity decreases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2258d8481c43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SOLID Principles: Single Responsibility]]></title>
            <link>https://medium.com/@pawel.szymura/understanding-solid-principles-single-responsibility-d366d72e4c12?source=rss-c95198f5aad5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d366d72e4c12</guid>
            <dc:creator><![CDATA[Pawel Szymura]]></dc:creator>
            <pubDate>Wed, 12 Aug 2020 08:42:10 GMT</pubDate>
            <atom:updated>2020-08-19T08:11:23.956Z</atom:updated>
            <content:encoded><![CDATA[<p>SOLID principles are regarded as one the best practices in programming. We hear about them all the time. Unfortunately, it seems to me that these rules are often misunderstood. I’ll try to present them in the series of five articles, one article for each rule.</p><h3>How has it all started?</h3><p>The rules originated in the 80s of the twentieth century. As a whole they were collected by Robert C. Martin — a famous “Uncle Bob”, an American software engineer, instructor, and best-selling author. He is most recognized for developing numerous software design principles and for being the founder of influential Agile Manifesto. Uncle Bob, if You read it by any chance, I’d like to thank you for each sentence from your books, which were, and still are, very precious to me. I’m constantly discovering how deep they are. At the beginning they were not called SOLID at all, it was one of the friends of Uncle Bob who suggested a different order so that a famous mnemonic acronym appeared. And, starting from 2004 these rules has been functioning under the smart name SOLID. They appeared in the context of object-oriented programming but can be referred to as any blocks of the code. Thanks to them our software should:</p><ul><li>Be flexible to changes</li><li>Be easy to understand</li><li>Enable to create components used in many various systems</li></ul><h3>Definition of Single-responsibility principle</h3><p>This rule, although at first sight seems to be the simplest of them all, appears to be worst understood. Many times, either while talking to the software engineers or while working over the project, or even in the course of recruitment process, when I ask to describe a chosen rule I can hear about the SRP that “class shall be responsible for one thing”. I usually ask an auxiliary/rescue question like how many public methods a class should have then. Almost always I hear “one”. This is not true. It’s a circulating opinion. Even Uncle Bob admitted after some time that the name was not accurate. As an author I suggest that a class (module, code block, etc.) shall have only “one reason for changes”. How can it be understood? Let’s look at the example.</p><h3>Breaking the rule</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*fmQOG9Z6qdq5RROG4fsWiQ.png" /></figure><p>Let’s imagine a usual class with user data. There have been three roles of user-actors defined in the system:</p><p>- Human resources department — prepares work time reports</p><p>- Payroll department — calculates salaries of employees</p><p>- Administration department — introduces employees to the system and makes updates in case of any change</p><p>-</p><p>Both payroll and human resources departments use the method that calculates the number of working hours — RegularHour(). Let’s assume that payroll department needs to change the method of calculating reported working hours in such a way that work during nights or weekends is double counted . Thanks to that it is possible to calculate the salary on the base of one rate. At the same time, HR department requires reported working hours to be calculated with a certain coefficient which will correct working time in such a way that a breakfast break or informal coffee breaks will be deducted from this reported working time. In the best version the method that calculates the number of working hours will contain a lot of conditions. In the worst version, while the second report is serviced, the changes introduced by the first one will be deleted.</p><h3>Correcting the situation</h3><p>The above example is not wrong because of several public methods, it is wrong because the reasons for changing EmployeeData class are overlapping. HR department or payroll department can demand changes that interact with each other. The easiest way to improve the code is to separate the class in such a way that functionality of each actor is contained in a separate class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*pR95cTEUS6ctPkboPBZUqw.png" /></figure><p>Now, if any department will demand changes to be made they should not influence functionalities that are used by other departments. However, 3 new classes have appeared in a code. Each of them can be potentially modified but by one actor only. It must be remembered that an actor can be a group of users but these will be users that make the same tasks in the system. Otherwise, it can be said that each class has one stakeholder.</p><p>It is possible that the change of each place in which the original version of a class was brought about will be troublesome and will require a huge amount of time. In such a situation it is worth to use the facade pattern</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*GQq1enAjlEUbx8eHH7nSaA.png" /></figure><h3>Examples of other applications</h3><p>The rule can be applied in reference to other structures of the code. And so, as an example, form user that collects contact data of an employee and client, despite the fact that it enables to introduce the same data it has different reasons for changes. It is worth mentioning, after the author of these rules, that another rule — DRY, is not violated when we have the code that looks the same but realizes a separate business tasks that have other reasons for changes.</p><h3>About the software architecture in brief</h3><p>Looking at SRP in a bit wider context allows to undertake proper designing methods. Let’s see how the application architecture that is built from API on a server and Angular application on Frontend, consequently maintained for all layers of application, could look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*52m3k9-M1X-MdkJIfVYKjA.png" /></figure><p>It is not difficult to imagine that in each component (class) there will occur sequences of conditions “if” that define specific behaviors for each actor. Such an architecture will cause problems with every change. Situation can be improved by using SRP in each layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*PnRs5QRn4eypOlP1hp_Xag.png" /></figure><p>Such an architecture will be surely more legible, easier to maintain and more resistant to changes. Additionally, such an application will be easier to scale or shape into microservices.</p><h3>Summary</h3><p>Using SRP does not necessarily mean that our class should have one public method and do one thing only. It should only has one reason for a change”. Thanks to it changes that will appear will not lead into situation when one change overlaps another. It is worth adding that the rule can be applied both in reference to the class and to the component, module or library. Thanks to SRP not only our classes will be better but also the whole architecture of our applications. I hope, my dear reader, that when we meet again you won’t tell me that the class shall do one thing only.</p><p><a href="https://medium.com/@pawel.szymura/open-close-principle-2258d8481c43">See next article</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d366d72e4c12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to prepare test data for unit test]]></title>
            <link>https://medium.com/@pawel.szymura/how-to-prepare-test-data-for-unit-test-e08c03e1d9af?source=rss-c95198f5aad5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e08c03e1d9af</guid>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Pawel Szymura]]></dc:creator>
            <pubDate>Thu, 30 Jul 2020 05:34:31 GMT</pubDate>
            <atom:updated>2020-07-30T05:34:31.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gTCUCVUd__CtGJmekmolw.png" /></figure><p>There are many articles describing how to write a good test. But the question is how to create a good data test? I will show an example, different from what you may have ever read. A few months ago, I developed a module for checking if the weight of a set of vehicles is too high or not. The module has been prepared according to the Polish law. Subsequent paragraphs define several dozen cases. The set of vehicles can be treated as one entity or each of them separately.</p><p>The very first decision was to assume whether each paragraph act should be a separate rule (block) in a code. Because there are plenty of rules, I decided to create a specific response class. This could tell if a paragraph is fulfilled or not:</p><pre>public class Info<br>{<br>        public string Paragraph { get; set; }<br>        public decimal CurrentValue { get; set; }<br>        public decimal Limit { get; set; }<br>        public int? AxisNumber { get; set; }<br>        public bool IsValid =&gt; CurrentValue &lt;= Limit;</pre><pre>private Info(string paragraph)<br>        {<br>            Paragraph = paragraph;<br>        }</pre><pre>public static Info Paragraph(string paragraph)<br>        {<br>            return new Info (paragraph);<br>        }<br>}</pre><h3>Algorithm preparation</h3><p>Now I was able to return with information about which rule is exceeded or not. What is the limit for the current rule? What is the current weight of a set of vehicles or axis pressure? If it is possible which axis is exceeded? Now I was ready to collect all the rules and relevant factors. It could be described with the following questions:</p><ul><li>Is it a car and a trailer or a tractor and a semi-trailer?</li><li>How many axes does a car or a tractor have?</li><li>How many axes does a trailer or semi-trailer have?</li><li>Is there a pneumatic suspension?</li><li>Which axis is a drive axis?</li><li>Are there any twin tires?</li><li>What are axis pressures?</li><li>What is a total weight?</li><li>What is the distance between axes?</li><li>How many axes are there in the group of axes?</li><li>What is the pressure of each axis in the group?</li></ul><p>As you can see there are many parameters and combinations. In this situation, a unit test is a must. Let’s start coding with 100% test code coverage.</p><h4>Objects creation</h4><p>First of all, I wanted to create a code concept that would allow an easy creation of subsequent test cases, as well as real objects. I decided that it would be best to use the Builder Design Pattern for this purpose. In our case, it is important that the set of vehicles consists of a car or a tractor and a trailer or a semi-trailer, respectively. Each axis has its own pressure. The sum of these pressures is the weight of individual vehicles.</p><p>This is already enough to create the builder class that will help us create a set of vehicles:</p><pre>internal class VehicleSetBuilder<br>{<br> public static VehicleSetBuilder Create()<br> {<br>  return new VehicleSetBuilder();<br> }</pre><pre>public VehicleSet Build() =&gt; vehicleSet;</pre><pre>public VehicleSetBuilder AddCarAxis(Axis axis)<br> {<br>  vehicleSet.Axes.Insert(vehicleSet.Car.AxisCount, axis);<br>  vehicleSet.Car.AxisCount++;<br>  return this;<br> }</pre><pre>public VehicleSetBuilder AddTrailerAxis(Axis axis)<br> {<br>  vehicleSet.Axes.Add(axis);<br>  vehicleSet.Trailer.AxisCount++;<br>  return this;<br> }</pre><pre>public VehicleSetBuilder IsSemiTrailer()<br> {<br>  vehicleSet.Trailer.IsSemiTrailer = true;<br>  return this;</pre><pre>}</pre><pre>internal VehicleSetBuilder IsTractor()<br> {<br>  vehicleSet.Car.IsTractor = true;<br>  return this;<br> }</pre><pre>internal VehicleSetBuilder HasPneumaticSuspensjon()<br> {<br>  vehicleSet.IsPneumaticSuspensjon = true;<br>  return this;<br> }<br>}</pre><p>And a single car axle:</p><pre>internal class AxisBuilder<br>{<br> public static AxisBuilder Create()<br> {<br>  return new AxisBuilder();<br> }<br> public Axis Build() =&gt; axis;</pre><pre>public AxisBuilder SetPresure(decimal presure)<br> {<br>  axis.PressureWithLoad = presure;<br>  return this;<br> }</pre><pre>public AxisBuilder IsDriveAxis()<br> {<br>  axis.IsDrive = true;<br>  return this;<br> }</pre><pre>public AxisBuilder HasDoubleTires()<br> {<br>  axis.Wheels = 4;<br>  return this;<br> }<br>}</pre><p>Now if we want to create a set of vehicles with specific parameters, consisting of, for example:</p><p>Tractor with two axes, where axis loads are 8 and 9 tonnes respectively and the first of the axes is driving, and a semi-trailer with three axes, each of which has 8.5 tonnes pressure equipped with a pneumatic suspension, just write the code:</p><pre>var vehicleSet = VehicleSetBuilder<br> .Create() .AddCarAxis(AxisBuilder.Create().SetPresure(8M).IsDriveAxis().Build())<br> .AddCarAxis(AxisBuilder.Create().SetPresure(9M).Build())<br> .AddTrailerAxis(AxisBuilder.Create().SetPresure(8.5M).Build())<br> .AddTrailerAxis(AxisBuilder.Create().SetPresure(8.5M).Build())<br> .AddTrailerAxis(AxisBuilder.Create().SetPresure(8.5M).Build())<br> .HasPneumaticSuspensjon()<br> .IsTractor()<br> .IsSemiTrailer()<br> .Build();</pre><p>This way of creating a set of vehicles allows you to create transparent test cases and, of course, real objects in the application.</p><h4>The main class of the algorithm</h4><p>Now let’s add a class, which task will be to check whether a vehicle set exceeds the permissible standards separately for each of the cases described in the regulations. The most complex rules, which define groups of axes, based on different distances between individual axes and define limits depending on the number of axes in the group and the distance between them. For the sake of simplicity, they will be omitted.</p><pre>public class VehicleSetChecker<br>{<br> public VehicleSetChecker(VehicleSet vehicleSet)<br> {<br>  resultChecker = new List&lt;Info&gt;();<br>  this.vehicleSet = vehicleSet;</pre><pre>}<br> <br> public List&lt;Info&gt; IsOverWeight()<br> {<br>  resultChecker.Append(VehicleSet3Axes ());<br>  resultChecker.Append(VehicleSet4AxesCar2Axes ());<br>  return resultChecker;<br> }</pre><pre>private Info VehicleSet3Axes()<br> {<br>  const string PARAGRAPH = &quot;§1. 1.&quot;;<br>  if (vehicleSet.TotalAxes == 3)<br>  {<br>   return Info.Paragraph(PARAGRAPH).Result(vehicleSet.TotalWeight, 28);<br>  }<br>  return null;<br> }</pre><pre>private Info VehicleSet4AxesCar2Axes()<br> {<br>  const string PARAGRAPH = &quot;§1. 2.&quot;;<br>  if (IsCarWithAxesAndTrailerAxes(2, 2))<br>  {<br>   return Info.Paragraph(PARAGRAPH).Result(vehicleSet.TotalWeight, 36);<br>  }<br>  return null;<br> }<br>}</pre><p>(The rest of rules were omitted)</p><h4>First Test</h4><p>Now we can create our first test:</p><pre>const string PARAGRAPH = &quot;§1. 1.&quot;;<br>[TestMethod]<br>public void WehicleSetWithThreeAxisTest()<br>{<br> var vehicleSet = VehicleSetBuilder<br>  .Create()<br>  .AddCarAxis(AxisBuilder.Create().SetPresure(9.5M).IsDriveAxis().HasDoubleTires().Build())<br>  .AddCarAxis(AxisBuilder.Create().SetPresure(9.5M).IsDriveAxis().HasDoubleTires().Build())<br>  .AddTrailerAxis(AxisBuilder.Create().SetPresure(9.5M).Build()<br>  .HasPneumaticSuspensjon()<br>  .Build();</pre><pre>VehicleSetChecker overWeightChecker = new VehicleSetChecker(vehicleSet);<br> CheckerResultList result = overWeightChecker.IsOverWeight();<br> Assert.IsTrue(result.HasParagraphReason(PARAGRAPH));<br> Assert.IsFalse (result.IsValid);<br>}</pre><p>First we create a simple vehicle set for checking separate rules. All the tests look very similar.</p><p>Second, we create a test object. In the above case, it will be a combination of vehicles with a total weight of 28.5 tones. Then we initialize the class, which is responsible for all checks, we perform the check as a result of which we get a list of Info objects. Finally, we check whether the vehicle has been correctly marked as exceeding the weight and whether the collection of Info objects contains the error information resulting from rule 1.1.</p><h4>Summary</h4><p>Such a test development path and the entire verification algorithm allows to create both tests to validate for:</p><ul><li>a particular regulation — by verifying a vehicle set slightly exceeding the permissible standards and the vehicle set that is in the upper limit of these standards,</li><li>all regulations at once — by verifying whether the entire vehicle does not exceed any standards,</li><li>each case asked to be verified by the client. Creation of a very simple test confirmed the correctness of the implementation — the algorithm returns a precise information about the reason for exceeding the standards.</li></ul><p>Designing applications and tests at the same time made it possible to prepare such a set of classes that facilitated the creation of further test scenarios and their verification through unit tests.</p><p>Despite the high complexity of the algorithm, only a few comments returned from the client about the created module:</p><ul><li>A few ended up indicating the paragraph, which is the reason to mark the set of vehicles as exceeding the standards,</li><li>One concerned the omission of a specific rule contained in the transitional provisions,</li><li>One specific case, which required a professional opinion of a legal expert regarding the interpretation of a law — unfortunately I had to agree with the lawyers. Maybe the act is written in an ambiguous way, and only with knowledge and experience, it can be interpreted correctly.</li></ul><p>When creating modules, that we intend to test with unit tests, it is also a good idea to plan it for providing data tests. This will allow you to create realistic tests. It will facilitate not only the creation of both tests but also the implementation of algorithms.</p><p>What is the pressure of each axis in the group?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e08c03e1d9af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Does the programmer have a chance to avoid simple mistakes?]]></title>
            <link>https://medium.com/@pawel.szymura/does-the-programmer-have-a-chance-to-avoid-simple-mistakes-2037751ea01d?source=rss-c95198f5aad5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2037751ea01d</guid>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[development-tips]]></category>
            <dc:creator><![CDATA[Pawel Szymura]]></dc:creator>
            <pubDate>Wed, 27 May 2020 10:06:58 GMT</pubDate>
            <atom:updated>2020-05-27T10:43:44.089Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QwScrgYPKioqy3cAf4SC-Q.jpeg" /></figure><p>I have seen once such a meme: “If debugging serves to remove errors from the code, programming certainly involves inserting bugs into the code.” There is some truth in it. Modern IT systems implement a lot of very complex processes, it is very easy to make a mistake. The programmer creates a tool that can be used in different cases. Testers and then end users will apply this tool in a way that the author hadn’t even imagined before. Combining this with ordinary human error during software development creates a mix that sooner or later will always “explode”.</p><p>So how should a programmer work so that the effects of his work are not negatively assessed after just a few clicks? Does the programmer have a chance to avoid simple mistakes? I have been creating a business application for companies and institutions for over 15 years. Over the years, I have developed a pattern that allows me to discover many simple errors at an early stage. This is a set of simple tests that significantly increases the quality of the produced software. Applied together with automatic tests (from unit to integration) they give a chance to eliminate many mistakes.</p><p>Most consumer applications can be generalized according to the following scheme</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*sXnkhN_2eNVDQ-kPyDFi1A.png" /></figure><p>No matter if we create a module of invoices, complaints, orders, reports, users, we can more or less always find the above pattern.</p><h4>I wrote the functionality, what’s next?</h4><p>The first problem that appears during simple tests performed by the programmer is the approach to the pattern of permissions. The programmer will perform the test using the role with the highest permission. In this way, I want to check if all components are working properly. It is a mistake to stop at such testing. Majority of future users will operate on the minimum permission required. It is worth enriching the basic check of the new functionality with the lowest possible permission to perform a given operation. Such a test allows to:</p><ul><li>verify if the system of user rights and roles works properly,</li><li>check if items available only to the administrator will be properly hidden or deactivated,</li><li>verify whether the lack of administrative data is an obstacle to the application’s operation,</li><li>check if, for example, the record passes successfully for a user with the rights different than the administrator’s rights.</li></ul><p>A perceptive reader will probably immediately think about the roles of users who can do more than the lowest role, but are not administrators. Should the programmer check all possible cases? Yes, because he or she should verify if the settings work for other roles or claims. No, because he or she does not have to log into the system thoroughly for every possible type of user verifying the operation. What about the other cases? Cold calculation of the code and delegation the functionality to a tester allow to eliminate most errors in this area.</p><h4>Adding, editing</h4><p>The ability to create new and to edit existing elements is the basic functionality of each module. By performing the following simple tests many different cases of application can be verified. When testing a user form (or dedicated API) for creating or editing, it is worth following the path below:</p><ul><li>Minimal filling — only required fields — allows to check whether such a set of data is really enough?</li><li>Maximum filling — allows you to check if all data are saved?</li><li>Boundary conditions for fields — allows to check if validation works as expected</li><li>Positive test — allows you to check if the system works for correct data?</li><li>Negative test — allows you to check if the system stops working for incorrect data and correctly informs the user about it?</li><li>Save — allows you to check if the change will actually be saved in a database?</li><li>Update — allows to check if the object will be modified?</li><li>Delete — allows you to check if the object can be deleted?</li><li>Navigation — allows you to check if the transitions are working properly, in the case of the form, you can check it for in and out?</li></ul><p>It should be a good practice to verify such operations as: saving, modifying or deleting directly on the database. When verifying the record, it is worth verifying that the data is being written to the appropriate columns and whether they are read and displayed correctly. This is to eliminate mistakes in the style of saving the net amount in the place for the gross amount and vice versa.</p><p>In the above method it is not possible to check all test cases, but it is possible to check if all the applied mechanisms work. At the testing stage, we should receive the answer whether these mechanisms are working properly.</p><h4>The list</h4><p>Another very common element to check is the list of elements, the table. Very often it will be a view from which you go to the edit form. Here you can again talk about a simple list of tests that allow for an initial assessment of the programmer’s work effect:</p><ul><li>Fetching data — we check if the data is in each column?</li><li>Filtering / Searching — we check if the search engine returns filtered data?</li><li>Pagination — we check if the paging mechanism works, and, whether filtering also works on subsequent pages?</li><li>Transitions — we check if you can go to details etc.?</li><li>Going to editing — allows you to check whether the user will be redirected to the correct record according to his authorization level?</li></ul><p>At this stage, it is also worth checking if there is a mistake regarding the assignment of data to the appropriate columns in the appropriate format — here it is very easy to make a mistake.</p><h3>The Report, The printout</h3><p>All types of printouts, reports, statements are very difficult to test and verify. It is necessary to prepare a set of test data and maintain it at a level adequate to the current state of application development. This will keep the data source in a state that allows you to verify, for example, invoice printout or a sales report over a given period. How to construct such a set of test data:</p><ul><li>Minimal — an object containing only the minimum data necessary for its recording</li><li>Maximum — an object containing all possible data</li><li>Most common — an object that contains a set of the most common data if it can be defined</li><li>In a different language version — at least one object in a different language version if the system provides such a possibility.</li></ul><p>Because work on e.g. the invoice module can be significantly extended in time, it is also worth updating the status of your own test data set with subsequent system updates. Contrary to appearances, this allows you to significantly save time by being constantly ready for testing.</p><h3>Database update</h3><p>After preparing the script or package updating the database and running it on the development machine, I strongly recommend that you should do this test also on the test machine. Configuration or server versions may differ between the development environment and the server. Verification of changes is a must.</p><h3>Debug — Release</h3><p>We are happy to use conditional compilation. It allows, for example, to write code that will perform the required task step by step — just in time for the needs of the debugger. This carries the risk of not adapting the code changes to the Release version. Therefore, checking tests should be done in Release mode. Surprisingly, you can do such tests on the programmer’s computer.</p><h3>Summary</h3><p>Modern systems are very complex and carry out very complex tasks. However, they can be systematized into fragments that can be described as successive CRUD elements. By using the presented set of simple tests you can eliminate many errors. In addition, by testing at a low level of permissions in a production-close environment, you can avoid many unpleasant surprises. I encourage you to create your own list of steps to verify the new code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2037751ea01d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Update your database with as less connection as is possible]]></title>
            <link>https://medium.com/@pawel.szymura/update-your-database-with-as-less-connection-as-is-possible-61166b55994e?source=rss-c95198f5aad5------2</link>
            <guid isPermaLink="false">https://medium.com/p/61166b55994e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[net-core]]></category>
            <dc:creator><![CDATA[Pawel Szymura]]></dc:creator>
            <pubDate>Wed, 20 May 2020 06:01:01 GMT</pubDate>
            <atom:updated>2020-05-22T10:57:22.124Z</atom:updated>
            <content:encoded><![CDATA[<h3>Update Your Database with as Less Connection as is Possible</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRAjkIr9s4ewY-x_fd99ww.png" /></figure><h3>Introduction</h3><p>This is the second article from series about how to improve your .NET application that use Entity Framework. In this lesson I will show you how to reduce number of connection and queries send to database when updating database. I will show you a few good practices in some common cases. Let’s start.</p><h3>Update single object</h3><p>Many developers use the following pattern when updating data:</p><pre>public async Task UpdateOneFiled()<br>        {<br>            var product = await GetProduct();<br>            if (product == null)<br>                return;<br><br>            product.ModifiedDate = DateTime.Now;<br><br>            using (var context = new ProdcutionContext())<br>            {<br>                var currentObject = await context.Product.FirstOrDefaultAsync(p =&gt; p.ProductID == product.ProductID);<br>                currentObject.ModifiedDate = product.ModifiedDate;<br>                context.SaveChanges();<br>            }<br>        }</pre><p>Which we can describe as follows:</p><ol><li>Retrieve data from user (GetProduct)</li><li>Get current version of an object</li><li>Update current object with the data from user</li><li>Save data.</li></ol><p>Sounds familiar? Unnecessary step is of course getting current version of object from database. I’ve seen many tutorials and articles where the author suggests such a way. It probably comes from not knowing the method Attach() and the way how EF in a previous version was updating data. In the default scenario EF was updating all fields. Most of the time we update only some bunch of fields and we don’t need to check what the previous version was. Imagine that we have a kind of an application for managing goods. We can change its name, color, cost and last modification date should change after each update:</p><pre>public async Task UpdateSeveralFiledWithAttach()<br>        {<br>            var product = await GetProduct();<br>            if (product == null)<br>                return;<br><br>            using (var context = new ProdcutionContext())<br>            {<br>                context.Product.Attach(product);<br>                context.Entry(product).State = EntityState.Unchanged;<br>                context.Entry(product).Property(x =&gt; x.Name).IsModified = true;<br>                context.Entry(product).Property(x =&gt; x.Color).IsModified = true;<br>                context.Entry(product).Property(x =&gt; x.StandardCost).IsModified = true;<br>                context.Entry(product).Property(x =&gt; x.ModifiedDate).IsModified = true;<br>                await context.SaveChangesAsync();<br>            }<br>        }</pre><p>Now our scenario looks like:</p><ol><li>Retrieve data from user (GetProduct)</li></ol><p>2. Mark object as tracked by data base context (Attach)</p><p>3. Set object as unchanged</p><p>4. Set only needed fields as changed</p><p>5. Save data.</p><p>We should remember that the object “product” must have a proper ID. Checking the Profiler we can see that only the fields set as changed are updated. It’s great! In Profiler we can see what is happening:</p><figure><img alt="Print sreen from profiler showing that only marked fields are being updated" src="https://cdn-images-1.medium.com/max/603/1*X5425XuFBpXuZx2w8vBHpw.png" /></figure><h3>Update bigger object</h3><p>In this scenario we need to update an order. The order has some attributes like date of order and list of position. Let’s assume that client can create order within a few days. He can save the order again and again modifying the list of positions:</p><p>1. Adding new positions,</p><p>2. Removing previously added positions,</p><p>3. Modifying previously added positions.</p><p>Unfortunately the most common scenario looks like that:</p><p>1. Get order from client</p><p>2. <strong>Get </strong>the list of positions that should be modified</p><p>3. <strong>Get </strong>the list of positions that should be added</p><p>4. <strong>Get </strong>the list of positions that should be removed from database</p><p>5. Modify the list of positions from step 2</p><p>6. Add the list of positions from step 3</p><p>7. Remove the list of object from step 4</p><p>The code looks like this:</p><pre>public async Task UpdateWrongWay()<br>        {<br>            var order = await GetOrder();<br><br>            using (var context = new ProdcutionContext())<br>            {<br>                //prepare data<br>                var elementsToUpdate = order.OrderItems.Where(x =&gt; x.SalesOrderDetailID &gt; 0).ToList();<br>                var elementsToAdd = order.OrderItems.Where(x =&gt; x.SalesOrderDetailID == 0).ToList();<br>                var elementsToDelete = (await context.OrderItem<br>                    .Where(x =&gt; x.SalesOrderID == order.SalesOrderID)<br>                    .ToListAsync())<br>                    .Where(x =&gt; !order.OrderItems.Any(item =&gt; item.SalesOrderDetailID == x.SalesOrderDetailID)).ToList();<br><br>                //update<br>                foreach (OrderItem itemToUpdate in elementsToUpdate)<br>                {<br>                    var item = await context.OrderItem.FirstOrDefaultAsync(x =&gt; x.SalesOrderDetailID == itemToUpdate.SalesOrderDetailID);<br>                    item.OrderQty = itemToUpdate.OrderQty;<br>                }<br><br>                //add<br>                foreach (OrderItem itemToAdd in elementsToAdd)<br>                    context.OrderItem.Add(itemToAdd);<br><br>                //remove<br>                foreach (OrderItem itemToDelete in elementsToDelete)<br>                    context.OrderItem.Remove(itemToDelete);<br><br>                await context.SaveChangesAsync();<br>            }<br>        }</pre><p>It isn’t the worst solution, I have seen the code where elements to update where retrieved from database using query or using SaveChanges() method after each data manipulation like updating object, inserting and deleting.</p><p>First of all we should consider if this is a proper situation when the order can be changed by two different users. In the overwhelming number of cases the answer is no. So if a user starts editing the order nothing will be changed. Therefore we can modify data model sending data from client for extra property “DeleteByUser”. It will inform us that the user has deleted such position from order. We should also modify our GUI to send back to the server a list of items deleted by the user, but only those that were previously read from the database.</p><p>Now our scenario looks like:</p><p>1. Get the order from the client</p><p>2. <strong>Filter </strong>the list of positions that should by modified</p><p>3. <strong>Filter </strong>the list of positions should be added</p><p>4. <strong>Filter </strong>the list of positions that should be removed from database</p><p>5. Modify the list of positions from step 2 without reading data</p><p>6. Add the list of positions from step 3</p><p>7. Remove the list of object from step 4</p><p>The code would look like as follows:</p><pre>public async Task Optymized()<br>        {<br>            var order = await GetOrder();<br><br>            using (var context = new ProdcutionContext())<br>            {<br>                //prepare data<br>                var elementsToUpdate = order.OrderItems.Where(x =&gt; x.SalesOrderDetailID &gt; 0 &amp;&amp; !x.DeleteByUser).ToList();<br>                var elementsToAdd = order.OrderItems.Where(x =&gt; x.SalesOrderDetailID == 0).ToList();<br>                var elementsToDelete = order.OrderItems.Where(x =&gt; x.DeleteByUser).ToList();<br><br><br>                //update<br>                context.OrderItem.AttachRange(elementsToUpdate);<br>                foreach (OrderItem itemToUpdate in elementsToUpdate)<br>                {<br>                    context.Entry(itemToUpdate).State = EntityState.Unchanged;<br>                    context.Entry(itemToUpdate).Property(x =&gt; x.OrderQty).IsModified = true;<br>                    itemToUpdate.OrderQty = itemToUpdate.OrderQty;<br>                }<br><br>                //add<br>                foreach (OrderItem itemToAdd in elementsToAdd)<br>                    context.OrderItem.Add(itemToAdd);<br><br>                //remove<br>                foreach (OrderItem itemToDelete in elementsToDelete)<br>                    context.OrderItem.Remove(itemToDelete);<br>                <br>                await context.SaveChangesAsync();<br>            }<br>        }</pre><p>Now we don not need to query database for elements to delete. We get rid of reading database for actual version of each position to update.</p><h3>Summary</h3><p>If we modify only few properties we should to this like in a clean SQL — update only needed properties. Then we can get rid of retrieving current version from database. We can reach that by using method Attach and by manipulating state of object. Little change in frontend can help improve the way we check which elements from list we should delete. Don’t afraid of using method AttachRange().</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61166b55994e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieving data from the database]]></title>
            <link>https://medium.com/@pawel.szymura/retrieving-data-from-the-database-a020cac90c8a?source=rss-c95198f5aad5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a020cac90c8a</guid>
            <dc:creator><![CDATA[Pawel Szymura]]></dc:creator>
            <pubDate>Mon, 16 Mar 2020 21:54:42 GMT</pubDate>
            <atom:updated>2020-03-16T21:54:42.214Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>This is the first article from the series about how to improve your .NET application which uses Entity Framework. I will show you some simple tips that will boost your application. I hope that many advices you will find here can be used in any other ORM or even any other programming language. First of all let’s see how the majority of applications work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*v7HhalmJq29hH4ChRhgJrg.png" /><figcaption>Figure 1. Simplified model modern applications</figcaption></figure><p>As we can see there are many client (devices) connected to application store in server. The application server communicates with data base server. Application server is a very fast machine prepared to handle many requests from clients and to communicate with a database server. What might be interesting is the fact that for most of the time server waits for the response from a database. The main aim of this series is to reduce and optimize communication between server application and database in order to use them both more efficiently. At the beginning we should start using an asynchronous call to database (and of course any other data source). Then the thread is not held up by waiting for the response but it can start to handle another request.</p><h3>Let’s get some data.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*OL73qpK5fzPlBWRXfuTmRw.png" /></figure><p>Let’s imagine we have to prepare some simple report that informs what kind of bikes are finished and are waiting in a warehouse, with the quantity lower than let’s say 50. We need their names, categories and of course the quantity itself.</p><p>First of all we need to create entity models:</p><pre>public class Product<br>{<br> [Key]<br> public int ProductID { get; set; }<br> public int ProductSubcategoryID { get; set; }<br> public int DaysToManufacture { get; set; }<br> public short SafetyStockLevel { get; set; }<br> public short ReorderPoint { get; set; }<br> public string ProductNumber { get; set; }<br> public decimal StandardCost { get; set; }<br> public decimal ListPrice { get; set; }<br> public string Color { get; set; }<br> public string Name { get; set; }<br> public bool MakeFlag { get; set; }<br> public bool FinishedGoodsFlag { get; set; }<br> public DateTime SellStartDate { get; set; }<br> public DateTime ModifiedDate { get; set; }<br> public ProductSubcategory ProductSubcategory { get; set; }<br> public ProductInventory ProductInventory { get; set; }<br>}</pre><pre>public class ProductSubcategory<br>{<br> [Key]<br> public int ProductSubcategoryID { get; set; }<br> public int ProductCategoryID { get; set; }<br> public string Name { get; set; }<br> public DateTime ModifiedDate { get; set; }<br> public ProductCategory ProductCategory { get; set; }<br> public ICollection&lt;Product&gt; Products { get; set; }<br>}</pre><pre>public class ProductCategory<br>{<br> [Key]<br> public int ProductCategoryID { get; set; }<br> public string Name { get; set; }<br> public Guid rowguid { get; set; }<br> public DateTime ModifiedDate { get; set; }<br>}</pre><pre>public class ProductInventory<br>{<br> public int ProductID { get; set; }<br> public short LocationID { get; set; }<br> public string Shelf { get; set; }<br> public byte Bin { get; set; }<br> public short Quantity { get; set; }<br> public Guid rowguid { get; set; }<br> public DateTime ModifiedDate { get; set; }<br> public Location Location { get; set; }<br>}</pre><pre>public class Location<br>{<br> [Key]<br> public short LocationID { get; set; }<br> public string Name { get; set; }<br> public decimal CostRate { get; set; }<br> public decimal Availability { get; set; }<br> public DateTime ModifiedDate { get; set; }<br>}</pre><p>Now we can create a database context:</p><pre>public class ProdcutionContext : DbContext<br>{<br> public DbSet&lt;Product&gt; Product { get; set; }<br> public DbSet&lt;ProductSubcategory&gt; ProductSubcategory { get; set; }<br> public DbSet&lt;ProductCategory&gt; ProductCategory { get; set; }<br> public DbSet&lt;ProductInventory&gt; ProductInventory { get; set; }<br> public DbSet&lt;Location&gt; Location { get; set; }</pre><pre>protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)<br> {<br>  optionsBuilder.UseSqlServer(@&quot;Server=.\SQLEXPRESS;Database=AdventureWorks2017;&quot;)<br>  .EnableSensitiveDataLogging(true);<br> }</pre><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br> {<br>  modelBuilder.HasDefaultSchema(&quot;Production&quot;);<br>  modelBuilder.Entity&lt;ProductInventory&gt;()<br>   .HasKey(o =&gt; new { o.LocationID, o.ProductID });<br> }<br>}</pre><p>Now we are ready to prepare data:</p><pre>using (var context = new ProdcutionContext())<br>{<br> var data = await context.Product<br>  .Include(x =&gt; x.ProductSubcategory)<br>  .Include(x =&gt; x.ProductSubcategory).ThenInclude(x =&gt; x.ProductCategory)<br>  .Include(x =&gt; x.ProductInventory)<br>  .Include(x =&gt; x.ProductInventory).ThenInclude(x =&gt; x.Location)<br>  .Where(x =&gt; x.ProductSubcategory.ProductCategory.Name.Equals(&quot;Bikes&quot;))<br>  .Where(x =&gt; x.ProductInventory.Location.Name.Equals(&quot;Finished Goods Storage&quot;))<br>  .Where(x =&gt; x.ProductInventory.Quantity &lt; 50)<br>  .OrderBy(x =&gt; x.ProductSubcategory.Name)<br>  .ThenBy(x =&gt; x.Name)<br>  .ThenBy(x =&gt; x.ProductInventory.Quantity)<br>  .ToListAsync();</pre><pre>foreach (var item in data)<br> {<br>  Console.WriteLine($&quot;{item.ProductSubcategory.Name} - {item.Name} - {item.ProductInventory.Quantity}&quot;);<br> }<br>}</pre><p>After running the program we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*SDWQRw_CNKoSTRyhZG3rjw.png" /></figure><p>It looks good, let’s see what has happened in details. To check what was going on I used SQL Server Profiler:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*O2Ri3iSoBP9ItkcQujt8yg.png" /></figure><p>Look how much data has been read. This is on of the most important issues which developers forget about when using any ORM. In short, when I ask a developer to prepare the list of all student names using SQL I will probably get something like:</p><pre>select firstName from student;</pre><p>But If ask about it in ORM like Entity Framework, I would get:</p><pre>context.Students.ToList()</pre><p>which, of course, gets all columns from the table. In the example above, all the columns from all the tables on the basis of which SQL query is created, are taken from the database.</p><h3>Solution</h3><p>The best way to fix the problem and reduce the amount of data received from server is to use the projection properly. There are two solutions. One is to use an anonymous class and the other is to prepare a special class. Let’s call it as view model. Both are good. You can use anonymous class when you do not need to pass the data forward. In most cases the best way is to prepare the class as follows:</p><pre>public class StockProductViewModel<br>{<br> public string Subcategory { get; internal set; }<br> public string Product { get; internal set; }<br> public short Quantity { get; internal set; }<br>}</pre><p>Then we can modify our code retrieving data:</p><pre>using (var context = new ProdcutionContext())<br>{<br> var data = await context.Product<br>  .Include(x =&gt; x.ProductSubcategory)<br>  .Include(x =&gt; x.ProductSubcategory).ThenInclude(x =&gt; x.ProductCategory)<br>  .Include(x =&gt; x.ProductInventory)<br>  .Include(x =&gt; x.ProductInventory).ThenInclude(x =&gt; x.Location)<br>  .Where(x =&gt; x.ProductSubcategory.ProductCategory.Name.Equals(&quot;Bikes&quot;))<br>  .Where(x =&gt; x.ProductInventory.Location.Name.Equals(&quot;Finished Goods Storage&quot;))<br>  .Where(x =&gt; x.ProductInventory.Quantity &lt; 50)<br>  .OrderBy(x =&gt; x.ProductSubcategory.Name)<br>  .ThenBy(x =&gt; x.Name)<br>  .ThenBy(x =&gt; x.ProductInventory.Quantity)<br>  .Select(x =&gt; new StockProductViewModel{<br>   Subcategory = x.ProductSubcategory.Name,<br>   Product = x.Name,<br>   Quantity = x.ProductInventory.Quantity<br>  })<br>  .ToListAsync();</pre><pre>foreach (var item in data)<br> {<br>  Console.WriteLine($&quot;{item.Subcategory} - {item.Product} - {item.Quantity}&quot;);<br> }<br>}</pre><p>Now we can check which SQL queries are generated when we start our new code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*3o1B5RczEOO-9dNu2EIvCg.png" /></figure><p>As we can see we get only the data we need. What is worth noticing is that fewer readings were made and it all took less time.</p><h3>Summary</h3><p>One of the problems with using ORM like Entity Framework is that one forgets about the proper use of projection. When we write a query in SQL we avoid using “select *“ but when we use ORM we forget about not using “select *”. To avoid the problem we should properly define “Select” section. In Entity Framework we have two solutions: either to create abstract or concrete classes that define only the fields we need.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a020cac90c8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>