<?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 Oleksandra Shershen on Medium]]></title>
        <description><![CDATA[Stories by Oleksandra Shershen on Medium]]></description>
        <link>https://medium.com/@oleksandra_shershen?source=rss-1d739931022b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6UMPQqPrNmS0v63e</url>
            <title>Stories by Oleksandra Shershen on Medium</title>
            <link>https://medium.com/@oleksandra_shershen?source=rss-1d739931022b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:06:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oleksandra_shershen/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[Function as a Service (FaaS): Enabling Efficient Serverless Computing]]></title>
            <link>https://medium.com/@oleksandra_shershen/function-as-a-service-faas-enabling-efficient-serverless-computing-e9c196f473d5?source=rss-1d739931022b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9c196f473d5</guid>
            <dc:creator><![CDATA[Oleksandra Shershen]]></dc:creator>
            <pubDate>Wed, 17 May 2023 12:10:34 GMT</pubDate>
            <atom:updated>2023-05-17T14:04:53.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pXSjmtfzTUSDwXmNCPVUEA.png" /></figure><p><strong>Function as a Service (FaaS)</strong> is a cloud computing paradigm that allows developers to execute code in the form of functions without worrying about server management. It is a key component of serverless computing, offering greater efficiency and scalability for modern applications. This article explores the concept of FaaS, its benefits, and its impact on the development and deployment of cloud-based applications.</p><h4>Understanding FaaS</h4><p>FaaS, also known as serverless functions, enables developers to focus solely on writing and deploying individual functions rather than managing the underlying infrastructure. In a FaaS model, functions are triggered by specific events or requests, such as HTTP requests, database events, or time-based triggers. The cloud provider dynamically allocates the necessary resources to execute the function, ensuring scalability and cost optimization.</p><h4>Benefits of FaaS</h4><ol><li><strong>Increased Efficiency:</strong> FaaS allows developers to break down applications into smaller, independent functions. This modularity enables better code management, promotes code reuse, and facilitates rapid development and deployment cycles.</li><li><strong>Auto-scaling:</strong> With FaaS, applications automatically scale based on demand. Functions are invoked and executed only when needed, resulting in optimal resource utilization and cost efficiency. The cloud provider manages the scaling process, freeing developers from capacity planning and infrastructure management.</li><li><strong>Pay-per-Use:</strong> FaaS follows a pay-as-you-go pricing model, where users are charged based on the actual function execution time and resource consumption. This approach offers cost savings, as users are not billed for idle resources, and eliminates the need for upfront infrastructure investments.</li><li><strong>Simplified Operations:</strong> FaaS abstracts away the complexity of server management, operating systems, and networking. Developers can focus on writing code and building application logic without worrying about infrastructure provisioning, monitoring, or maintenance.</li></ol><h4>Impact on Application Development</h4><p>FaaS has revolutionized the way applications are developed and deployed, offering several advantages to developers and businesses:</p><ol><li><strong>Agility and Innovation:</strong> FaaS enables rapid prototyping, iterative development, and quick deployment of new features. Developers can easily experiment, test ideas, and iterate on application functionality without the need for complex infrastructure setup.</li><li><strong>Scalability and Resilience: </strong>FaaS architectures inherently scale to handle varying workloads and ensure high availability. Applications can seamlessly handle sudden spikes in traffic or scale down during periods of low activity, all while maintaining performance and user experience.</li><li><strong>Event-driven Architectures: </strong>FaaS promotes event-driven architectures, where functions respond to specific events or triggers. This approach fosters loose coupling, modularity, and enables the integration of various services and systems.</li><li><strong>Cost Optimization: </strong>FaaS allows businesses to optimize costs by paying only for the actual usage of functions. Applications with sporadic or unpredictable workloads can benefit significantly from this pricing model.</li></ol><h4>Use Cases of FaaS</h4><ol><li><strong>Real-time Data Processing: </strong>FaaS is well-suited for handling real-time data processing tasks such as stream processing, data transformation, and event-driven analytics. Functions can be triggered by incoming data streams, enabling near-instantaneous processing and analysis.</li><li><strong>Web and Mobile Applications:</strong> FaaS is widely used in the development of web and mobile applications, particularly for handling serverless backends and executing specific functions in response to user actions. It allows developers to build scalable and responsive applications without managing servers or worrying about infrastructure scalability.</li><li><strong>IoT (Internet of Things):</strong> FaaS plays a crucial role in IoT applications by providing the necessary backend processing for sensor data, device communication, and event-driven automation. Functions can be triggered by IoT device events, enabling efficient and scalable processing of data from numerous connected devices.</li><li><strong>Chatbots and Virtual Assistants:</strong> FaaS enables the development of intelligent chatbots and virtual assistants. Functions can be used to process natural language queries, perform backend operations, and integrate with various APIs and services to provide real-time responses.</li></ol><h4>Challenges and Considerations</h4><ol><li><strong>Cold Start Latency:</strong> When a function is triggered for the first time or after a period of inactivity, it may experience a “cold start” delay due to the need to provision resources. This latency can impact real-time or highly responsive applications. However, various optimization techniques and strategies, such as pre-warming function instances, can mitigate this issue.</li><li><strong>Vendor Lock-In:</strong> Adopting FaaS may result in vendor lock-in, as each cloud provider offers its own FaaS implementation and ecosystem. It is essential to consider portability and the availability of migration strategies when selecting a FaaS provider.</li><li><strong>Debugging and Monitoring:</strong> Debugging and monitoring FaaS applications can be more challenging compared to traditional server-based architectures. Tools and frameworks specifically designed for serverless environments are necessary to effectively troubleshoot and monitor function execution.</li><li><strong>Resource Limitations:</strong> FaaS imposes certain resource limits, such as maximum execution time and memory allocation per function instance. Developers need to be aware of these limitations and design their applications accordingly to avoid performance issues or function timeouts.</li></ol><h4>Conclusion</h4><p>Function as a Service (FaaS) provides developers with a powerful and efficient way to build and deploy applications in a serverless environment. Its benefits, such as increased efficiency, auto-scaling, pay-per-use pricing, and simplified operations, make it an attractive choice for modern application development. With various use cases across industries and the ability to handle real-time data processing, FaaS continues to drive innovation and reshape the cloud computing landscape. However, considerations such as cold start latency, vendor lock-in, and resource limitations should be taken into account when adopting FaaS. By leveraging the strengths of FaaS and addressing its challenges, businesses can unlock the full potential of serverless computing and accelerate their digital transformation journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9c196f473d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harnessing the Power of JNI: Seamless Integration of Java and C++ for Enhanced Performance]]></title>
            <link>https://medium.com/@oleksandra_shershen/harnessing-the-power-of-jni-seamless-integration-of-java-and-c-for-enhanced-performance-d1a6ac4f4a77?source=rss-1d739931022b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1a6ac4f4a77</guid>
            <dc:creator><![CDATA[Oleksandra Shershen]]></dc:creator>
            <pubDate>Mon, 15 May 2023 20:28:50 GMT</pubDate>
            <atom:updated>2023-05-18T09:20:35.391Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5t9gd-o4pL7dFiBqxUemQ.png" /></figure><p>JNI stands for Java Native Interface. It is a framework that allows Java code to interact with and invoke native code written in other programming languages, such as C or C++.</p><h4>Introduction</h4><p>Java and C++ are two versatile programming languages, each with its own strengths and areas of specialization. While Java offers platform independence and strong object-oriented capabilities, C++ provides low-level control and high performance. In certain scenarios, developers may find themselves needing to combine the best of both worlds by integrating Java and C++ code within a single application. Enter the Java Native Interface (JNI), a powerful framework that acts as a bridge between Java and C++, enabling seamless communication and collaboration. In this article, we will explore JNI in-depth, providing explanations and concrete code examples to demonstrate its usage and benefits.</p><h4>Understanding JNI</h4><p>The Java Native Interface (JNI) is a programming framework that facilitates interoperability between Java and code written in other languages, specifically C and C++. It allows Java applications to invoke and be invoked by native code, unlocking the potential for incorporating existing native libraries, leveraging performance-critical algorithms, or interacting with hardware devices.</p><h4>JNI Workflow</h4><p>To comprehend how JNI operates, let’s walk through its typical workflow:</p><ol><li><strong>Writing the Native Code: </strong>Begin by crafting the native code in C or C++. This code may encompass custom functionality, performance-critical computations, or interactions with platform-specific features.</li><li><strong>Compiling the Native Code:</strong> Compile the native code using a C/C++ compiler to generate a shared library (DLL/SO) that corresponds to the target platform.</li><li><strong>Creating the Java Native Interface:</strong> Define a Java class that serves as the bridge between the Java code and the native code. This class contains native method declarations that correspond to the functions implemented in the native code.</li><li><strong>Generating the Java Header File:</strong> Employ the Java Native Development Kit (JDK) to generate a C/C++ header file (.h). This header file includes the function prototypes for the native methods declared in the Java class.</li><li><strong>Implementing the Native Methods:</strong> In the generated C/C++ header file, implement the native methods declared in the Java class. These implementations provide the actual functionality that will be invoked from Java.</li><li><strong>Loading the Native Library:</strong> In the Java code, load the native library using the System.loadLibrary() method. This ensures that the native methods can be accessed and executed.</li><li><strong>Invoking Native Methods:</strong> Finally, invoke the native methods from the Java code, and they will execute the corresponding native code, enabling seamless communication and data exchange between Java and C++.</li></ol><h4>How does it work?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vdaVQUorAnS14H1G.png" /></figure><h4>Primitive Types and Native Equivalents in JNI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*hdcrQTW3uci9m4gB3SRR8g.png" /></figure><h4>How is the name of a C function that implements a Java method formed?</h4><p>The name of a C function that implements a Java method in JNI is formed by concatenating the Java class name, the Java method name, and optionally the Java method signature. This process follows a specific naming convention.</p><p>The general format for forming the C function name is as follows:</p><pre>Java_[package_name]_[class_name]_[method_name]</pre><p>In this format:</p><ul><li>[package_name] represents the package name of the Java class, with periods replaced by underscores.</li><li>[class_name] represents the simple name of the Java class.</li><li>[method_name] represents the name of the Java method.</li></ul><p>If there are multiple methods with the same name but different parameter signatures within a class, the Java method signature is appended to the C function name. The signature is formed by concatenating the letter representing the return type, followed by the letters representing the parameter types.</p><p>For example, consider a Java class named com.example.MyClass with a method named addNumbers that takes two int parameters and returns an int. The corresponding C function name would be:</p><pre>Java_com_example_MyClass_addNumbers</pre><p>If the method signature needs to be included, it would be added to the C function name as follows:</p><pre>Java_com_example_MyClass_addNumbers__II</pre><p>Note that the signatures for primitive types follow specific conventions, where I represents int, J represents long, F represents float, D represents double, Z represents boolean, C represents char, S represents short, and B represents byte.</p><h4>Example: Matrix Multiplication with JNI</h4><p>To illustrate the power and practicality of JNI, let’s delve into a more intricate example. We will develop a Java application that performs matrix multiplication by leveraging a native C++ implementation for enhanced performance.</p><ol><li><strong>Native Code (matrix_operations.cpp):</strong></li></ol><pre>#include &lt;jni.h&gt;<br><br>extern &quot;C&quot; {<br><br>JNIEXPORT jobject JNICALL Java_com_example_MatrixOperations_multiplyMatrix(JNIEnv* env, jobject obj, jobjectArray matrix1, jobjectArray matrix2) {<br>    // Get the dimensions of the matrices<br>    jint rows1 = env-&gt;GetArrayLength(matrix1);<br>    jint cols1 = env-&gt;GetArrayLength(static_cast&lt;jobjectArray&gt;(env-&gt;GetObjectArrayElement(matrix1, 0)));<br><br>    jint rows2 = env-&gt;GetArrayLength(matrix2);<br>    jint cols2 = env-&gt;GetArrayLength(static_cast&lt;jobjectArray&gt;(env-&gt;GetObjectArrayElement(matrix2, 0)));<br><br>    // Create a new matrix to store the result<br>    jobjectArray resultMatrix = env-&gt;NewObjectArray(rows1, env-&gt;FindClass(&quot;[I&quot;), nullptr);<br><br>    // Perform matrix multiplication<br>    for (jint i = 0; i &lt; rows1; ++i) {<br>        jintArray row = env-&gt;NewIntArray(cols2);<br>        jint* rowData = env-&gt;GetIntArrayElements(row, nullptr);<br><br>        for (jint j = 0; j &lt; cols2; ++j) {<br>            jint sum = 0;<br><br>            for (jint k = 0; k &lt; cols1; ++k) {<br>                jint value1 = env-&gt;GetIntArrayElements(static_cast&lt;jintArray&gt;(env-&gt;GetObjectArrayElement(matrix1, i)), nullptr)[k];<br>                jint value2 = env-&gt;GetIntArrayElements(static_cast&lt;jintArray&gt;(env-&gt;GetObjectArrayElement(matrix2, k)), nullptr)[j];<br>                sum += value1 * value2;<br>            }<br><br>            rowData[j] = sum;<br>        }<br><br>        env-&gt;SetObjectArrayElement(resultMatrix, i, row);<br>        env-&gt;ReleaseIntArrayElements(row, rowData, 0);<br>    }<br><br>    return resultMatrix;<br> }<br><br>}</pre><p>2.<strong> Java Native Interface (MatrixOperations.java):</strong></p><pre>public class MatrixOperations {<br>    static {<br>        System.loadLibrary(&quot;matrix_operations&quot;);<br>    }<br><br>    private native int[][] multiplyMatrix(int[][] matrix1, int[][] matrix2);<br><br>    public static void main(String[] args) {<br>        MatrixOperations operations = new MatrixOperations();<br><br>        // Define two matrices<br>        int[][] matrix1 = {{1, 2}, {3, 4}};<br>        int[][] matrix2 = {{5, 6}, {7, 8}};<br><br>        // Perform matrix multiplication using the native code<br>        int[][] resultMatrix = operations.multiplyMatrix(matrix1, matrix2);<br><br>        // Display the result<br>        for (int[] row : resultMatrix) {<br>            for (int value : row) {<br>                System.out.print(value + &quot; &quot;);<br>            }<br>            System.out.println();<br>        }<br>    }<br>}</pre><p><strong>3. Compiling and Running:</strong></p><ul><li>Compile the native code:</li></ul><pre>g++ -c -fPIC -I&quot;$JAVA_HOME/include&quot; -I&quot;$JAVA_HOME/include/linux&quot; matrix_operations.cpp -o matrix_operations.o</pre><p>The given command is a compilation command using the g++ compiler to compile a C++ source file named matrix_operations.cpp into an object file named matrix_operations.o. Here&#39;s a short explanation of each component:</p><p>g++: The GNU C++ compiler.</p><p>-c: Compile the source file without linking, generating an object file.</p><p>-fPIC: Generate position-independent code, allowing the compiled code to be loaded and executed at any memory address. This is necessary for creating shared libraries or using JNI.</p><p>-I&quot;$JAVA_HOME/include&quot;: Include the directory containing JNI header files for Java.</p><p>-I&quot;$JAVA_HOME/include/linux&quot;: Include the directory containing Linux-specific JNI header files.</p><p>matrix_operations.cpp: The source file to be compiled, containing C++ code for matrix operations.</p><p>-o matrix_operations.o: Specify the output file name as matrix_operations.o, where the compiled code will be stored.</p><ul><li>Link the shared library:</li></ul><pre>g++ -shared -o libmatrix_operations.so matrix_operations.o</pre><p>Here’s a short explanation of each component:</p><p>-shared: Create a shared library instead of an executable. Shared libraries allow code and data to be dynamically linked by multiple programs.</p><p>-o libmatrix_operations.so: Specify the output file name as libmatrix_operations.so, where lib is a common convention for shared library names, and .so is the file extension for shared libraries on Unix-like systems.</p><p>matrix_operations.o: The object file containing the compiled code for matrix operations.</p><p>The command uses the g++ compiler as the linker to take the object file matrix_operations.o and generate a shared library named libmatrix_operations.so. This shared library can be dynamically linked with other programs, enabling them to access the functions and symbols defined in matrix_operations.o. The resulting shared library file can be loaded and used by programs, including Java applications through JNI, to leverage the matrix operations implemented in the C++ code.</p><ul><li>Compile the Java program:</li></ul><pre>javac MatrixOperations.java</pre><p>The command instructs the javac compiler to read the MatrixOperations.java file and generate the corresponding bytecode file MatrixOperations.class. The .class file contains the compiled Java code and can be executed by the JVM.</p><ul><li>Run the Java program:</li></ul><pre>java MatrixOperations</pre><p>In this example, we have a Java class MatrixOperations that contains a native method multiplyMatrix. This method takes two 2-dimensional arrays (matrix1 and matrix2) as input and performs matrix multiplication using native code written in C++. The native code uses JNI to access and manipulate the arrays. It calculates the dimensions of the input matrices, creates a new matrix to store the result, and performs the matrix multiplication operation.</p><p>In the Java code, we create an instance of MatrixOperations and define two matrices matrix1 and matrix2. We then invoke the native method multiplyMatrix to perform matrix multiplication using the native code. The resulting matrix is stored in resultMatrix, and we display the result by iterating over the rows and columns.</p><h4>Conclusion</h4><p>JNI provides a powerful mechanism for integrating Java and C++ code, enabling developers to leverage the strengths of both languages in a seamless manner. This article explored JNI, its workflow, and provided an example showcasing matrix multiplication using JNI. By using JNI, developers can enhance performance, access native libraries, and utilize low-level capabilities while maintaining the portability and flexibility of Java. With JNI, the boundaries between Java and C++ can be blurred, empowering developers to build high-performance applications that harness the best of both worlds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1a6ac4f4a77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID principles: implementation and examples in C++]]></title>
            <link>https://medium.com/@oleksandra_shershen/solid-principles-implementation-and-examples-in-c-99f0d7e3e868?source=rss-1d739931022b------2</link>
            <guid isPermaLink="false">https://medium.com/p/99f0d7e3e868</guid>
            <dc:creator><![CDATA[Oleksandra Shershen]]></dc:creator>
            <pubDate>Sat, 29 Apr 2023 12:45:53 GMT</pubDate>
            <atom:updated>2023-04-29T13:18:26.493Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hLqRYSuWEaH9PuQuJufL1A.png" /></figure><p>SOLID principles are widely adopted by software developers as a set of guidelines for designing maintainable and extensible code. By following these principles, developers can create software that is easier to understand, modify, and test. In this article, we discussed each of the SOLID principles and provided examples of how they can be implemented in C++.</p><h4>Introduction</h4><p>SOLID principles are a set of guidelines or best practices for object-oriented programming that help to create software that is more maintainable, flexible, and scalable. The term “SOLID” is an acronym for five different principles, each of which focuses on a different aspect of software development:</p><p><strong>S</strong> — Single Responsibility Principle (SRP)<br><strong>O</strong> — Open-Closed Principle (OCP)<br><strong>L</strong> — Liskov Substitution Principle (LSP)<br><strong>I</strong> — Interface Segregation Principle (ISP)<br><strong>D</strong> — Dependency Inversion Principle (DIP)</p><h4>Single Responsibility Principle (SRP)</h4><p>The <strong>Single Responsibility Principle (SRP)</strong> is one of the five SOLID principles of object-oriented design. It states that a class should have only one responsibility, which means it should have only one reason to change. This principle helps in reducing the coupling between classes and makes the code more maintainable and scalable.</p><p>In C++, SRP can be implemented by dividing the responsibilities of a class into smaller, more focused classes. Each class should be responsible for only one task and should have no other reason to change. This makes the code easier to understand, modify and test.</p><p>Let’s consider an example of a class named Customer which is responsible for calculating the final bill of a customer. In its current form, the Customer class has several responsibilities, such as maintaining the customer details, calculating the final bill, and generating an invoice.</p><pre>class Customer {<br>private:<br>  string name;<br>  int id;<br>  vector&lt;Item&gt; items;<br>  float totalAmount;<br>public:<br>  void setName(string name);<br>  string getName();<br>  void setId(int id);<br>  int getId();<br>  void addItem(Item item);<br>  void removeItem(Item item);<br>  float calculateTotalAmount();<br>  string generateInvoice();<br>};</pre><p>As we can see, the Customer class is responsible for multiple tasks, such as maintaining customer details, calculating the final bill, and generating an invoice. This violates the Single Responsibility Principle, as the class has multiple reasons to change. For instance, if the calculation of the final bill is changed, then the Customer class needs to be modified, even though it is not related to the customer details or the generation of invoices.</p><p>To implement SRP, we can create separate classes for each of these responsibilities. For example, we can create a CustomerDetails class to handle the customer details, a BillingCalculator class to calculate the final bill, and an InvoiceGenerator class to generate the invoice.</p><pre>class CustomerDetails {<br>private:<br>  string name;<br>  int id;<br>public:<br>  void setName(string name);<br>  string getName();<br>  void setId(int id);<br>  int getId();<br>};<br><br>class BillingCalculator {<br>private:<br>  vector&lt;Item&gt; items;<br>public:<br>  void addItem(Item item);<br>  void removeItem(Item item);<br>  float calculateTotalAmount();<br>};<br><br>class InvoiceGenerator {<br>public:<br>  string generateInvoice(CustomerDetails customerDetails, BillingCalculator billingCalculator);<br>};</pre><p>By dividing the responsibilities of the Customer class into smaller, more focused classes, each class has only one responsibility, which makes the code more maintainable and scalable. If any changes are required in any of these classes, only that class needs to be modified, rather than the entire Customer class. This leads to cleaner and more maintainable code, which is easier to understand, modify and test.</p><h4>Open-Closed Principle (OCP)</h4><p>The <strong>Open-Closed Principle (OCP)</strong> is one of the five SOLID principles of object-oriented design. It states that a class should be open for extension but closed for modification. This principle helps in making the code more maintainable and flexible.</p><p>In C++, OCP can be implemented by creating classes that can be extended by adding new functionality without modifying the existing code. This is achieved by using inheritance, polymorphism, and interfaces. By following this principle, we can make the code more modular and less prone to bugs.</p><p>Let’s consider an example of a Shape class hierarchy that includes different types of shapes, such as Rectangle, Circle, and Triangle. Each shape has a different area calculation method.</p><pre>class Shape {<br>public:<br>  virtual double area() = 0;<br>};<br><br>class Rectangle : public Shape {<br>private:<br>  double width;<br>  double height;<br>public:<br>  Rectangle(double width, double height);<br>  double area() override;<br>};<br><br>class Circle : public Shape {<br>private:<br>  double radius;<br>public:<br>  Circle(double radius);<br>  double area() override;<br>};<br><br>class Triangle : public Shape {<br>private:<br>  double base;<br>  double height;<br>public:<br>  Triangle(double base, double height);<br>  double area() override;<br>};</pre><p>Now, let’s suppose that we want to add a new shape, such as a Square, to our hierarchy. One way to do this would be to modify the Shape class hierarchy by adding a new Square class. However, this would violate the OCP, as we would be modifying the existing code.</p><p>Instead, we can extend the Shape class hierarchy by creating a new class that inherits from the Shape class and implements the area() method. In this way, we are adding new functionality without modifying the existing code.</p><pre>class Square : public Shape {<br>private:<br>  double side;<br>public:<br>  Square(double side);<br>  double area() override;<br>};</pre><p>Now, we can create objects of the Square class and calculate their areas using the area() method without modifying the existing code.</p><pre>Square square(5.0);<br>double squareArea = square.area(); // returns 25.0</pre><p>By following the Open-Closed Principle, we can create code that is more maintainable, flexible, and easier to extend. This allows us to add new functionality to our code without modifying the existing code, which reduces the risk of introducing bugs and makes the code more modular.</p><h4>Liskov Substitution Principle (LSP)</h4><p>The <strong>Liskov Substitution Principle (LSP)</strong> is one of the SOLID principles of object-oriented design. It states that objects of a superclass should be able to be replaced with objects of a subclass without affecting the correctness of the program. In other words, a subclass should be able to be substituted for its parent class without causing any errors or unexpected behavior.</p><p>In C++, LSP can be implemented by ensuring that subclasses adhere to the same interface and behavior as their parent class. This allows us to use a subclass object wherever we would normally use a parent class object.</p><p>Let’s consider an example of a Bird class hierarchy that includes different types of birds, such as Eagle, Penguin, and Ostrich. Each bird has a different ability to fly.</p><pre>class Bird {<br>public:<br>  virtual void fly() = 0;<br>};<br><br>class Eagle : public Bird {<br>public:<br>  void fly() override;<br>};<br><br>class Penguin : public Bird {<br>public:<br>  void fly() override;<br>};<br><br>class Ostrich : public Bird {<br>public:<br>  void fly() override;<br>};</pre><p>Now, let’s suppose that we have a function that takes a Bird object and makes it fly.</p><pre>void makeBirdFly(Bird&amp; bird) {<br>  bird.fly();<br>}</pre><p>According to the LSP, we should be able to pass any Bird subclass object to this function without affecting the correctness of the program. For example, we should be able to pass an Eagle object, a Penguin object, or an Ostrich object to this function.</p><pre>Eagle eagle;<br>Penguin penguin;<br>Ostrich ostrich;<br><br>makeBirdFly(eagle); // okay, eagle can fly<br>makeBirdFly(penguin); // error, penguin can&#39;t fly<br>makeBirdFly(ostrich); // error, ostrich can&#39;t fly</pre><p>As we can see, passing a Penguin or an Ostrich object to this function would result in an error because they cannot fly. Therefore, these classes do not adhere to the same behavior as their parent class, Bird, and violate the LSP.</p><p>By following the Liskov Substitution Principle, we can create code that is more modular and flexible. This allows us to use subclasses interchangeably with their parent class, which reduces the complexity of our code and makes it easier to maintain.</p><h4>Interface Segregation Principle (ISP)</h4><p>The <strong>Interface Segregation Principle (ISP) </strong>is one of the SOLID principles of object-oriented design. It states that a client should not be forced to depend on interfaces that it does not use. In other words, a class should not have to implement methods that it does not need.</p><p>In C++, ISP can be implemented by breaking down larger interfaces into smaller, more specific interfaces. This allows clients to only depend on the specific methods they need, rather than being forced to implement unnecessary methods.</p><p>Let’s consider an example of a Printer class that can print documents in different formats, such as PDF, HTML, and plain text. We could define a single interface for this class that includes all possible methods, such as printPDF(), printHTML(), and printPlainText().</p><pre>class Printer {<br>public:<br>  virtual void printPDF() = 0;<br>  virtual void printHTML() = 0;<br>  virtual void printPlainText() = 0;<br>};</pre><p>However, this interface may not be suitable for all clients. For example, a client that only needs to print plain text documents may not want to implement the printPDF() and printHTML() methods.</p><p>To adhere to the ISP, we could break down the Printer interface into smaller interfaces that are specific to each document format.</p><pre>class Printable {<br>public:<br>  virtual void print() = 0;<br>};<br><br>class PDFPrintable : public Printable {<br>public:<br>  void print() override;<br>};<br><br>class HTMLPrintable : public Printable {<br>public:<br>  void print() override;<br>};<br><br>class PlainTextPrintable : public Printable {<br>public:<br>  void print() override;<br>};</pre><p>Now, clients can depend on the specific interfaces they need. For example, a client that only needs to print plain text documents can depend on the PlainTextPrintable interface.</p><pre>class PlainTextPrinter {<br>public:<br>  void print(PlainTextPrintable&amp; document) {<br>    document.print();<br>  }<br>};</pre><p>By adhering to the Interface Segregation Principle, we can create more flexible and reusable code that is easier to maintain. Clients can depend on smaller interfaces that are specific to their needs, rather than being forced to implement unnecessary methods.</p><h4>Dependency Inversion Principle (DIP)</h4><p>The <strong>Dependency Inversion Principle (DIP)</strong> is one of the SOLID principles of object-oriented design. It states that high-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.</p><p>In C++, DIP can be implemented by using interfaces or abstract classes to decouple high-level modules from low-level modules. This allows for more flexibility in the design, as different implementations of the same interface can be easily swapped out without affecting the overall structure of the program.</p><p>Let’s consider an example of a Database class that stores user information. We could define a concrete implementation of this class that depends on the MySQLConnector class.</p><pre>class MySQLConnector {<br>public:<br>  void connect();<br>  void query(const std::string&amp; query);<br>};<br><br>class Database {<br>public:<br>  void addUser(const std::string&amp; name, const std::string&amp; email) {<br>    MySQLConnector connector;<br>    connector.connect();<br>    std::string query = &quot;INSERT INTO users (name, email) VALUES (&#39;&quot; + name + &quot;&#39;, &#39;&quot; + email + &quot;&#39;)&quot;;<br>    connector.query(query);<br>  }<br>};</pre><p>This implementation violates the Dependency Inversion Principle, as the Database class depends on the low-level MySQLConnector class. If we were to switch to a different database system, we would need to modify the Database class to use a different connector.</p><p>To adhere to the DIP, we could define an abstract interface for the database connector, and have the Database class depend on this interface instead of a concrete implementation.</p><pre>class IDatabaseConnector {<br>public:<br>  virtual void connect() = 0;<br>  virtual void query(const std::string&amp; query) = 0;<br>};<br><br>class MySQLConnector : public IDatabaseConnector {<br>public:<br>  void connect() override;<br>  void query(const std::string&amp; query) override;<br>};<br><br>class Database {<br>public:<br>  Database(IDatabaseConnector&amp; connector) : connector_(connector) {}<br><br>  void addUser(const std::string&amp; name, const std::string&amp; email) {<br>    connector_.connect();<br>    std::string query = &quot;INSERT INTO users (name, email) VALUES (&#39;&quot; + name + &quot;&#39;, &#39;&quot; + email + &quot;&#39;)&quot;;<br>    connector_.query(query);<br>  }<br><br>private:<br>  IDatabaseConnector&amp; connector_;<br>};</pre><p>Now, the Database class depends on the abstract IDatabaseConnector interface instead of a concrete implementation. We can create different implementations of the IDatabaseConnector interface for different database systems, and easily swap them out without modifying the Database class.</p><pre>class PostgreSQLConnector : public IDatabaseConnector {<br>public:<br>  void connect() override;<br>  void query(const std::string&amp; query) override;<br>};<br><br>int main() {<br>  PostgreSQLConnector postgresConnector;<br>  Database db(postgresConnector);<br><br>  db.addUser(&quot;John Doe&quot;, &quot;john.doe@example.com&quot;);<br>}</pre><p>By adhering to the Dependency Inversion Principle, we can create more flexible and maintainable code that is easier to extend and modify. High-level modules depend on abstractions, not low-level details, which allows for easier substitution of implementations.</p><h4>Conclusion</h4><p>In conclusion, SOLID principles provide a framework for writing clean and maintainable code. As a C++ developer, it’s important to understand each of these principles and how to apply them to your code. By implementing SOLID principles in your codebase, you can ensure that your software is easy to understand, modify, and test.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99f0d7e3e868" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Part 1] Computations at Compile-Time: Exploring consteval and constinit in C++20]]></title>
            <link>https://medium.com/@oleksandra_shershen/part-1-computations-at-compile-time-exploring-consteval-and-constinit-in-c-20-170b09b5cc51?source=rss-1d739931022b------2</link>
            <guid isPermaLink="false">https://medium.com/p/170b09b5cc51</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[cpp20]]></category>
            <category><![CDATA[const]]></category>
            <category><![CDATA[modern-cpp]]></category>
            <category><![CDATA[cpplus]]></category>
            <dc:creator><![CDATA[Oleksandra Shershen]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 15:46:39 GMT</pubDate>
            <atom:updated>2023-04-29T13:34:11.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mn6RU920Nltqhp7sEtpr1A.png" /></figure><p>C++20 has introduced a new set of features that allow computations at compile-time. These features, called consteval and constinit, offer many benefits to developers, including improved performance, reduced code complexity, and increased flexibility.</p><p>Whether you are a seasoned C++ developer or just starting out, this article will provide valuable insights into the power and potential of consteval and constinit in C++20.</p><h4>Table of Contents :</h4><ul><li><a href="#b136">Introduction</a></li><li><a href="#20c8">consteval specifier</a></li><li><a href="#e048">constinit specifier</a></li><li><a href="#82c0">consteval VS constinit</a></li><li><a href="#b0c9">Conclusion</a></li></ul><h4><strong>Introduction</strong></h4><p>In this article, we will explore consteval and constinit in C++20, and how they can be used to improve the efficiency and quality of C++ programs. We will examine the syntax and semantics of these features, as well as practical examples of how they can be applied in real-world scenarios.</p><h4><strong>consteval specifier</strong></h4><p>Key word consteval — specifies that a function is an immediate function, that is, every call to the function must produce a compile-time constant.</p><p>consteval is a C++20 specifier that allows a function to be evaluated at compile time. It specifies that a function must be evaluated during compilation and can only contain a set of constant expressions. This specifier allows for faster code execution and can also be used for various compile-time computations, such as string parsing, mathematical computations, or generating data structures.</p><blockquote><strong><em>Best practice</em></strong></blockquote><blockquote><em>Use </em><em>consteval if you have a function that must run at compile-time for some reason (e.g. performance).</em></blockquote><p>Here’s example of using consteval in C++ to perform compile-time parsing of a string into a numerical value:</p><pre>#include &lt;iostream&gt;<br>#include &lt;limits&gt;<br><br>constexpr bool isDigit(char ch) {<br>    return ch &gt;= &#39;0&#39; &amp;&amp; ch &lt;= &#39;9&#39;;<br>}<br><br>consteval int parseInt(const char* str, std::size_t size) {<br>    int result = 0;<br>    bool negative = false;<br><br>    if (*str == &#39;-&#39;) {<br>        negative = true;<br>        ++str;<br>        --size;<br>    }<br><br>    for (std::size_t i = 0; i &lt; size; ++i) {<br>        if (!isDigit(str[i])) {<br>            return std::numeric_limits&lt;int&gt;::quiet_NaN();<br>        }<br>        result = result * 10 + (str[i] - &#39;0&#39;);<br>    }<br><br>    return negative ? -result : result;<br>}<br><br>int main() {<br>    constexpr char str[] = &quot;-12345&quot;;<br>    constexpr auto value = parseInt(str, sizeof(str) - 1);<br>    static_assert(value == -12345, &quot;value does not match&quot;);<br>    return 0;<br>}</pre><p>Here, we define two functions: isDigit() and parseInt(). isDigit() is a helper function that returns true if a character is a digit between ‘0&#39; and &#39;9&#39;. parseInt() is a consteval function that takes a string and its length as input and returns its integer value.</p><p>In main, we use parseInt() to parse the string &quot;-12345&quot; into its integer value. Since parseInt() is evaluated at compile time, its result is known at compile time and does not need to be computed at run time. The result is then checked using a static assertion to ensure that it matches the expected value.</p><p>Here it might be useful to understand what an <strong>immediate function</strong> is. Cpp reference page lists out in detail on when a function qualifies to be an immediate function. A summary of those requirements are below:</p><ul><li>it must not be a <a href="https://en.cppreference.com/w/cpp/language/coroutines">coroutine</a></li><li>it must not have a throw statement in its body</li><li>it must not have goto statement (which is seldom used by anyone these days) or a label statement except for case and default</li><li>it’s parameters as well as return type must be a <a href="https://en.cppreference.com/w/cpp/named_req/LiteralType">literal type</a> or in short a type that can be evaluated at compile time (such as all types that could be used in constexpr context).</li></ul><pre>#include &lt;iostream&gt;<br><br>consteval int sqr(int n) {<br>    return n*n;<br>}<br>constexpr int r = sqr(100); // OK<br><br>int x = 100;<br>int r2 = sqr(x);            // Error: Call does not produce a constant<br><br>consteval int sqrsqr(int n) {<br>    return sqr(sqr(n));     // Not a constant expression at this point, but OK<br>}<br><br>constexpr int dblsqr(int n) {<br>    return 2 * sqr(n);        // Error: Enclosing function is not consteval<br>                              // and sqr(n) is not a constant<br>}</pre><p>An identifier expression that denotes an immediate function may only appear within a subexpression of an immediate invocation or within an immediate function context (i.e. a context mentioned above, in which a call to an immediate function needs not to be a constant expression). A pointer or reference to an immediate function can be taken but cannot escape constant expression evaluation:</p><pre>consteval int f() { return 42; }<br>consteval auto g() { return &amp;f; }<br>consteval int h(int (*p)() = g()) { return p(); }<br>constexpr int r = h();  // OK<br>constexpr auto e = g(); // ill-formed: a pointer to an immediate function is<br>                        // not a permitted result of a constant expression</pre><h4>constinit specifier</h4><p>Key word constinit— asserts that a variable has static initialization, i.e. <a href="https://en.cppreference.com/w/cpp/language/zero_initialization">zero initialization</a> and <a href="https://en.cppreference.com/w/cpp/language/constant_initialization">constant initialization</a>, otherwise the program is ill-formed.</p><p>constinit is a C++20 specifier that allows a variable to be initialized at compile time or at dynamic initialization, but not at runtime. It ensures that the variable is initialized exactly once, and its value cannot be changed after initialization.</p><p>The constinit specifier is used to declare static and thread-local variables that are guaranteed to be initialized with a constant expression. Unlike constexpr variables, which must be evaluated at compile time, constinit variables can also be initialized at dynamic initialization. However, their initialization must be performed before any non-constant initialization occurs.</p><p>The constinitcan be applied to <strong>variables that have static</strong> or <strong>thread-local storage duration</strong>.</p><p>→ <strong>Variables with static storage duration</strong> are initialized once when the program starts and retain their values throughout the entire lifetime of the program.</p><p>Here’s an example of using constinit specifier with variables of static storage duration in C++20:</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T&gt;<br>class MyClass {<br>public:<br>    static constinit int staticValue;<br>};<br><br>template &lt;typename T&gt;<br>constinit int MyClass&lt;T&gt;::staticValue = 42;<br><br>int main() {<br>    MyClass&lt;int&gt; myObj1;<br>    MyClass&lt;std::string&gt; myObj2;<br>    std::cout &lt;&lt; &quot;myObj1.staticValue = &quot; &lt;&lt; myObj1.staticValue &lt;&lt; std::endl;<br>    std::cout &lt;&lt; &quot;myObj2.staticValue = &quot; &lt;&lt; myObj2.staticValue &lt;&lt; std::endl;<br>    return 0;<br>}<br><br>//Output<br>//myObj1.staticValue = 42<br>//myObj2.staticValue = 42</pre><p>Here, MyClass is a class template with a static data member staticValue of type int. staticValue is initialized with the value 42 using constinit specifier.</p><p>When the program is executed, main() creates two objects myObj1 and myObj2 of type MyClass&lt;int&gt; and MyClass&lt;std::string&gt;, respectively. It then prints the values of the static data members staticValue for each object. Since staticValue is initialized with the same constant expression for both objects, myObj1.staticValue and myObj2.staticValue are both 42.</p><p>→ <strong>Thread-local variables</strong> have a separate instance for each thread, and their values are retained throughout the lifetime of the thread.</p><p>Here’s an example of using constinit with a thread-local variable:</p><pre>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br>#include &lt;array&gt;<br><br>class MyThreadLocalClass {<br>public:<br>    MyThreadLocalClass() = default;<br><br>    void printThreadId() {<br>        std::cout &lt;&lt; &quot;Thread ID: &quot; &lt;&lt; std::this_thread::get_id() &lt;&lt; std::endl;<br>    }<br>};<br><br>thread_local constinit std::array&lt;MyThreadLocalClass, 1&gt; myThreadLocalObjects{};<br><br>int main() {<br>    std::thread t1([]{<br>        std::cout &lt;&lt; &quot;Thread 1 started&quot; &lt;&lt; std::endl;<br>        myThreadLocalObjects[0].printThreadId();<br>        std::this_thread::sleep_for(std::chrono::seconds(1));<br>        std::cout &lt;&lt; &quot;Thread 1 ended&quot; &lt;&lt; std::endl;<br>    });<br><br>    std::thread t2([]{<br>        std::cout &lt;&lt; &quot;Thread 2 started&quot; &lt;&lt; std::endl;<br>        myThreadLocalObjects[0].printThreadId();<br>        std::this_thread::sleep_for(std::chrono::seconds(1));<br>        std::cout &lt;&lt; &quot;Thread 2 ended&quot; &lt;&lt; std::endl;<br>    });<br><br>    t1.join();<br>    t2.join();<br><br>    return 0;<br>}<br><br>//Output<br>//Thread 1 started<br>//Thread ID: 140633650480320<br>//Thread 2 started<br>//Thread ID: 140633650476224<br>//Thread 2 ended<br>//Thread 1 ended</pre><p>Here, MyThreadLocalClass has a default constructor that is used to initialize the objects in the std::array. The printThreadId() function is called on each thread-local object to print the thread ID. When the threads are started and joined, the output shows that each thread has its own copy of the MyThreadLocalClass object.</p><h4><strong>consteval VS constinit</strong></h4><p>consteval is used to indicate that a function should be evaluated at compile-time, which means that the result of the function will be available at compile-time. This can be helpful for optimizing code by avoiding runtime calculations, and it can also be used to check input parameters at compile-time to ensure that they are valid.</p><p>On the other hand, constinit is used to indicate that a variable should be initialized at compile-time. The variable must be declared constexpr, and it can only be initialized with constant expressions, making it a compile-time constant. This allows for more efficient use of memory and can help improve program performance.</p><p>In summary, while consteval is used for compile-time evaluation of functions, constinit is used for compile-time initialization of variables. Both can help improve program efficiency and performance by allowing computations to be performed at compile-time rather than runtime.</p><p>For example:</p><pre>#include &lt;iostream&gt;<br><br>consteval int factorial(int n) {<br>    return n == 0 ? 1 : n * factorial(n - 1);<br>}<br><br>constinit int arr1[] = {1, 2, 3, factorial(4)};<br>constexpr int arr2[] = {1, 2, 3, factorial(4)};<br><br>int main() {<br>    std::cout &lt;&lt; &quot;arr1: &quot;;<br>    for (int i = 0; i &lt; sizeof(arr1) / sizeof(*arr1); ++i) {<br>        std::cout &lt;&lt; arr1[i] &lt;&lt; &quot; &quot;;<br>    }<br>    std::cout &lt;&lt; std::endl;<br><br>    std::cout &lt;&lt; &quot;arr2: &quot;;<br>    for (int i = 0; i &lt; sizeof(arr2) / sizeof(*arr2); ++i) {<br>        std::cout &lt;&lt; arr2[i] &lt;&lt; &quot; &quot;;<br>    }<br>    std::cout &lt;&lt; std::endl;<br><br>    return 0;<br>}<br><br>//Output<br>//arr1: 1 2 3 24<br>//arr2: 1 2 3 24<br></pre><p>This code defines two arrays, arr1 and arr2, which contain the values 1, 2, 3, and the factorial of 4. The factorial() function is defined using the consteval keyword, which tells the compiler to evaluate the function at compile-time. This means that the result of factorial(4) is known at compile-time and can be used to initialize the arrays.</p><p>arr1 is initialized using the constinit keyword, which specifies that it should be initialized at compile-time and can only be initialized once. arr2 is initialized using the constexpr keyword, which also specifies that it should be evaluated at compile-time and be a constant expression.</p><p>In the main() function, the values of arr1 and arr2 are printed to the console using a loop. The output shows that both arrays contain the same values, including the factorial of 4, which is 24.</p><h4>Conclusion</h4><p>consteval<strong> </strong>and constinitare powerful specifiers that can be used to optimize and catch errors in your code at compile-time. By ensuring that functions and variables are evaluated and initialized at compile-time, you can improve code efficiency and reduce the risk of runtime errors. When used appropriately, constevaland constinitcan help you write better, more efficient, and safer C++ code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=170b09b5cc51" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>