<?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 Emre İRİŞ on Medium]]></title>
        <description><![CDATA[Stories by Emre İRİŞ on Medium]]></description>
        <link>https://medium.com/@emreiris?source=rss-fa890824224f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*u8HRR6E0pcWlo3RBmVhc0w.jpeg</url>
            <title>Stories by Emre İRİŞ on Medium</title>
            <link>https://medium.com/@emreiris?source=rss-fa890824224f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:21:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emreiris/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[Strategy Pattern]]></title>
            <link>https://emreiris.medium.com/strategy-pattern-19ae93b243dc?source=rss-fa890824224f------2</link>
            <guid isPermaLink="false">https://medium.com/p/19ae93b243dc</guid>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Emre İRİŞ]]></dc:creator>
            <pubDate>Sat, 08 Mar 2025 13:45:27 GMT</pubDate>
            <atom:updated>2025-03-08T13:48:59.469Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will explain the strategy pattern you are probably familiar with without noticing. If you are unfamiliar with design patterns, you can read the first paragraph of this <a href="https://emreiris.medium.com/prototype-pattern-ff5de0f2acca">article</a>. Now let&#39;s dive in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_cDwzpqA94vF0mkZCF9sg.jpeg" /><figcaption>image that is nothing to do with article</figcaption></figure><p>Sometimes ( a lot of times ) it is required to operate some algorithm for the collection of data such as sorting, filtering, transforming, etc. C++ users who are familiar with STL use functions like</p><pre>enum class TestResult {<br>SUCCESS,<br>FAIL<br>ERROR<br>};<br><br>struct TestCase<br>{<br>  std::string name;<br>  TestResult result;<br>}<br><br>std::vector&lt;TestCase&gt; testCases{ <br>{&quot;smoketest&quot;       , SUCCESS },<br>{&quot;pingtest&quot;        , FAIL    },<br>{&quot;performancetest&quot; , FAIL    },<br>{&quot;diagnostictest&quot;  , ERROR   }<br>};<br> <br>std::vector&lt;TestCase&gt; successfullTests;<br><br>std::copy_if(testCases.begin(), testCases.end(),<br>             std::back_inserter(successfullTests),<br>              [](TestCase case) { return case.result == TestResult::SUCCESS; }<br>            );</pre><p>As you can see from the copy_if function, it is possible to define an algorithm to decide if the object should be copied or not, the only expectation is to return a boolean. This is called the <strong>strategy pattern</strong>, having the freedom to choose the strategy. The diagram looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*LUGUPFdAJmVYaHCYusFIDA.png" /></figure><p>We have a strategy class that consists of an algorithm and other strategy classes are derived from it applies the strategy. Also, callable objects can be used instead of classes, anything that can run an algorithm with the desired signature can be used. Now let&#39;s give an example.</p><p>This time I will also give the scenario, imagine you have an e-commerce system that accepts different payment systems such as credit cards, Bitcoin, and Apple Pay and your product manager notifies you that other payment methods will be supported with the new release, so you should define a dynamic interface that can be expanded without modifying the existing interface, it is also important for open/closed principle. Then, lets define it.</p><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>class PaymentStrategy {<br>public:<br>    virtual void pay(int amount) const = 0;<br>    virtual ~PaymentStrategy() = default;<br>};<br><br>class CreditCardPayment : public PaymentStrategy {<br>public:<br>    void pay(int amount) const override {<br>        std::cout &lt;&lt; &quot;Paid $&quot; &lt;&lt; amount &lt;&lt; &quot; using Credit Card.&quot; &lt;&lt; &quot;\n&quot;;<br>    }<br>};<br><br>class ApplePayPayment : public PaymentStrategy {<br>public:<br>    void pay(int amount) const override {<br>        std::cout &lt;&lt; &quot;Paid $&quot; &lt;&lt; amount &lt;&lt; &quot; using Apple Pay.&quot; &lt;&lt; &quot;\n&quot;;<br>    }<br>};<br><br>class BitcoinPayment : public PaymentStrategy {<br>public:<br>    void pay(int amount) const override {<br>        std::cout &lt;&lt; &quot;Paid $&quot; &lt;&lt; amount &lt;&lt; &quot; using Bitcoin.&quot; &lt;&lt; &quot;\n&quot;;<br>    }<br>};<br><br>class PaymentContext {<br>private:<br>    std::unique_ptr&lt;PaymentStrategy&gt; strategy;<br>public:<br>    void setPaymentStrategy(std::unique_ptr&lt;PaymentStrategy&gt; s) {<br>        strategy = std::move(s);<br>    }<br><br>    void pay(int amount) const {<br>        if (strategy) {<br>            strategy-&gt;pay(amount);<br>        } else {<br>            std::cout &lt;&lt; &quot;No payment method selected!&quot; &lt;&lt; &quot;\n&quot;;<br>        }<br>    }<br>};<br><br>int main() {<br>    PaymentContext context;<br><br>    std::cout &lt;&lt; &quot;Selecting Credit Card Payment:&quot; &lt;&lt; &quot;\n&quot;;<br>    context.setPaymentStrategy(std::make_unique&lt;CreditCardPayment&gt;());<br>    context.pay(100);<br><br>    std::cout &lt;&lt; &quot;\nSelecting Apple Pay Payment: &quot; &lt;&lt; &quot;\n&quot;;<br>    context.setPaymentStrategy(std::make_unique&lt;ApplePayPayment&gt;());<br>    context.pay(200);<br><br>    std::cout &lt;&lt; &quot;\nSelecting Bitcoin Payment:&quot; &lt;&lt; &quot;\n&quot;;<br>    context.setPaymentStrategy(std::make_unique&lt;BitcoinPayment&gt;());<br>    context.pay(300);<br><br>    return 0;<br>}<br><br>Output:<br>Selecting Credit Card Payment:<br>Paid $100 using Credit Card.<br><br>Selecting Apple Pay Payment:<br>Paid $200 using Apple Pay.<br><br>Selecting Bitcoin Payment:<br>Paid $300 using Bitcoin.</pre><p>As is seen in the example, <strong>PaymentStrategy </strong>is defined with the pay virtual function, and then <strong>CreditCardPayment</strong>, <strong>ApplePayPayment,</strong> and <strong>BitcoinPayment </strong>classes implement<strong> </strong>the pay algorithm, we now have a flexible payment strategy that can be extended. Ofc it is possible to use functors like this.</p><pre>#include &lt;iostream&gt;<br>#include &lt;functional&gt;<br>#include &lt;memory&gt;<br><br>class CreditCardPayment {<br>public:<br>    void operator()(int amount) const {<br>        std::cout &lt;&lt; &quot;Paid $&quot; &lt;&lt; amount &lt;&lt; &quot; using Credit Card.&quot; &lt;&lt; &quot;\n&quot;;<br>    }<br>};<br><br>class ApplePayPayment {<br>public:<br>    void operator()(int amount) const {<br>        std::cout &lt;&lt; &quot;Paid $&quot; &lt;&lt; amount &lt;&lt; &quot; using Apple Pay.&quot; &lt;&lt; &quot;\n&quot;;<br>    }<br>};<br><br>class BitcoinPayment {<br>public:<br>    void operator()(int amount) const {<br>        std::cout &lt;&lt; &quot;Paid $&quot; &lt;&lt; amount &lt;&lt; &quot; using Bitcoin.&quot; &lt;&lt; &quot;\n&quot;;<br>    }<br>};<br><br>class PaymentContext {<br>private:<br>    std::function&lt;void(int)&gt; strategy;<br>public:<br>    void setPaymentStrategy(std::function&lt;void(int)&gt; s) {<br>        strategy = std::move(s);<br>    }<br><br>    void pay(int amount) const {<br>        if (strategy) {<br>            strategy(amount);<br>        } else {<br>            std::cout &lt;&lt; &quot;No payment method selected!&quot; &lt;&lt; &quot;\n&quot;;<br>        }<br>    }<br>};<br><br>int main() {<br>    PaymentContext context;<br><br>    std::cout &lt;&lt; &quot;Selecting Credit Card Payment: &quot; &lt;&lt; &quot;\n&quot;;<br>    context.setPaymentStrategy(CreditCardPayment());<br>    context.pay(100);<br><br>    std::cout &lt;&lt; &quot;\nSelecting Apple Pay Payment:&quot; &lt;&lt; &quot;\n&quot;;<br>    context.setPaymentStrategy(ApplePayPayment());<br>    context.pay(200);<br><br>    std::cout &lt;&lt; &quot;\nSelecting Bitcoin Payment:&quot; &lt;&lt; &quot;\n&quot;;<br>    context.setPaymentStrategy(BitcoinPayment());<br>    context.pay(300);<br><br>    return 0;<br>}</pre><p>Instead of having a pure virtual function to invoke, a function call operator is invoked. There is no difference from the operation aspect.</p><p>We had a closer look at the strategy pattern, and gave an example( I don&#39;t think payment systems are written in C++ but anyway :) ) to monitor the application of the strategy pattern. Next time you use std::find_if, std::copy_if, std::remove_if, you can say “Oh there we have a strategy pattern over here” with high consciousness.</p><p>Happy developing</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19ae93b243dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Composite Pattern]]></title>
            <link>https://emreiris.medium.com/composite-pattern-1bf8dd474f4c?source=rss-fa890824224f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bf8dd474f4c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Emre İRİŞ]]></dc:creator>
            <pubDate>Tue, 25 Feb 2025 05:50:44 GMT</pubDate>
            <atom:updated>2025-02-25T05:50:44.431Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will explain the need for composite design patterns and how it works. If you are unfamiliar with the design pattern concept, you can read the first heading of this <a href="https://emreiris.medium.com/prototype-pattern-ff5de0f2acca">article</a>. Well, let&#39;s dive into the composite design pattern.</p><p>Composite design is a nice way of composing tree structures and provides functionality for using objects individually. It is classified as a structural design pattern. Imagine you have a JSON file like this;</p><pre>{<br>&quot;menu&quot;: <br>{<br>    &quot;id&quot;: 123,<br>    &quot;value&quot;: &quot;File&quot;, <br>    &quot;popup&quot;: {<br>      &quot;menuitem&quot;: [<br>        {&quot;value&quot;: &quot;New&quot;, &quot;onclick&quot;: &quot;CreateNewDoc()&quot;},<br>        {&quot;value&quot;: &quot;Open&quot;, &quot;onclick&quot;: &quot;OpenDoc()&quot;},<br>        {&quot;value&quot;: &quot;Close&quot;, &quot;onclick&quot;: &quot;CloseDoc()&quot;}<br>      ]<br>    }<br>  }<br>}</pre><p>As you can see, you have various keys and values for each key, value types vary like string, int, array, etc. This is a tree-structured format because it can be nested infinitely in theory. Let&#39;s take a look at another one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/0*0AYkfsX5t7Ngq9jH.png" /><figcaption>Linux file tree</figcaption></figure><p>This is another example of the tree structure, it is the nested file structure, some components like bin, usr, etc. are folders, and possibly some components like dirtree, and fortunes are files.</p><p>Composite design pattern offers a solution to create well-defined structures and use them with ease. There are three elements in the composite design pattern: composite, leaf, and component.</p><h4>Component</h4><p>The component is the interface the client code is coupled, it provides the desired operation for the high-level classes.</p><h4>Leaf</h4><p>The leaf is the object that it desires to do some operation on, it is where implementation is done, and it does not have any sub-classes.</p><h4>Composite</h4><p>Components are branches of the tree, they have parents, children, and siblings, and they are responsible for connecting all leaves and other composite objects. Also, they return the result of operations in the leaf.</p><p>The composite design pattern looks like this on the diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*GL7lOvD9MLfFP4MRSyZh3A.png" /></figure><p>Both Leaf and Composite elements are derived from Component. Now let&#39;s implement it with an example.</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>#include &lt;memory&gt;<br>#include &lt;algorithm&gt;<br><br>class Widget {<br>public:<br>    virtual void draw() const = 0;<br>    virtual ~Widget() = default;<br>};<br><br>class Button : public Widget {<br>public:<br>    Button(const std::string&amp; text) : text(text) {}<br>    void draw() const override {<br>        std::cout &lt;&lt; &quot;Drawing Button: &quot; &lt;&lt; text &lt;&lt; &quot;\n&quot;;<br>    }<br>private:<br>    std::string text;<br>};<br><br>class Label : public Widget {<br>public:<br>    Label(const std::string&amp; text) : text(text) {}<br>    void draw() const override {<br>        std::cout &lt;&lt; &quot;Drawing Label: &quot; &lt;&lt; text &lt;&lt; &quot;\n&quot;;<br>    }<br>private:<br>    std::string text;<br>};<br><br>class Panel : public Widget {<br>public:<br>    void addWidget(std::shared_ptr&lt;Widget&gt; widget) {<br>        children.push_back(widget);<br>    }<br><br>    void removeWidget(std::shared_ptr&lt;Widget&gt; widget) {<br>        children.erase(std::remove_if(children.begin(), children.end(),<br>            [&amp;widget](const std::shared_ptr&lt;Widget&gt;&amp; w) { return w == widget; }), children.end());<br>    }<br><br>    void draw() const override {<br>        std::cout &lt;&lt; &quot;Drawing Panel with &quot; &lt;&lt; children.size() &lt;&lt; &quot; widgets:&quot; &lt;&lt; &quot;\n&quot;;<br>        for (const auto&amp; child : children) {<br>            child-&gt;draw();<br>        }<br>    }<br>private:<br>    std::vector&lt;std::shared_ptr&lt;Widget&gt;&gt; children;<br>};<br><br>int main() {<br>    auto button1 = std::make_shared&lt;Button&gt;(&quot;OK&quot;);<br>    auto button2 = std::make_shared&lt;Button&gt;(&quot;Cancel&quot;);<br>    auto label = std::make_shared&lt;Label&gt;(&quot;Username:&quot;);<br><br>    auto panel = std::make_shared&lt;Panel&gt;();<br>    panel-&gt;addWidget(label);<br>    panel-&gt;addWidget(button1);<br>    panel-&gt;addWidget(button2);<br><br>    std::cout &lt;&lt; &quot;Before removing a widget:&quot; &lt;&lt; &quot;\n&quot;;<br>    panel-&gt;draw();<br><br>    panel-&gt;removeWidget(button2); <br><br>    std::cout &lt;&lt; &quot;\nAfter removing the Cancel button:&quot; &lt;&lt; &quot;\n&quot;;<br>    panel-&gt;draw();<br><br>    return 0;<br>}<br><br>Output:<br>Before removing a widget:<br>Drawing Panel with 3 widgets:<br>Drawing Label: Username:<br>Drawing Button: OK<br>Drawing Button: Cancel<br><br>After removing the Cancel button:<br>Drawing Panel with 2 widgets:<br>Drawing Label: Username:<br>Drawing Button: OK</pre><p>In this example, we have a “Widget” class with a pure virtual member function named draw to draw the widget itself, then we have two classes named “Button” and “Label”, they implement the draw function as they need and then finally we have “Panel” function that uses widgets by drawing them. Now let&#39;s assign their role together</p><pre>class Widget {<br>public:<br>    virtual void draw() const = 0;<br>    virtual ~Widget() = default;<br>};</pre><p>The “Widget” class is the <strong>component</strong>, it does not have any implementation and provides an interface to be used.</p><pre>class Button : public Widget {<br>public:<br>    Button(const std::string&amp; text) : text(text) {}<br>    void draw() const override {<br>        std::cout &lt;&lt; &quot;Drawing Button: &quot; &lt;&lt; text &lt;&lt; &quot;\n&quot;;<br>    }<br>private:<br>    std::string text;<br>};<br><br>class Label : public Widget {<br>public:<br>    Label(const std::string&amp; text) : text(text) {}<br>    void draw() const override {<br>        std::cout &lt;&lt; &quot;Drawing Label: &quot; &lt;&lt; text &lt;&lt; &quot;\n&quot;;<br>    }<br>private:<br>    std::string text;<br>};</pre><p>Button and Label classes represent <strong>leaf, </strong>they are derived from the Widget class and implement the actual work<strong>.</strong></p><pre>class Panel : public Widget {<br>public:<br>    void addWidget(std::shared_ptr&lt;Widget&gt; widget) {<br>        children.push_back(widget);<br>    }<br><br>    void removeWidget(std::shared_ptr&lt;Widget&gt; widget) {<br>        children.erase(std::remove_if(children.begin(), children.end(),<br>            [&amp;widget](const std::shared_ptr&lt;Widget&gt;&amp; w) { return w == widget; }), children.end());<br>    }<br><br>    void draw() const override {<br>        std::cout &lt;&lt; &quot;Drawing Panel with &quot; &lt;&lt; children.size() &lt;&lt; &quot; widgets:&quot; &lt;&lt; &quot;\n&quot;;<br>        for (const auto&amp; child : children) {<br>            child-&gt;draw();<br>        }<br>    }<br>private:<br>    std::vector&lt;std::shared_ptr&lt;Widget&gt;&gt; children;<br>};</pre><p>Panel class is <strong>composite</strong>, it has addWidget and removeWidget member functions to control children, also it runs the actual “draw” operation of all children. Since children are defined as vectors of Widget pointers, another panel can be added as children, like a tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*mJZoZno95HW5Lgc-" /></figure><p>The UML chart of the example looks like the above.</p><p>In this article, I explained the composite design pattern with real-world examples, even tho you won&#39;t need to implement it, you may have to understand the structure since even Qt uses it for their libraries.</p><p>Happy coding</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bf8dd474f4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prototype Pattern]]></title>
            <link>https://emreiris.medium.com/prototype-pattern-ff5de0f2acca?source=rss-fa890824224f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff5de0f2acca</guid>
            <dc:creator><![CDATA[Emre İRİŞ]]></dc:creator>
            <pubDate>Fri, 21 Feb 2025 07:34:43 GMT</pubDate>
            <atom:updated>2025-02-21T07:34:43.685Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will explain the prototype pattern, one of the useful design patterns. But before explaining the prototype pattern, let&#39;s cover the meaning of the design pattern.</p><h4>Design Patterns</h4><p>In the early stage of software development, developers realized that they needed systematic design rules to keep the complexity under control, otherwise, complexity was becoming complex and non-controllable. The first study was introduced by Christopher Alexander in 1977, A Pattern Language: Towns, Buildings, Construction (Center for Environmental Structure Series), then Design Patterns: Elements of Reusable Object-Oriented Software was published by Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm in 1994 and we associate 23 design pattern now toGoF(Gang of Four). But design patterns are not limited to only GoF Patterns, there are other patterns like type erasure, MVC(Model-View-Controller), thread pool, etc.</p><p>Design patterns offer generic solutions to generic problems, whether an object is created, isolating the high-level modules from the low-level modules, or implementing an iterator to costume-type objects.</p><p>Design patterns can be composed and it is helpful for many times to use more than one pattern shoulder-to-shoulder like observer+strategy to observe the behavior of an object and take action dynamically, or builder+prototype to both efficiently build an object and clone it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zgaCAj__H4ggdw6LxEk0Cw.jpeg" /><figcaption>Prototype and Builder merging their power</figcaption></figure><p>GoF design patterns are classified into three categories;</p><ul><li>Creational patterns: Helps the object creation, copying, and borrowing operations.</li><li>Structural partners: Helps the relation of objects to each other.</li><li>Behavioral patterns: Helps control the behavior of objects, modules, and anything functional.</li></ul><p>Well since we had a small introduction to design patterns, let&#39;s start exploring prototype patterns.</p><h4>Prototype Pattern</h4><p>The prototype pattern is used to copy objects without having a dependence on the class it is copied. Some C++ enjoyers already may think that copy constructors and copy assignment operators do this job but both can&#39;t be used to copy different types of objects. For example;</p><pre>#include &lt;iostream&gt;<br><br>class Vehicle {<br>    public:<br>    Vehicle(std::string m) : model(m) {}<br><br>    Vehicle(const Vehicle&amp; other) : model(other.model) {}<br><br>    virtual void show() const {<br>        std::cout &lt;&lt; &quot;Vehicle Model: &quot; &lt;&lt; model &lt;&lt; &quot;\n&quot;;<br>    }<br>    protected:<br>    std::string model;<br>};<br><br>class Car : public Vehicle {<br>    public:<br>    Car(std::string m, int doors) : Vehicle(m), numDoors(doors) {}<br><br>    Car(const Car&amp; other) : Vehicle(other), numDoors(other.numDoors) {}<br><br>    void show() const override {<br>        std::cout &lt;&lt; &quot;Car Model: &quot; &lt;&lt; model &lt;&lt; &quot;, Doors: &quot; &lt;&lt; numDoors &lt;&lt; &quot;\n&quot;;<br>    }<br>    int numDoors; <br>};<br><br>int main() {<br>    Car myCar(&quot;Tesla&quot;, 4);<br><br>    Vehicle copiedCar = myCar;<br><br>    myCar.show();     <br>    copiedCar.show();<br><br>    return 0;<br>}<br><br>Output:<br>Car Model: Tesla, Doors: 4<br>Vehicle Model: Tesla</pre><p>In the example above, the copied car was supposed to have the number of doors info by numDoors variable but it was not copied due to the object slicing issue. So the intention was to copy myCar into copiedCar but it was not achieved. Where there is a problem, there is a solution for that and it is prototype pattern. Let&#39;s update the code and achieve what is intended.</p><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>class Vehicle {<br>public:<br>    Vehicle(const std::string&amp; model) : model(model) {}<br><br>    virtual std::unique_ptr&lt;Vehicle&gt; clone() const = 0; <br><br>    virtual void show() const {<br>        std::cout &lt;&lt; &quot;Vehicle Model: &quot; &lt;&lt; model &lt;&lt; &quot;\n&quot;;<br>    }<br><br>    virtual ~Vehicle() = default;<br><br>    protected:<br>    std::string model;<br>};<br><br>class Car : public Vehicle {<br>public:<br>    Car(const std::string&amp; model, int doors) : Vehicle(model), numDoors(doors) {}<br><br>    std::unique_ptr&lt;Vehicle&gt; clone() const override {<br>        return std::make_unique&lt;Car&gt;(*this);<br>    }<br><br>    void show() const override {<br>        std::cout &lt;&lt; &quot;Car Model: &quot; &lt;&lt; model &lt;&lt; &quot;, Doors: &quot; &lt;&lt; numDoors &lt;&lt; &quot;\n&quot;;<br>    }<br>    private:<br>    int numDoors;<br>};<br><br>class Truck : public Vehicle {<br>public:<br>    Truck(const std::string&amp; model, int capacity) : Vehicle(model), payloadCapacity(capacity) {}<br><br>    std::unique_ptr&lt;Vehicle&gt; clone() const override {<br>        return std::make_unique&lt;Truck&gt;(*this);<br>    }<br><br>    void show() const override {<br>        std::cout &lt;&lt; &quot;Truck Model: &quot; &lt;&lt; model &lt;&lt; &quot;, Payload Capacity: &quot; &lt;&lt; payloadCapacity &lt;&lt; &quot; tons&quot; &lt;&lt; &quot;\n&quot;;<br>    }<br>    private:<br>    int payloadCapacity;<br>};<br><br>int main() {<br>    std::unique_ptr&lt;Vehicle&gt; myCar = std::make_unique&lt;Car&gt;(&quot;Tesla&quot;, 4);<br>    std::unique_ptr&lt;Vehicle&gt; myTruck = std::make_unique&lt;Truck&gt;(&quot;Volvo&quot;, 10);<br><br>    std::unique_ptr&lt;Vehicle&gt; clonedCar = myCar-&gt;clone();<br>    std::unique_ptr&lt;Vehicle&gt; clonedTruck = myTruck-&gt;clone();<br><br>    myCar-&gt;show();    <br>    clonedCar-&gt;show(); <br><br>    myTruck-&gt;show();     <br>    clonedTruck-&gt;show(); <br><br>    return 0;<br>}<br><br>Output:<br>Car Model: Tesla, Doors: 4<br>Car Model: Tesla, Doors: 4<br>Truck Model: Volvo, Payload Capacity: 10 tons<br>Truck Model: Volvo, Payload Capacity: 10 tons</pre><p>Let me explain the code part by part.</p><pre>class Vehicle {<br>public:<br>    Vehicle(const std::string&amp; model) : model(model) {}<br><br>    virtual std::unique_ptr&lt;Vehicle&gt; clone() const = 0; <br><br>    virtual void show() const {<br>        std::cout &lt;&lt; &quot;Vehicle Model: &quot; &lt;&lt; model &lt;&lt; &quot;\n&quot;;<br>    }<br><br>    virtual ~Vehicle() = default;<br><br>    protected:<br>    std::string model;<br>};</pre><p>Here, a Vehicle class is created, and there is a pure virtual function that returns a unique pointer to the base class, it shall be implemented later to have a common cloning functionality. There is also a “show” function but that is not required, just to demonstrate the example.</p><pre>class Car : public Vehicle {<br>public:<br>    Car(const std::string&amp; model, int doors) : Vehicle(model), numDoors(doors) {}<br><br>    std::unique_ptr&lt;Vehicle&gt; clone() const override {<br>        return std::make_unique&lt;Car&gt;(*this);<br>    }<br><br>    void show() const override {<br>        std::cout &lt;&lt; &quot;Car Model: &quot; &lt;&lt; model &lt;&lt; &quot;, Doors: &quot; &lt;&lt; numDoors &lt;&lt; &quot;\n&quot;;<br>    }<br>    private:<br>    int numDoors;<br>};<br><br>class Truck : public Vehicle {<br>public:<br>    Truck(const std::string&amp; model, int capacity) : Vehicle(model), payloadCapacity(capacity) {}<br><br>    std::unique_ptr&lt;Vehicle&gt; clone() const override {<br>        return std::make_unique&lt;Truck&gt;(*this);<br>    }<br><br>    void show() const override {<br>        std::cout &lt;&lt; &quot;Truck Model: &quot; &lt;&lt; model &lt;&lt; &quot;, Payload Capacity: &quot; &lt;&lt; payloadCapacity &lt;&lt; &quot; tons&quot; &lt;&lt; &quot;\n&quot;;<br>    }<br>    private:<br>    int payloadCapacity;<br>};</pre><p>“Car” and “Truck” classes are derived from the vehicle class, which has different attributes and implements the clone function. This will provide a generic copying functionality in the runtime without object slicing.</p><pre>int main() {<br>    std::unique_ptr&lt;Vehicle&gt; myCar = std::make_unique&lt;Car&gt;(&quot;Tesla&quot;, 4);<br>    std::unique_ptr&lt;Vehicle&gt; myTruck = std::make_unique&lt;Truck&gt;(&quot;Volvo&quot;, 10);<br><br>    std::unique_ptr&lt;Vehicle&gt; clonedCar = myCar-&gt;clone();<br>    std::unique_ptr&lt;Vehicle&gt; clonedTruck = myTruck-&gt;clone();<br><br>    myCar-&gt;show();    <br>    clonedCar-&gt;show(); <br><br>    myTruck-&gt;show();     <br>    clonedTruck-&gt;show(); <br><br>    return 0;<br>}<br><br>Output:<br>Car Model: Tesla, Doors: 4<br>Car Model: Tesla, Doors: 4<br>Truck Model: Volvo, Payload Capacity: 10 tons<br>Truck Model: Volvo, Payload Capacity: 10 tons</pre><p>Finally, cloning functionality is used in client code, as it is seen, objects don&#39;t lose their attributes when they are copied. So what is intended is achieved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*93SBgca4Y6UbQtp6gEJilw.png" /></figure><p>And this is how the relation between classes is shown, client directly deals with the interface rather than dealing with the lower classes.</p><p>Everything is so far so good, let&#39;s highlight some important parts.</p><ul><li>Prototype pattern helps the copying operator, but if an object is not copyable or has some attributes that are not copyable, then this will fail to copy the objects.</li><li>It is suggested to give relevant names to base classes, like “Copiable”, “Cloneable”, and “Prototype” so that the intent will be clear.</li><li>If there is a circular reference between objects, it should be handled carefully, like a node that also has nodes or a user class that has other users, etc. Only relevant parts should be part of the copying.</li></ul><p>I explained the prototype pattern and hopefully made your mind clear about why it is useful and where to use it.</p><p>Happy coding</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff5de0f2acca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[QT 1| QML Property Bindings]]></title>
            <link>https://emreiris.medium.com/qt-1-qml-property-bindings-86bbe53ef7e?source=rss-fa890824224f------2</link>
            <guid isPermaLink="false">https://medium.com/p/86bbe53ef7e</guid>
            <category><![CDATA[qt]]></category>
            <category><![CDATA[qml]]></category>
            <category><![CDATA[gui]]></category>
            <dc:creator><![CDATA[Emre İRİŞ]]></dc:creator>
            <pubDate>Sat, 08 Jan 2022 10:20:27 GMT</pubDate>
            <atom:updated>2022-01-08T10:20:27.354Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*kQrx2kpd7AChRL7KkReOLg.jpeg" /></figure><p>In the previous article, we had a small brief about how the GUI mechanism works and took a look at terms from the GUI’s world. Also, we analyzed a simple piece of QML code. In this article, we will go deeply into the property binding concept and how to use it efficiently.</p><h4>Wait? What is property exactly?</h4><p>There are plenty of components in QML for different purposes. Some of them are used to display widgets, some of them are used for layout mechanisms and some of them are used for other purposes. The point is every component has different functionality and usage. In order to control their functionality and behaviors, the property concept is introduced in QML. As its name reveals, the property is an attribute of a QML component. Let&#39;s give a small example</p><pre>Window {</pre><pre>id: main_window</pre><pre>width: 640</pre><pre>height: 480</pre><pre>visible: true</pre><pre>title: <em>qsTr</em>(&quot;Hello World&quot;)</pre><pre>}</pre><p>As you see there is a Window component and defined some properties to determine its attribute. It is important to point that properties also have “types”. There are mainly five built-in types in QML; int, string, bool, var( inherited from javascript ), and list( the color is also used as a type but it is identical with string ). It is also possible to define your own type or even the QML component itself but it is reserved for another article :). When using properties somewhere else, It is a must to do type checking.</p><p>Note: Unlike other properties, the Id property can’t be overridden because It is used to access other properties. You cant destroy that bridge.</p><h4>Property Binding</h4><p>Now we can bind properties. Let&#39;s see the example.</p><pre>Window {</pre><pre>id: <em>main_window</em></pre><pre>width: 640</pre><pre>height: 480</pre><pre>visible: true</pre><pre>title: <em>qsTr</em>(&quot;Hello World&quot;)</pre><pre>Rectangle {</pre><pre>id: <em>rect_half</em></pre><pre>width: <em>main_window</em>.width / 2</pre><pre>height: <em>main_window</em>.height</pre><pre>color: &quot;blue&quot;</pre><pre>}</pre><pre>}</pre><p>I defined another child Qml component inside my window and instead of giving a numerical width and height gave main_window’s half-width and height. From this point, whenever main_windows width and height change, It emits a signal to the QML engine, and then the QML engine recalculates or overrides bound properties.</p><p>By default, property binding is detected by the “:” operator in the QML engine. It is possible to reach some results by using slots.</p><pre>Window {</pre><pre>id: <em>main_window</em></pre><pre>width: 640</pre><pre>height: 480</pre><pre>visible: true</pre><pre>title: <em>qsTr</em>(&quot;Hello World&quot;)</pre><pre>onWidthChanged: {</pre><pre><em>rect_half</em>.width = <em>width</em> / 2</pre><pre>}</pre><pre>onHeightChanged: {</pre><pre><em>rect_half</em>.height = heigth</pre><pre>}</pre><pre>Rectangle {</pre><pre>id: <em>rect_half</em></pre><pre>width: 320 <em>//</em> <em>Initial</em> <em>value</em></pre><pre>height: 480 <em>//</em> <em>Initial</em> <em>value</em></pre><pre>color: &quot;blue&quot;</pre><pre>}</pre><pre>}</pre><p>As it is seen instead of binding the property, the same calculations are done in the slot. So whenever main_window’s width and height changed, rect_half’s width and height changed, too.</p><p>Note: Signal and Slot mechanism in Qt is a deep concept and probably will be explained more and more deeply. They deserve their own articles.</p><p>We mentioned about properties have types right. Now we can fairly point that different types of properties cant be bound.</p><pre>Window {</pre><pre>id: <em>main_window</em></pre><pre>width: 640</pre><pre>height: 480</pre><pre>visible: true</pre><pre>title: <em>qsTr</em>(&quot;Hello World&quot;)</pre><pre>onWidthChanged: {</pre><pre><em>rect_half</em>.width = <em>width</em> / 2</pre><pre>}</pre><pre>onHeightChanged: {</pre><pre><em>rect_half</em>.height = heigth</pre><pre>}</pre><pre>Rectangle {</pre><pre>id: <em>rect_half</em></pre><pre>width: 320 <em>//</em> <em>Initial</em> <em>value</em></pre><pre>height: 480 <em>//</em> <em>Initial</em> <em>value</em></pre><pre>color: <em>main_window</em>.height</pre><pre>}</pre><pre>}</pre><pre>Output Message:<br>qrc:/article_1.qml:22:9: Unable to assign int to QColor</pre><p>It is obvious to say that int typed property should not be assigned to QColor typed property.</p><h4><strong>Evil Side of Property Bindings, Binding Loops!!!</strong></h4><p>Property binding relies on property changes and that relies on signal-slot mechanism. But what if bounded property binds the property it is bound? They will bind themselves forever or till the application is crashed. Let&#39;s see an example.</p><pre>Window {</pre><pre>id: <em>main_window</em></pre><pre>width: <em>rect_half</em>.width</pre><pre>height: 480</pre><pre>visible: true</pre><pre>title: <em>qsTr</em>(&quot;Hello World&quot;)</pre><pre>Rectangle {</pre><pre>id: <em>rect_half</em></pre><pre>width: <em>main_window</em>.width / 3</pre><pre>height: <em>main_window</em>.height</pre><pre>color: &quot;blue&quot;</pre><pre>}</pre><pre>}<br>Output Message:<br>QWindowsWindow::setGeometry: Unable to set geometry 53x480+880+280 (frame: 69x519+872+249) on QQuickWindowQmlImpl/&quot;&quot; on &quot;\\.\DISPLAY4&quot;. Resulting geometry: 120x480+880+280 (frame: 136x519+872+249) margins: 8, 31, 8, 8)</pre><p>Do you see the problem? rect_half’s width changed according to main_window’s width but also it is changed when rect_half’s width changed.</p><p>It is obvious to detect. But what if there is chained property binding?</p><pre>Window {</pre><pre>id: <em>main_window</em></pre><pre>width: <em>rect_half</em>.height</pre><pre>height: 480</pre><pre>visible: true</pre><pre>title: <em>qsTr</em>(&quot;Hello World&quot;)</pre><pre>Rectangle {</pre><pre>id: <em>rect_half</em></pre><pre>width: <em>main_window</em>.width / 3</pre><pre>height: <em>main_window</em>.width / 2</pre><pre>color: &quot;blue&quot;</pre><pre>}</pre><pre>}</pre><p>Now main_window’s width binds rect_half’s height. But now that property binds its width. It is a problem because the QML engine won&#39;t be able to set geometry properly due to property binding issues.</p><p>It is a required practice to be aware of binding loops while binding a property.</p><p>I simply introduced QML binding concept and gave some examples. Also, I touched on some dangerous misusage of property binding. You can download and run the code <a href="https://github.com/Emreiris/QML_Lessons.git">here</a>.</p><p>Have a great day and see you in the next article :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86bbe53ef7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[QT 0| Introduction to QML]]></title>
            <link>https://emreiris.medium.com/introduction-to-qml-qt-ec9737a0e334?source=rss-fa890824224f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec9737a0e334</guid>
            <category><![CDATA[qml]]></category>
            <category><![CDATA[qt]]></category>
            <category><![CDATA[gui]]></category>
            <dc:creator><![CDATA[Emre İRİŞ]]></dc:creator>
            <pubDate>Sat, 25 Dec 2021 15:10:50 GMT</pubDate>
            <atom:updated>2022-01-08T10:23:25.272Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*JkOHXoGhXiJ-G9tGbpLf0A.jpeg" /></figure><p><strong>Brief Introduction to GUI’s Mechanism</strong></p><p>Since the displayer technology evolved over the years, human and machine interaction also evolved hand to hand with it. This evolution brought a new discipline to the table, Graphical User Interface, GUI in short. There are numerous examples around you like the webpage you look at right now, social media applications you look at every day, the vending machines that you ask for a portion of food, the ATMs and so much more. The concept of screens is almost identical, providing users well-defined interface through the machine. Because you know, you don&#39;t want to write hundreds of commands to a machine since it is the only thing the machine understands(no offense CLI funs).</p><p><strong>Basics Terms to Make Life Easy</strong></p><p>It is fairly understandable what a GUI looks like from a user perspective. But, we, as a developer, should tackle it more technically. For this reason, let&#39;s take a look at some basic terms.</p><p><strong>Windows</strong></p><p>As it is self-explanatory, the window is the frame that covers all the components( later on we will classify components) of GUI and beings the parent to components. It can be a web page to host your videos, or an IDE to let you code the GUI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KMIXDkYkbQu3jtkIdjvQcw.png" /><figcaption>Figure 1. Simple window</figcaption></figure><p><strong>Widgets ( Graphical Widget )</strong></p><p>Widgets are generic visual components to provide various functionality to users to operate what is wished. Button, checkbox, text area, scrollbar, tab bar, icons, labels, table and many more like that can be classified as a widget. Their visual difference evokes different purposes on the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ut7mHc17oCmFAa7DoUkJEw.png" /><figcaption>Figure 2, window and widgets</figcaption></figure><p><strong>Layout</strong></p><p>We mentioned windows and widgets briefly and explained that windows are like coverage of the widgets. But how should widgets be positioned on the window? Does it make sense to put them randomly? Or giving their position as coordinates? Of course not. The layout is simply how to put widgets on the window. There are a few approaches for different purposes like anchoring or aligning or giving coordinates( bare in your mind that coordinates are bad ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0UpcqLfgEjvFPWUmD-EhBw.png" /><figcaption>Figure 3, Widgets aligned on the center.</figcaption></figure><p>You can see that three widgets are aligned on the center and put some spaces between them.</p><p><strong>Parent, Child &amp; Sibling Concept</strong></p><p>We now have a window and some widgets in it. There is a hierarchy between widgets and windows and between other widgets. In figure 3, the button is the child widget of the window and the window is the parent of all three widgets. As you can guess widgets are siblings to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eVrIeK9_Wra8Y00tfbvSpw.png" /><figcaption>figure 4. Parent, child &amp; sibling example</figcaption></figure><p><strong>Signals &amp; Events</strong></p><p>Widgets are not only to click visually and enjoy with it. Widgets are also responsible to create a warning to inform the business logic side( back end ) and business logic is to take action after this signal. This signal can be button clicking or releasing, text editing, dragging or dropping an object, or sliding a slider. The warning is called a signal and the action is called an event. From this point, we can fairly say that GUI is event-based mostly. It takes action when a signal is emitted by the user.</p><p>There are lots of terms to explain on the way. But It is better to keep it simple for now. Let&#39;s go dive into QML.</p><p><strong>QML</strong></p><p>QML stands for Qt modeling language, it is developed by the Qt company. It is a declarative language( It will be explained in binding concept ) and makes life easy while designing a GUI. Let&#39;s give a simple example. We can consider the development environment later.</p><pre><em>import</em> QtQuick 2.12</pre><pre><em>import</em> QtQuick.Controls 2.5</pre><pre>ApplicationWindow {<br>id: <em>app</em></pre><pre>width: 1080</pre><pre>height: 720</pre><pre>visible: true</pre><pre>title: <em>qsTr</em>(&quot;Windows&quot;)</pre><pre>color: &quot;red&quot;</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtE8spLdPdSk2YtMF0IQaQ.png" /><figcaption>Figure 5. Output after code execution</figcaption></figure><p>There are a few things to consider here. Firstly, the ApplicationWindow component has a scope defined with the curly brackets, every component defined inside curly brackets is ApplicationWindow’s child now. In addition, there are some specifications to be given like width, height, visibility, title, and color. Those are so-called properties. Properties are used to determine the component’s structure. If a property is not defined by the developer( we will do that in the future) It must have an initial value. If it is asked to change any property of the component, It is possible to access it via the component’s id. Let&#39;s add some more code to it.</p><pre><em>import</em> QtQuick 2.12</pre><pre><em>import</em> QtQuick.Controls 2.5</pre><pre>ApplicationWindow {</pre><pre>id: <em>app</em></pre><pre>width: 1080</pre><pre>height: 720</pre><pre>visible: true</pre><pre>title: <em>qsTr</em>(&quot;Window&quot;)</pre><pre>color: &quot;red&quot;</pre><pre>Button {</pre><pre>id: <em>button</em></pre><pre>width: <em>app</em>.width / 10</pre><pre>height: <em>app</em>.height / 10</pre><pre>text: &quot;Press me&quot;</pre><pre>}</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wfR_36SN1PcC-Y7GT30npQ.png" /><figcaption>Figure 6. Output after code execution</figcaption></figure><p>We added a button to our window and gave it an id. Also, we used the parent window’s id to access its properties. As it is seen, it is possible to use component properties to assign value to other properties. If the width property of the “app” component changes, then the button&#39;s width property changes, too. It is one of the beautiful features belonging to QML. Properties can be bound. It also gives the opportunity to design responsive GUI’s.</p><p>It is a simple introduction to Qt QML language. We will see signals, binding concepts, functions, events(and handling them), dynamic component creation, and many more.</p><p>Have a nice day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec9737a0e334" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Derleyici Terbiyeciliği]]></title>
            <link>https://emreiris.medium.com/derleyici-terbiyecili%C4%9Fi-d8d37824f0db?source=rss-fa890824224f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8d37824f0db</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[compilers]]></category>
            <dc:creator><![CDATA[Emre İRİŞ]]></dc:creator>
            <pubDate>Sun, 28 Feb 2021 09:45:09 GMT</pubDate>
            <atom:updated>2021-02-28T09:50:02.957Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mgnWDRTNagni3hxbzx9XYg.jpeg" /><figcaption>resim : en.wikipedia.org</figcaption></figure><p>Yazılım disiplinlerinde derleyici; kodu yorumlayan ve gerekli olduğunda optimize edip en kompakt hale getiren dönüştürücü olarak bilinir. Aynı zamanda yazılan kodu hedef makineye göre uygun formata çeviren birim görevini de üstlenir ( Linking ve Locating aşamaları da derleyicinin parçaları olarak varsayılmıştır ). Örneğin .elf( Executable and Linkable Format ) bu formatlardan bir tanesidir. Fakat bazen modern derleyiciler bile yazılımcının istemediği derlemeler yapabilir. Bazı durumlarda da kodun belli kısımları optimizasyona kapatılabilir, değişkenlerin farklı şekilde belleğe yerleştirilmesi istenebilir ya da olabildiğince az yer kaplaması talep edilebilir. Bunları ve daha fazlasını yapabilmek için derleyiciye bazı komutlar vermek gerekir.</p><p>Yazının devamında bu komutlardan ve işlevlerinden bahsedeceğim.</p><p><strong>__attribute__((…)) Kullanımı</strong></p><p>Kelime anlamından anlaşılacağı üzere attribute ile bir fonksiyonun, bir verinin ya da struct ile öbeklenmiş veri yığınlarının özniteliğini değiştirmek için kullanılır. Bellekteki dizilimi, kapladığı yeri yeniden şekillendirmek, fonksiyonun bellek yerleşimini ya da derleyici tarafından değerlendirilme şeklini değiştirebilmeye yarar. Yazılışı yukarıdaki başlıkta görüldüğü gibidir. Öncelikle __attribute__ daha sonra iki parantez içerisine yapılmak istenen işlem yazılır. Neden iki tane paranteze ihtiyaç duyulmuş hiç bir fikrim yok :). Gelin bir örnek üzerinde inceleyelim.</p><pre>/* 32 bit arch word lenght = 4 byte is assumed. */</pre><pre>int16_t val __attribute__((aligned(4));</pre><p>Yukarıdaki değişken tanımlamasında görüldüğü üzere attribute içerisine aligned eklenmiş. Aligned kullanımı ile verinin bellekte kaplayacağı yerin boyutunu byte cinsinden belirlenmiş oldu. Verinin boyutu 2 byte olması gerekirken 4 byte a çıkartıldı. (Not aligned içerisindeki sayı 2 nin katları şeklinde olmalıdır). Burada ciddi bir bellek harcanması söz konusudur. Yani gereksiz yere 2 byte harcanmış. Fakat 32 bitlik bir mimaride çekirdek register larının 4 byte olduğunu düşününce avantajı ortaya çıkıyor. Eğer bu veri 2 bytelık olarak verilseydi derleyici geri kalan 2 byte ı çekirdek register ına yazmamak için çırpınacaktı. Yani aligned kullanırken bellekten taviz verip performanstan kazanıyoruz. Mimari 64 lik olsaydı aligned değeri 8 olurdu.Bu arada aligned ile bellekte sadece arttırma işlemi yapılmaktadır.</p><pre>int32_t val __attribute__((aligned(2));</pre><p>Yukarıdaki attribute tanımlamasında aligned dikkate alınmaz. Veri yine 4 byte yer kaplar.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;stdint.h&gt;</pre><pre>typedef struct type_1<br>{</pre><pre>uint32_t val1;<br>uint8_t val2;<br>char val3;</pre><pre>};</pre><pre>struct type_2<br>{</pre><pre>uint32_t val1 __attribute__((aligned(4)));<br>uint8_t val2 __attribute__((aligned(4)));<br>char val3 __attribute__((aligned(4)));</pre><pre>};</pre><pre>struct type_3<br>{</pre><pre>uint32_t val1;<br>uint8_t val2;<br>char val3;</pre><pre>} __attribute__((aligned(16)));</pre><pre>int main(void)<br>{</pre><pre>printf(&quot;%u\n&quot;, sizeof(struct type_1));</pre><pre>printf(&quot;%u\n&quot;, sizeof(struct type_2));</pre><pre>printf(&quot;%u\n&quot;, sizeof(struct type_3));</pre><pre>return EXIT_SUCCESS;</pre><pre>}</pre><pre>Output :<br>8<br>12<br>16</pre><p>Aligned yukarıda gösterildiği gibi struct içinde kullanılabilinir. Hatta doğrudan structure ile oluşturulan veri yığını içinde kullanılabilinir. Bu sayede sadece değişken tanımlanmasında sınırlanmamış olur. Şimdi attribute ın farklı bir kullanımına bakalım.</p><pre>/* 32 bit arch word lenght = 4 byte is assumed. */</pre><pre>struct nameless /* nothing came to my mind */<br>{<br>float val1;    /* 4 byte */<br>int16_t val2;  /* 2 byte */<br>char val3;     /* 1 byte */<br>} __attribute__((packed));</pre><p>Packed kullanımı ile derleyiciyi verilerin kapladığı yerden daha fazlasını tutmasına engel olabilirsiniz. Eğer __attribute__((packed)) kullanımı olmasaydı, derleyici 7 byte lık veriyi 2 word olacak şekilde 8 byte a yuvarlayacaktı. Bu durumda da 1 byte kullanılmamış olacaktı. Attribute kullanımı ile bunun önüne geçmiş olduk. Fakat bu seferde performanstan taviz verdik. Yani hem performansı hem de bellek kullanımını olumlu yönde etkilemek çoğu zaman mümkün olmuyor. Tabi hangisinin önemli olduğu tamamanen uygulamaya bağlıdır.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;stdint.h&gt;</pre><pre>struct nameless<br>{</pre><pre>float val1;<br>int16_t val2;<br>char val3;</pre><pre>};</pre><pre>struct nameless_2<br>{</pre><pre>float val1;<br>int16_t val2;<br>char val3;</pre><pre>}  __attribute__((packed));</pre><pre>int main(void)<br>{</pre><pre>printf(&quot;%u\n&quot;, sizeof(struct nameless));</pre><pre>printf(&quot;%u\n&quot;, sizeof(struct nameless_2));</pre><pre>return EXIT_SUCCESS;</pre><pre>}<br>Output :<br>8<br>7</pre><p>Yukarıdaki kod parçasıyla siz de denemeler yapabilirsiniz.</p><p>Şimdi attribute ile bu yazının son örneğine geçelim.</p><pre>inline __attribute__((always_inline)) uint32_t add(uint16_t val1,<br>uint16_t val2)<br>{</pre><pre>    return val1 + val2;</pre><pre>}</pre><p>Burada inline anahtar kelimesi görülmektedir. “inline” kullanımı ile istediğiniz fonksiyonun içeriğinin tamamını fonksiyonun çağırıldığı yere yapıştırmasını sağlayabilirsiniz. Yani fonksiyon hem derlenip bir güzel optimize edilir hem de Macro fonksiyon gibi davranarak performansı arttırır ( Burada fonksiyonun programın yazılı olduğu bellekte zıplamaları azaltacağı belirtilmiştir.). Fakat sadece “inline” kullanımı fonksiyonun gövdesinin çağırıldığı yere kopyalanacağı garantisini vermez. Bu yüzden Yüzüklerin Efendisi’nde Gandalf ın kartallardan yardım aldığı gibi always_inline dan yardım alarak bu işlemi garantiye alabiliriz. Fakat kartalların her sorunu çözmesinin mantıksız olması gibi her zaman “always_inline” kullanımı da mantıklı bir çözüm değildir. Çünkü uzun ve kompleks işlemler içeren fonksiyonların gövdesini almak çağırıldığı yerde başka problemlere yol açabilir. Ayrıca <a href="https://betterembsw.blogspot.com/2017/08/the-spaghetti-factor-software.html">spagetti factor</a> ünü fazlasıyla yükseltir. Fakat yerinde kullanıldığında oldukça faydalıdır. Şimdi biraz daha tartışmalı olan #pragma lara gelelim. <a href="https://indico.cern.ch/event/386232/sessions/159923/attachments/771039/1057534/always_inline_performance.pdf">Buradan</a> “always inline” kullanımına dair ilginç bir karşılaştırmaya göz atabilirsiniz.</p><p><strong>#pragma Kullanımı</strong></p><p>Konuya girmeden önce bazı karmaşalara açıklık getirmek gerekiyor. Chart(#) kullanımı genelde preprocess in bir parçasıdır. Yani derleme aşamasına gelmeden preprocess bitmiş olur ve derleme aşamasını çoğunlukla etkilemez. Yani preprocesste yapılan işlemler derlemeden bağımsızdır. Küçük bir örnek üzerinde görelim.</p><pre>#if DEBUG<br>#define PRINTER(x) \<br>    print(#x)<br>#elif RELEASE<br>#define PRINTER(x) \<br>    printf(#x)<br>#endif</pre><p>Yukarıdaki kodda bilerek ilk PRINTER tanımlamasında “print” yazılarak hata yapılmıştır. Fakat eğer RELEASE kısmı aktifse bu hata derleyici aşamasına bile gelemez. Yani preprocess te silinip derlenmeye alınmaz. Yani preprocess ve derleme işlemleri birbiri ile doğrudan bağımlı değildir. Fakat #pragma kullanımı bu yargıyı yıkar. #pragma kullanımı ile derleme aşamalarına müdahele etmek mümkündür. Bir kaç tane örnek üzerinde görelim.</p><pre>#pragma GCC push<br>#pragma GCC optimize(&quot;O0&quot;)<br>void Func()<br>{<br>    /* Some statements that is not supposed to be optimized */<br>}<br>#pragma GCC pop</pre><p>Yukarıdaki kodda görüldüğü üzere bir fonksiyon için optimizasyon seviyesi değiştirilmiştir. Burada başka bir optimizasyon da seçilebilirdi. “#pragma optimize” sayesinde kodun belirli kısımlarında optimizasyon seviyesi değiştirilebilinir. Başka bir örneğe bakalım.</p><pre>#pragma poison printf</pre><pre>void func()<br>{<br>printf(&quot;I am a function.\n&quot;);<br>}</pre><pre>void main()<br>{<br>    func1();</pre><pre>puts(&quot;Hello World\n&quot;);</pre><pre>}</pre><p>Yukarıdaki örnekte printf kullanımı yasaklanarak kullanıldığı durumlarda derleme aşamasında hata verecektir. Bazı standart fonksiyonların kullanımın tehlikeli olduğu durumlarda pragma poisondan yardım alınabilinir. Son bir tane örnekle yazıyı bitirelim.</p><pre>void VIP_Func()<br>{<br>    printf(&quot;I am VIP\n&quot;);</pre><pre>}</pre><pre>#pragma startup VIP_Func</pre><pre>void main()<br>{</pre><pre>printf(&quot;Hello World&quot;);</pre><pre>}</pre><p>Yukarıda gördüğünüz üzere pragma VIP_Func fonksiyonunu startup esnasında ya da diğer tabirle main e girmeden önce çağırmaktadır. Aynı sonuca start up dosyasını modifiye ederek te ulaşmak mümkündür. Fakat kısa zamanda çok iş yapılmak isteniyorsa bu pragmayı kullanmak mümkündür.</p><p><strong>Sonuç</strong></p><p>Attribute ve pragma kullanımı ile derleme aşaması kısmen kontrol altına alınabilinir. Bazı durumlarda müdahalelerde bulunma imkanı vardır. Yazıda ele alınmayan çok sayıda attribute ve pragma kullanımı da vardır. İsteyen araştırıp inceleyebilir.</p><p><strong>UYARI!!!</strong></p><p>Attribute ve bazı pragmalar standart C nin bir parçası değildir ve derleyiciye bağımlı bir işlemdir. Bazı derleyicilerde kullanımı farklı olabilir. Bu yüzden kullanmadan önce derleyicinin dökümanı incelenmelidir.</p><p>Sağlıklı günler dilerim…</p><p>Emre İRİŞ</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8d37824f0db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gömülü Yazılımda Yarış Durumları]]></title>
            <link>https://emreiris.medium.com/g%C3%B6m%C3%BCl%C3%BC-yaz%C4%B1l%C4%B1mda-yar%C4%B1%C5%9F-durumlar%C4%B1-2054a2b9b3d5?source=rss-fa890824224f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2054a2b9b3d5</guid>
            <category><![CDATA[synchronization]]></category>
            <category><![CDATA[embedded-software]]></category>
            <category><![CDATA[race-condition]]></category>
            <dc:creator><![CDATA[Emre İRİŞ]]></dc:creator>
            <pubDate>Sun, 07 Feb 2021 09:28:42 GMT</pubDate>
            <atom:updated>2021-02-08T06:44:01.298Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*D18brvIU8Bd5FS5Xb8BSzA.jpeg" /></figure><h3>Yarış Durumu nedir?</h3><p>Yazılım tasarımında birden çok görev tarafından paylaşılan kaynaklar bazı problemleri beraberinde getirmiştir. Bu problemlerden birisi de görevler arasındaki yarış durumudur. Özellikle kesme rutinlerinin bolca bulunduğu ve asenkron olarak kesme meydana gelen projelerde ortak kullanılan kaynaklara özellikle dikkat edilmelidir. Hele ki kesme içinde yapılan operasyonlar zaman alıyorsa yarış durumlarını göz etmek kaçınılmalıdır. Bahsi geçen kaynak bir değişken, obje, bayrak olabilir. Bir örnek üzerinden devam edelim.</p><pre>#include &lt;stdio.h&gt;</pre><pre>#include &lt;stdint.h&gt;</pre><pre>static int32_t resource = 20;</pre><pre>int main()<br>{<br>    Some_Initialization();</pre><pre>    while(1)<br>    {<br> <br>    }</pre><pre>}</pre><pre>void Interrupt_1( Interrupt_Typedef *handler)<br>{</pre><pre>/* Some statements that adds resource +10*/</pre><pre>}</pre><pre>void Interrupt_2(Interrupt_Typedef *handler)<br>{</pre><pre>/* Some statements that adds resource +5*/</pre><pre>}<br></pre><p>Yukarıdaki kod parçasında iki adet kesme fonksiyonunu ortak bir kaynağı kullandığı gözükmektedir. Şimdi bir senaryo düşünelim ve nelerin yanlış gidebileceğini görelim.</p><p>1-) Interrupt_1 tetiklenir ve rutine başlar.</p><p>2-) Bellekten resource değerini işlemci register ına yükler.</p><p>3-) resource değişkenine 10 ekler.</p><p>4-) Interrupt_1 rutini bitmeden Interrupt_2 de tetiklenir ve rutine başlar.</p><p>5-) Interrupt_2 resource değişkenini işlemci register ına yükler.</p><p>5-) Interrupt_2 resource değişkenine 5 ekler ve yerine yazar.</p><p>6-) Interrupt_1 resource değişkenin başlangıç haline 10 eklenmiş değişkeni yükler.</p><p>E ne oldu peki şimdi?</p><p>Aslında resource değişkenine 15 eklenmesi gerekirken sadece 10 eklendi. Çünkü Interrupt_1 rutini tamamlamadan Interrupt_2 araya girdi ve değişkeni modifiye etti. Fakat Interrupt_1 bu rutinden habersiz olduğu için başlangıç değeri üzerinden işlem yaptı. Sonuçta istenilen sonuca ulaşılamadı. Burada tahmin edilebilir bir sonuçta söz konusu değildir. Çünkü rutinlerin yer değiştirmesi de söz konusu olabilir.</p><h4>Alınabilecek Önlemler</h4><h4>1-) Bir Bayrakla Erişimi Yönetmek</h4><p>Akla gelebilecek ilk önlem bir bayrak vasıtasıyla kaynağa erişimi yönetmek olabilir. Örnek üzerinde göstermek gerekirse,</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdint.h&gt;</pre><pre>typedef enum<br>{<br>TASK_1_COMPLETED,<br>TASK_2_COMPLETED<br>}resource_control_flag_t;</pre><pre>static resource_control_flag_t resource_controller;</pre><pre>static int32_t resource = 20;</pre><pre>int main()<br>{<br>    Some_Initialization();</pre><pre>while(1)<br>    {<br> <br>    }</pre><pre>}</pre><pre>void Interrupt_1( Interrupt_Typedef *handler)<br>{</pre><pre>    if( resource_controller == TASK_2_COMPLETED )<br>    {<br>         /* Some statements that adds resource +10*/<br>         resource_controller = TASK_1_COMPLETED;<br>    }<br>}</pre><pre>void Interrupt_2(Interrupt_Typedef *handler)<br>{<br>    if( resource_controller == TASK_1_COMPLETED )<br>    {<br>         /* Some statements that adds resource +5*/<br>         resource_controller = TASK_2_COMPLETED;<br>    }</pre><pre>}</pre><p>Yukarıdaki kodda görüldüğü üzere resource controller bayrağı vasıtasıyla kaynağa erişim sırayla yapılmaktadır. Fakat burada da şöyle bir soru akla gelebilir, ya görevlerden bir tanesi diğerinden çok daha sık gerçekleşiyorsa? Bu durumda seyrek gerçekleşeni beklemek zorunda kalacaktır. Yani bu tasarımda aslında o kadar da verimli değildir.</p><h4>2-) Her Göreve Ayrı Bayrak Atamak</h4><p>İkinci çözüm olarak her göreve ayrı bayrak atarak bunu kontrol etmek olabilir. Örnek kod üzerinde gösterelim,</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdint.h&gt;</pre><pre>typedef enum<br>{<br>TASK_LOCKED,<br>TASK_FREE<br>}resource_control_flag_t;</pre><pre>static resource_control_flag_t task_1_controller, task_2_controller;</pre><pre>static int32_t resource = 20;</pre><pre>int main()<br>{<br>    Some_Initialization();</pre><pre>while(1)<br>    {<br> <br>    }</pre><pre>}</pre><pre>void Interrupt_1( Interrupt_Typedef *handler)<br>{<br>if( !( task_2_controller == TASK_LOCKED ) )<br>    {<br>         task_1_controller = TASK_LOCKED;<br>         /* Some statements that adds resource +10*/<br>         task_1_controller = TASK_FREE;<br>    }<br>}</pre><pre>void Interrupt_2(Interrupt_Typedef *handler)<br>{<br>if( !( task_1_controller == TASK_LOCKED ) )<br>    {<br>         task_2_controller = TASK_LOCKED;<br>         /* Some statements that adds resource +5*/<br>         task_2_controller = TASK_FREE;<br>    }<br>}</pre><p>Yukarıdaki kodda her görev için ayrı bayrak atadık ve görevlerden önceki görevin durumunu kontrol ettik. Bu durumda verimli gözükebilir. Fakat burada oluşabilecek bir durum dead-lock’a sebep olabilir. O da iki görevin de aynı anda bayrağı çekmesidir. Nadir oluşabilecek bir durum olsa da iki görevde kaynağa erişemeyeceğinden olumsuz sonuçlar doğurabilir. Gelelim en son ve verimli olan yönteme.</p><h4>3-) Dekker Algoritması</h4><p>Bu yöntem (ya da algoritma ne demek isterseniz ) ise bahsi geçen iki yöntemi birleştirerek görev süreçlerini kontrollü bir şekilde yönetmektedir. Örnek üzerinde görelim.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdint.h&gt;</pre><pre>typedef enum<br>{<br>TASK_1_COMPLETED,<br>TASK_2_COMPLETED<br>}task_control_flag_t;</pre><pre>typedef enum<br>{<br>TASK_LOCKED,<br>TASK_FREE<br>}resource_control_flag_t;</pre><pre>static resource_control_flag_t task_1_controller, task_2_controller;<br>task_control_flag_t task_control_flag;</pre><pre>static int32_t resource = 20;</pre><pre>int main()<br>{<br>    Some_Initialization();</pre><pre>while(1)<br>    {<br> <br>    }</pre><pre>}</pre><pre>void Interrupt_1( Interrupt_Typedef *handler)<br>{<br>if( (!( task_2_controller == TASK_LOCKED )) &amp;&amp;<br>    ( task_control_flag == TASK_2_COMPLETED ))<br>    {<br>         task_1_controller = TASK_LOCKED;<br>         /* Some statements that adds resource +10*/<br>         task_1_controller = TASK_FREE;<br>         task_control_flag = TASK_1_COMPLETED;<br>    }<br>}</pre><pre>void Interrupt_2(Interrupt_Typedef *handler)<br>{<br>if( (!( task_1_controller == TASK_LOCKED )) &amp;&amp;<br>    ( task_control_flag == TASK_1_COMPLETED ))<br>    {<br>         task_2_controller = TASK_LOCKED;<br>         /* Some statements that adds resource +5*/<br>         task_2_controller = TASK_FREE;<br>         task_control_flag = TASK_2_COMPLETED;<br>    }<br>}</pre><p>Yukarıdaki kodda ise fazladan bir bayrak daha ekleyerek hem kaynağa erişim iznini kontrol etmiş olduk hem de dead-lock oluşmasını engelledik. Burada görevler iki adet kesme olarak verilmiş olmasının sebebi “OS-less” bir sistem üzerinde göstermektir. Yukarıda anlatılan yöntemler işletim sisteminde dönen görevler içinde geçerlidir.</p><p>Sağlıklı günler dilerim :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2054a2b9b3d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>