<?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 Semih Kırdinli on Medium]]></title>
        <description><![CDATA[Stories by Semih Kırdinli on Medium]]></description>
        <link>https://medium.com/@semihkirdinli?source=rss-bf035e5c6845------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*chYt2GeDS2BeyqjKXPxZgw.jpeg</url>
            <title>Stories by Semih Kırdinli on Medium</title>
            <link>https://medium.com/@semihkirdinli?source=rss-bf035e5c6845------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:56:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@semihkirdinli/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[Java Debugging in Cursor IDE: A Comprehensive Guide]]></title>
            <link>https://semihkirdinli.medium.com/java-debugging-in-cursor-ide-a-comprehensive-guide-3e5a3ae83b27?source=rss-bf035e5c6845------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e5a3ae83b27</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[cursor]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Semih Kırdinli]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 19:10:06 GMT</pubDate>
            <atom:updated>2025-10-28T19:11:36.816Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*d0SmetTIVtUmduKOOtMSDQ.png" /></figure><h3>Introduction</h3><p>Debugging is an essential skill for any Java developer. While Cursor is a powerful AI-enhanced code editor built on VS Code, it requires proper configuration to enable full debugging capabilities for Java applications. This guide will walk you through setting up and using Java debugging features in Cursor, using a Spring Boot REST API project as a practical example.</p><h3>Project Overview</h3><p>Our example project is a simple Customer Management REST API built with Spring Boot 3.5.6 and Java 21. The application provides CRUD operations for customer records through RESTful endpoints.</p><p><strong>Technology Stack</strong><br>- Java 21<br>- Spring Boot 3.5.6<br>- Maven<br>- Spring Web</p><p><strong>Key Components</strong><br>- Customer.java — Entity class representing customer data<br>- CustomerController.java — REST controller with CRUD endpoints<br>- DemoApplication.java — Spring Boot application entry point</p><p><strong>Prerequisites<br></strong>Before starting, ensure you have:<br>1. Java 21 JDK installed on your system<br>2. Cursor IDE installed<br>3. Maven (included with the project via Maven Wrapper)<br>4. Extension Pack for Java installed in Cursor</p><h3>Setting Up Java Debugging in Cursor</h3><h4>Step 1: Install Required Extensions</h4><p>Cursor, being based on VS Code, supports VS Code extensions. For Java debugging, you need to install the following extensions:</p><ol><li>Open Cursor</li><li>Press “Cmd+Shift+X” (macOS) or “Ctrl+Shift+X” (Windows/Linux) to open the Extensions panel</li><li>Search for and install these extensions:<br><strong>Extension Pack for Java</strong> (Microsoft)<br><strong>Debugger for Java</strong> (Microsoft)<br><strong>Language Support for Java(TM)</strong> (Red Hat)<br><strong>Maven for Java</strong> (Microsoft)</li></ol><p>💡 <em>Tip:</em> The “Extension Pack for Java” already includes all the essential extensions.</p><h4>Step 2: Configure Java Runtime</h4><p>After installing the extensions, you’ll need to tell Cursor where your JDK is located.</p><ol><li>Open <strong>Settings</strong> (Cmd+, on macOS or Ctrl+, on Windows/Linux)</li><li>Search for &quot;java.home&quot;</li><li>Add your JDK installation path.</li></ol><p>To find your Java path:</p><pre>/usr/libexec/java_home -v 21   # macOS<br>which java                     # Linux<br>where java                     # Windows</pre><p>Or set it in your settings.json:</p><pre>{<br>  &quot;java.configuration.runtimes&quot;: [<br>    {<br>      &quot;name&quot;: &quot;JavaSE-21&quot;,<br>      &quot;path&quot;: &quot;/path/to/your/jdk-21&quot;,<br>      &quot;default&quot;: true<br>    }<br>  ]<br>}</pre><p>💡 Replace 21 with your installed version (e.g., JavaSE-17 or JavaSE-11).</p><h4>Step3: Create a Launch Configuration</h4><p>In your project root, create a file at .vscode/launch.json:</p><pre>{<br>  &quot;version&quot;: &quot;0.2.0&quot;,<br>  &quot;configurations&quot;: [<br>    {<br>      &quot;type&quot;: &quot;java&quot;,<br>      &quot;name&quot;: &quot;Debug Spring Boot App&quot;,<br>      &quot;request&quot;: &quot;launch&quot;,<br>      &quot;mainClass&quot;: &quot;com.example.demo.DemoApplication&quot;,<br>      &quot;projectName&quot;: &quot;demo&quot;,<br>      &quot;args&quot;: &quot;&quot;,<br>      &quot;envFile&quot;: &quot;${workspaceFolder}/.env&quot;<br>    },<br>    {<br>      &quot;type&quot;: &quot;java&quot;,<br>      &quot;name&quot;: &quot;Debug Current File&quot;,<br>      &quot;request&quot;: &quot;launch&quot;,<br>      &quot;mainClass&quot;: &quot;${file}&quot;<br>    },<br>    {<br>      &quot;type&quot;: &quot;java&quot;,<br>      &quot;name&quot;: &quot;Attach to Process&quot;,<br>      &quot;request&quot;: &quot;attach&quot;,<br>      &quot;hostName&quot;: &quot;localhost&quot;,<br>      &quot;port&quot;: 5005<br>    }<br>  ]<br>}</pre><h4>Step3: Configure Maven (Optional but Recommended)</h4><p>Create .vscode/settings.json with the following configuration:</p><pre>{<br>  &quot;java.configuration.updateBuildConfiguration&quot;: &quot;automatic&quot;,<br>  &quot;maven.executable.path&quot;: &quot;./mvnw&quot;,<br>  &quot;java.debug.settings.hotCodeReplace&quot;: &quot;auto&quot;,<br>  &quot;java.debug.settings.console&quot;: &quot;integratedTerminal&quot;<br>}</pre><p>This enables automatic build updates, uses your project’s Maven wrapper, and turns on Hot Code Replace.</p><h4>Step4: Set Up IntelliJ-Like Navigation Shortcuts (Optional)</h4><p>If you’re used to IntelliJ IDEA’s navigation shortcuts (Cmd+Option+Left/Right), you can make Cursor behave the same way.</p><ol><li><strong>Open your global keybindings file:</strong></li></ol><ul><li>macOS: ~/Library/Application Support/Cursor/User/keybindings.json</li><li>Windows: %APPDATA%\Cursor\User\keybindings.json</li><li>Linux: ~/.config/Cursor/User/keybindings.json</li></ul><p><strong>2. Add the following:</strong></p><pre>[<br>  {<br>    &quot;key&quot;: &quot;cmd+alt+left&quot;,<br>    &quot;command&quot;: &quot;-workbench.action.previousEditor&quot;<br>  },<br>  {<br>    &quot;key&quot;: &quot;cmd+alt+right&quot;,<br>    &quot;command&quot;: &quot;-workbench.action.nextEditor&quot;<br>  },<br>  {<br>    &quot;key&quot;: &quot;cmd+alt+left&quot;,<br>    &quot;command&quot;: &quot;workbench.action.navigateBack&quot;<br>  },<br>  {<br>    &quot;key&quot;: &quot;cmd+alt+right&quot;,<br>    &quot;command&quot;: &quot;workbench.action.navigateForward&quot;<br>  }<br>]</pre><p>💡 On Windows/Linux, replace cmd with ctrl.</p><p>Now you’ll navigate through your code history (not just between tabs), just like in IntelliJ IDEA.</p><h3><strong>Debugging Workflow</strong></h3><h4>Set Breakpoints</h4><ol><li>Open any Java file (e.g., CustomerController.java)</li><li>Click to the left of the line number to add a breakpoint</li><li>A red dot will appear when it’s active</li></ol><h4>Start Debugging</h4><ol><li>Press F5 or click the <strong>Run and Debug</strong> icon in the sidebar</li><li>Choose <strong>Debug Spring Boot App</strong></li><li>Wait for the Spring Boot banner in the terminal — you’re now debugging!</li></ol><h4>Trigger a Breakpoint</h4><p>Run this in your terminal or use Postman:</p><pre>curl http://localhost:8080/api/customers</pre><p>Cursor will pause at your breakpoint, showing variable values and execution flow.</p><h4>Debug Toolbar Controls</h4><ul><li><strong>Continue (F5):</strong> Resume execution until the next breakpoint</li><li><strong>Step Over (F10):</strong> Move to the next line of code</li><li><strong>Step Into (F11):</strong> Step into a method to debug its contents</li><li><strong>Step Out (Shift+F11):</strong> Exit the current method and return to the caller</li><li><strong>Restart (Cmd+Shift+F5):</strong> Restart the current debugging session</li><li><strong>Stop (Shift+F5):</strong> Stop debugging</li></ul><h4>Inspecting Variables</h4><p>While paused at a breakpoint, you can:</p><ul><li>Use the <strong>Variables Panel</strong> to view local variables and fields</li><li><strong>Hover</strong> over variables to see their values inline</li><li><strong>Right-click → Add to Watch</strong> to monitor values</li><li>Use the <strong>Debug Console</strong> to evaluate expressions</li></ul><h3>Advanced Debugging Techniques</h3><h4>Remote Debugging</h4><p>If your app runs on a remote server or container, start it with these JVM arguments:</p><pre>java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar your-app.jar</pre><p>Or with Spring Boot:</p><pre>./mvnw spring-boot:run -Dspring-boot.run.jvmArguments=&quot;-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005&quot;</pre><p>Then attach via the <strong>Attach to Process</strong> configuration.</p><h3>Hot Code Replace</h3><p>Modify code during debugging without restarting the app:</p><ol><li>Hit a breakpoint</li><li>Change your code</li><li>Save the file</li><li>Cursor applies the change automatically</li></ol><p>Works for method body changes, not for adding/removing methods or fields.</p><h3>Conclusion</h3><p>With proper setup, <strong>Cursor becomes a full-featured Java IDE</strong> — offering breakpoints, hot reloads, remote debugging, and more.</p><p>By now, you should be able to:</p><ul><li>Set up Java debugging in Cursor</li><li>Manage breakpoints effectively</li><li>Use advanced features like HCR and remote debugging</li><li>Troubleshoot common issues with confidence</li></ul><blockquote>The real power of debugging lies in understanding your code flow and being systematic in how you approach problems.</blockquote><h3>Additional Resources</h3><ul><li><a href="https://code.visualstudio.com/docs/java/java-debugging">VS Code Java Debugging Docs</a></li><li><a href="https://spring.io/projects/spring-boot">Spring Boot Documentation</a></li><li><a href="https://docs.oracle.com/en/java/javase/21/docs/specs/jdwp/jdwp-spec.html">JDWP Specification</a></li><li><a href="https://cursor.sh/docs">Cursor Documentation</a></li></ul><h3>Example Project Structure</h3><pre>demo/<br>├── pom.xml<br>├── mvnw<br>├── mvnw.cmd<br>├── .vscode/<br>│   ├── launch.json<br>│   └── settings.json<br>└── src/<br>    ├── main/<br>    │   ├── java/<br>    │   │   └── com/example/demo/<br>    │   │       ├── DemoApplication.java<br>    │   │       ├── Customer.java<br>    │   │       └── CustomerController.java<br>    │   └── resources/<br>    │       └── application.properties<br>    └── test/<br>        └── java/<br>            └── com/example/demo/<br>                └── DemoApplicationTests.java</pre><p>Happy debugging!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e5a3ae83b27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Really Happens in Spring Boot Auto-Configuration]]></title>
            <link>https://semihkirdinli.medium.com/what-really-happens-in-spring-boot-auto-configuration-c2980a8c2f28?source=rss-bf035e5c6845------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2980a8c2f28</guid>
            <dc:creator><![CDATA[Semih Kırdinli]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 22:57:55 GMT</pubDate>
            <atom:updated>2025-08-03T22:58:27.217Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*SNyzsoFObNM5m2-4bwA1og.jpeg" /></figure><h3>Introduction</h3><p>Spring Boot follows the idea of using smart defaults instead of requiring a lot of setup. One of its most powerful features is <strong>auto-configuration</strong>, which automatically sets up components based on your project setup.</p><p>In this article, we’ll uncover how auto-configuration works, how Spring Boot decides which beans to register, how to override default behavior, and a few important nuances that even experienced developers often overlook.</p><h3>What Is Auto-Configuration?</h3><p>Auto-configuration is the mechanism by which Spring Boot automatically configures beans in the ApplicationContext based on:</p><ul><li>What’s on the classpath</li><li>Application properties</li><li>Existing user-defined beans</li><li>Metadata declarations in META-INF</li></ul><p>It eliminates most boilerplate configurations and helps you get started faster.</p><h3>How Auto-Configuration Works: 3 Main Steps</h3><h4>1. Classpath Scanning</h4><p>Spring Boot scans the project’s dependencies (classpath) to check for specific libraries or classes. Based on what it finds, it determines which components should be configured.</p><p>For example:</p><ul><li>Adding spring-boot-starter-data-jpa brings in a JDBC driver and JPA classes, so Spring Boot tries to configure a DataSource bean.</li><li>Adding spring-boot-starter-web triggers the creation of DispatcherServlet and embedded web server beans.</li></ul><blockquote><em>Spring Boot uses the </em><em>@ConditionalOnClass annotation to apply a configuration only when a specific class is present on the classpath.</em></blockquote><h4>2. The Role of META-INF Files</h4><p>Spring Boot uses special files inside its jars to locate auto-configuration classes:</p><ul><li><strong>Before Spring Boot 2.7:</strong> META-INF/spring.factories listed all auto-config classes.</li><li><strong>Starting Spring Boot 2.7+: </strong>META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports replaced the old file for better modularity.</li></ul><p>These files contain fully qualified names of auto-configuration classes. Spring Boot reads these files during startup to load potential configurations.</p><h4>3. Conditional Configuration with Annotations</h4><p>Once candidate configuration classes are loaded, Spring Boot uses conditional annotations to decide which to activate:</p><ul><li>@ConditionalOnClass: Checks if a specific class is present on the classpath</li><li>@ConditionalOnMissingBean: Avoids creating a bean if one already exists</li><li>@ConditionalOnProperty: Activates config only if a specific property is set</li></ul><p>For example:</p><p>DataSourceAutoConfiguration activates only if:</p><ul><li>The javax.sql.DataSource class is on the classpath (@ConditionalOnClass)</li><li>The property spring.datasource.url is defined (@ConditionalOnProperty)</li></ul><pre>@Configuration<br>@ConditionalOnClass(javax.sql.DataSource.class)<br>@ConditionalOnProperty(prefix = &quot;spring.datasource&quot;, name = &quot;url&quot;)<br>public class DataSourceAutoConfiguration {<br>    @Bean<br>    @ConfigurationProperties(prefix = &quot;spring.datasource&quot;)<br>    public DataSource dataSource() {<br>        return DataSourceBuilder.create().build();<br>    }<br>}</pre><h3>How Spring Boot Applies Auto-Configuration</h3><p>The process includes:</p><ol><li><strong>Enabling Auto-Configuration:</strong><br> @EnableAutoConfiguration or @SpringBootApplication triggers Spring Boot to start processing auto-config classes listed in the AutoConfiguration.imports file.</li><li><strong>Loading Configuration Classes:</strong><br> Spring Boot loads all candidate configuration classes declared in metadata files.</li><li><strong>Evaluating Conditions:</strong><br> Each configuration class’s conditional annotations are evaluated against the current runtime environment.</li><li><strong>Registering Beans:</strong><br> Beans from configurations whose conditions pass are registered into the application context.</li></ol><h3>Are Auto-Configuration Classes Dynamic?</h3><p>A key point often misunderstood:</p><blockquote>Auto-configuration classes are static and do not change their code based on your dependencies.</blockquote><p>Their source code — like DataSourceAutoConfiguration — is fixed inside the Spring Boot jars.</p><p>What changes is whether Spring Boot <strong>activates</strong> these classes based on conditions such as classpath contents and properties.</p><h4>So, What <em>Does</em> Change?</h4><ul><li>Which dependencies are available on the classpath</li><li>What properties are defined in application.properties or application.yaml</li></ul><p>For example The DataSourceAutoConfiguration class is <strong>always available</strong> in Spring Boot. But if javax.sql.DataSource is <strong>not present</strong> on the classpath or if spring.datasource.url is <strong>not configured</strong> in your properties. Then Spring Boot will simply <strong>skip</strong> this configuration — it won’t run the code inside DataSourceAutoConfiguration and won&#39;t create any related beans.</p><h3>Dynamic Bean Configuration in Action</h3><p>Spring Boot dynamically creates beans based on runtime data such as:</p><ul><li>Dependencies found on classpath</li><li>Defined properties in application.properties or application.yml</li><li>Beans already defined by the developer</li></ul><p>Example — DataSource creation:</p><pre>@Component<br>@ConfigurationProperties(prefix = &quot;spring.datasource&quot;)<br>public class DataSourceProperties {<br>    private String url;<br>    private String username;<br>    private String password;<br>    private String driverClassName;<br>    // getters and setters<br>}<br><br>@Bean<br>public DataSource dataSource(DataSourceProperties properties) {<br>    HikariDataSource dataSource = new HikariDataSource();<br>    dataSource.setJdbcUrl(properties.getUrl());<br>    dataSource.setUsername(properties.getUsername());<br>    dataSource.setPassword(properties.getPassword());<br>    dataSource.setDriverClassName(properties.getDriverClassName());<br>    return dataSource;<br>}</pre><h3>Overriding and Excluding Auto-Configuration</h3><h4>Excluding Auto-Configurations</h4><p>You can exclude auto-configuration classes to prevent Spring Boot from applying them:</p><ul><li>Via annotation:</li></ul><pre>@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})</pre><ul><li>Via configuration files:</li></ul><pre># application.properties<br>spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration</pre><pre># application.yaml<br>spring:<br>  autoconfigure:<br>    exclude: org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration</pre><p>Multiple exclusions supported:</p><pre>spring:<br>  autoconfigure:<br>    exclude:<br>      - org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration<br>      - org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration</pre><h4>Defining Custom Beans</h4><p>You can provide your own beans to override the auto-configured ones:</p><pre>@Bean<br>public DataSource myCustomDataSource() {<br>    return new HikariDataSource();<br>}</pre><h3>Handling Missing Beans and Fallbacks</h3><p>The code demonstrates how to provide a fallback bean when a required bean is missing. In this case, it’s about the DataSource bean, which is used for database connections.</p><p>If no DataSource is defined in the application context, the application might fail to start. To prevent this, the @ConditionalOnMissingBean annotation is used to define a default DataSource.</p><pre>@Configuration<br>public class FallbackConfiguration {<br>    @Bean<br>    @ConditionalOnMissingBean(DataSource.class)<br>    public DataSource fallbackDataSource() {<br>        return new EmbeddedDatabaseBuilder()<br>            .setType(EmbeddedDatabaseType.H2)<br>            .build();<br>    }<br>}</pre><h3>Conclusion</h3><p>Spring Boot’s auto-configuration dramatically simplifies application setup by dynamically applying configurations based on your project’s dependencies and properties.</p><p>Understanding this process empowers you to customize or disable configurations, provide your own beans, debug startup issues related to bean creation. Auto-configuration does a lot behind the scenes — now that you understand how it works, you can take full advantage of it and customize when needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2980a8c2f28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Command Design Pattern]]></title>
            <link>https://semihkirdinli.medium.com/command-design-pattern-fe98076e4e60?source=rss-bf035e5c6845------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe98076e4e60</guid>
            <category><![CDATA[command-pattern]]></category>
            <category><![CDATA[design-patterns-in-java]]></category>
            <category><![CDATA[behavioral-patterns]]></category>
            <category><![CDATA[command-design-pattern]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Semih Kırdinli]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 23:45:47 GMT</pubDate>
            <atom:updated>2023-06-05T08:00:38.079Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*9V7MiDmbHKZMYFahwFnGEw.png" /></figure><p><strong>Command Design Pattern</strong> is a behavioral design pattern that turns a request(action or operation) into a stand-alone object that contains all information about the request.</p><p>The command design pattern wraps the objects that performs user requests. In this way, the same code structure can be used again and again. Each process to be performed on the command pattern is wrapped as an object.</p><p>There may be different command objects which has already implemented. The object to be processed is sent to the command class as a parameter and various operations are performed on the object.</p><p>As a benefit of creating commands as objects, they can also be taught to undo their actions when desired. As a result, Redo(Redo)/Undo(Undo) operations can be performed and a macro feature can be created.</p><p>The Command Pattern involves the following key components:</p><ul><li><strong>Command:</strong> This is an interface or an abstract class that declares an execute() method. This method defines the operation to be performed.</li><li><strong>Concrete Command:</strong> These are the implementations of the Command interface. Each concrete command encapsulates a specific request and binds it to a receiver by invoking the corresponding operation on the receiver.</li><li><strong>Receiver:</strong> This is the object that performs the actual operation when a command is executed. The receiver knows how to carry out the request.</li><li><strong>Invoker:</strong> The invoker is responsible for initiating the execution of the command. It holds a reference to a command object and can execute the command by calling its execute() method.</li><li><strong>Client:</strong> The client is responsible for creating the command objects, setting their receivers, and associating them with invokers.</li></ul><p>Now take a look at the example written in Java.</p><pre>// Step 1: Create the Command interface<br>interface Command {<br>    void execute();<br>}<br><br>// Step 2: Create Concrete Command classes<br>class LightOnCommand implements Command {<br>    private Light light;<br><br>    public LightOnCommand(Light light) {<br>        this.light = light;<br>    }<br><br>    public void execute() {<br>        light.turnOn();<br>    }<br>}<br><br>class LightOffCommand implements Command {<br>    private Light light;<br><br>    public LightOffCommand(Light light) {<br>        this.light = light;<br>    }<br><br>    public void execute() {<br>        light.turnOff();<br>    }<br>}<br><br>class LightChangeColorCommand implements Command {<br>  private Light light;<br><br>  public LightChangeColorCommand(Light light) {<br>    this.light = light;<br>  }<br><br>  public void execute() {<br>    light.changeColor();<br>  }<br>}<br><br>// Step 3: Create the Receiver class<br>class Light {<br>    public void turnOn() {<br>        System.out.println(&quot;Light is on&quot;);<br>    }<br><br>    public void turnOff() {<br>        System.out.println(&quot;Light is off&quot;);<br>    }<br><br>    public void changeColor() {<br>      System.out.println(&quot;Light color has been changed&quot;);<br>    }<br>}<br><br>// Step 4: Create the Invoker class<br>class RemoteControl {<br>    private Command command;<br><br>    public void setCommand(Command command) {<br>        this.command = command;<br>    }<br><br>    public void pressButton() {<br>        command.execute();<br>    }<br>}<br><br>// Step 5: Create the Client class<br>class Client {<br>    public static void main(String[] args) {<br>        // Create the receiver<br>        Light light = new Light();<br><br>        // Create the commands<br>        LightOnCommand lightOnCommand = new LightOnCommand(light);<br>        LightOffCommand lightOffCommand = new LightOffCommand(light);<br>        LightChangeColorCommand lightChangeColorCommand = new LightChangeColorCommand(light);<br><br>        // Create the invoker<br>        RemoteControl remoteControl = new RemoteControl();<br><br>        // Set the commands in the invoker<br>        remoteControl.setCommand(lightOnCommand);<br><br>        // Press the button to turn on the light<br>        remoteControl.pressButton();<br><br>        // Set a different command in the invoker<br>        remoteControl.setCommand(lightOffCommand);<br><br>        // Press the button to turn off the light<br>        remoteControl.pressButton();<br><br>        // Set a different command in the invoker<br>        remoteControl.setCommand(lightChangeColorCommand);<br><br>        // Press the button to change color the light<br>        remoteControl.pressButton();<br>    }<br>}</pre><blockquote>Command and Strategy patterns are both behavioral design patterns. They may look similar because you can use both to parameterize an object with some action. However, they serve different purposes and have distinct intents.</blockquote><blockquote>The Strategy pattern is about dynamically selecting and switching algorithms, while the Command pattern is about encapsulating and decoupling requests as objects.</blockquote><h3><strong>Fields of Usage</strong></h3><p>The Command pattern can be applied in various fields, including:</p><p><strong>1. User Interfaces:</strong> The Command pattern is commonly used in GUI frameworks and applications to handle user actions and operations. Each user action is encapsulated as a command object, allowing the application to manage and execute them as needed.<br><strong>2. Transactional Systems:</strong> The Command pattern is suitable for implementing transactional systems, where a series of actions need to be executed or rolled back as a single atomic unit. Each command object represents an individual action, and the transactional manager orchestrates their execution.<br><strong>3. Menu Systems and Keyboard Shortcuts:</strong> Applications that involve menus and keyboard shortcuts can utilize the Command pattern. Each menu item or shortcut can be associated with a command object, which performs the corresponding action when invoked.<br><strong>4. Multi-level Undo/Redo: </strong>The Command pattern facilitates implementing undo and redo functionality in applications. By keeping a history of executed commands, you can easily revert or reapply them to achieve undo and redo operations.<br><strong>5. Task Scheduling and Job Queues:</strong> In systems that require scheduling and queuing of tasks or jobs, the Command pattern can be employed. Each task or job can be encapsulated as a command object, allowing the system to schedule, prioritize, and execute them accordingly.<br><strong>6. Remote Procedure Calls (RPC) and Networking:</strong> The Command pattern can be utilized in distributed systems, especially for implementing Remote Procedure Calls (RPC). The command object carries the necessary data and logic required to invoke remote methods or perform operations on remote systems.</p><p>These are just a few examples of the fields of usage for the Command pattern. Its flexibility and ability to encapsulate requests make it applicable in various scenarios where loose coupling, extensibility, and flexibility are desired.</p><p>I’ve tried to summarize it in its simple form. I hope it has been an example you can apply to your specific scenarios.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe98076e4e60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adapter Design Pattern]]></title>
            <link>https://semihkirdinli.medium.com/adapter-design-pattern-b55f9f13f41c?source=rss-bf035e5c6845------2</link>
            <guid isPermaLink="false">https://medium.com/p/b55f9f13f41c</guid>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[structural-design-pattern]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[adapter-design-pattern]]></category>
            <category><![CDATA[adapter]]></category>
            <dc:creator><![CDATA[Semih Kırdinli]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 23:34:54 GMT</pubDate>
            <atom:updated>2023-06-04T23:48:11.058Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*-j1UXRfzxSD0yQx0ktLPCQ.png" /></figure><p><strong>Adapter Design Pattern</strong> is used so that two unrelated or incompatible interfaces can work together.<br>The main goal for this pattern is to convert an existing interface into another one the client expects.</p><p>There is always something incompatible between the old and the new. We create an adapter classes to manage such incompatibilities.<br>To do this, we wrap an existing class with a new interface. Adapter Pattern is also known as Wrapper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S53gnfGUPGeEHnE3CYnkYg.jpeg" /></figure><p><strong>Advantages of Adapter Pattern</strong></p><ul><li>Facilitates Integration: The Adapter pattern can facilitate the integration of different systems or components by providing a common interface that both can understand.</li><li>Flexibility: You can swap or extend the adapters without affecting the rest of the system.</li><li>Re-usability: Adapters can be reused with different adaptees, making it easy to use the same adapter with different systems.</li><li>Improves Readability and Usability: The Adapter pattern allows the client code to remain separate from the adaptee code, which makes it easier to modify.</li><li>Reduces Dependencies: The Adapter pattern can improve code maintainability by reducing the number of dependencies between components.</li></ul><p><strong>Disadvantages of Adapter Pattern</strong></p><ul><li>Increases Complexity: The use of adapters can add additional layers of complexity to the codebase, which can make it harder to understand and maintain.</li><li>Performance Overhead: Using an adapter can introduce performance overhead depending on the implementation, as additional processing may be required to translate data between different interfaces.</li><li>Possible Tight Coupling: If the adapter is tightly coupled to the adaptee, it can create a dependency that may make it harder to modify the adaptee.</li><li>May Obscure Errors: If errors occur within the adaptee code, they may be obscured by the adapter, which can make it harder to diagnose and fix problems.</li></ul><p><strong>When to use the Adapter Pattern?</strong></p><ul><li>Legacy Code Integration</li><li>Third Party Library Integration</li><li>GUI Development</li><li>Accessing Different Databases such as SQL, NoSQL or filesTranslate Requests and Responses between XML and JSON or SOAP and REST</li></ul><p><strong>How to implement the Adapter Pattern?</strong><br>There are two ways to implement the adapter pattern: class adapter and object adapter.</p><ul><li><strong>Class Adapter:</strong> The class adapter uses inheritance to extqend the existing class and implement the desired interface. It is simpler and faster.</li></ul><figure><img alt="Class Adapter" src="https://cdn-images-1.medium.com/max/1024/1*Q1TBDtXzG9xmhhJoB5c5cg.jpeg" /><figcaption>Class Adapter</figcaption></figure><ul><li><strong>Object Adapter:</strong> The object adapter uses composition to wrap the existing class and delegate the interface methods to it. It is more flexible and robust, but it requires more code and may introduce some overhead.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ck8e4R5JftRzyTD25IUbYg.jpeg" /><figcaption>Object Adapter</figcaption></figure><p>Both approaches have their pros and cons, and you should choose the most suitable implementation, such as class adapter or object adapter.</p><p>In this part, I would like to show you an example of the adapter pattern that we used in a project. It needs to communicate to different bank account statement web services. Although the return response is the same, the request body information may differ for each bank. We have used an adapter pattern to convert the request to a specific request.</p><p>According to the bank type, we have done the conversion of the request with the adaptee method. So we have provided an abstraction based on the bank type, and we can now implement numerous banks in our system. As a result, we have created a structure where we accept different requests and return the same response.</p><pre>@RestController<br>@RequiredArgsConstructor<br>@RequestMapping(&quot;/api/account-statements&quot;)<br>public class AccountStatementController {<br>    private final AccountStatementFacade accountStatementFacade;<br><br>    @GetMapping<br>    ResponseEntity&lt;AccountStatementResponse&gt; getAccountStatements(@RequestHeader String bankType, @RequestBody String payload) {<br>        return ResponseEntity.ok(accountStatementFacade.getAccountStatements(BankType.valueOf(bankType), payload));<br>    }<br>}</pre><pre>public enum BankType {<br>    A_BANK,<br>    B_BANK<br>}</pre><pre>@Slf4j<br>public class AccountStatementClientFactory implements Factory&lt;AccountStatementClient&gt; {<br>    private final BankType bankType;<br>    public AccountStatementClientFactory(BankType bankType) {<br>        this.bankType = bankType;<br>    }<br>    @Override<br>    public AccountStatementClient build() {<br>        switch (bankType) {<br>            case A_BANK -&gt; {<br>                var username = &quot;a_bank_user&quot;;<br>                var password = &quot;YV9iYW5rcGQ=&quot;;<br>                var webServiceUrl = &quot;soap-service@a_bank.com&quot;;<br>                return new ABankAccountStatementClient(webServiceUrl, username, password);<br>            }<br>            case B_BANK -&gt; {<br>                var authURL = &quot;auth@b_bank.com&quot;;<br>                var webServiceUrl = &quot;rest-service@b_bank.com&quot;;<br>                var clientId = &quot;b_bank_user&quot;;<br>                var clientSecret = &quot;Tl6zBL0xaPF=&quot;;<br>                return new BBankAccountStatementClient(webServiceUrl, authURL, clientId, clientSecret);<br>            }<br><br>            default -&gt; throw new IllegalStateException(&quot;Unexpected bankType: &quot; + bankType);<br>        }<br>    }<br>}</pre><pre>public interface AccountStatementFacade {<br>    AccountStatementResponse getAccountStatements(BankType bankType, String payload);<br>}<br><br>@Slf4j<br>@RequiredArgsConstructor<br>@Component<br>public class AccountStatementFacadeImpl implements AccountStatementFacade {<br>  private final AccountStatementService accountStatementService;<br><br>  @Override<br>  public AccountStatementResponse getAccountStatements(BankType bankType, String payload) {<br>    var accountStatements = accountStatementService.getAccountStatements(<br>      new AccountStatementClientFactory(bankType).build(),<br>      new AccountStatementRequestAdapter(bankType, payload).adaptee());<br>    log.info(&quot;Request has been sent and response has been received from the [{}] external system. {}&quot;, bankType, accountStatements);<br><br>    var accountStatementResponseConverterFactory = new AccountStatementResponseConverterFactory(bankType);<br>    var accountStatementResponse = accountStatementResponseConverterFactory.build().convert(accountStatements);<br>    log.info(&quot;Response received from the external system has been converted to the AccountStatementResponse object.&quot;);<br>    return accountStatementResponse;<br>  }<br>}</pre><pre>public interface Adapter&lt;T&gt; {<br>  T adaptee();<br>}<br><br>@Slf4j<br>public class AccountStatementRequestAdapter implements Adapter&lt;Object&gt; {<br>  private final BankType bankType;<br>  private final String payload;<br>  private final ObjectMapper objectMapper = new ObjectMapper();<br>  public AccountStatementRequestAdapter(BankType bankType, String payload) {<br>    this.bankType = bankType;<br>    this.payload = payload;<br>  }<br>  // Request is converted to a specific request in adaptee method.<br>  public Object adaptee() {<br>    try {<br>      return switch (bankType) {<br>        case A_BANK -&gt; objectMapper.readValue(payload, ABankAccountStatementRequest.class);<br>        case B_BANK -&gt; objectMapper.readValue(payload, BBankAccountStatementRequest.class);<br>      };<br>    } catch (JsonProcessingException e) {<br>      var message = String.format(&quot;An error occurred while trying to build the [%s] request.&quot;, bankType);<br>      log.error(message);<br>      throw new RuntimeJsonMappingException(message);<br>    }<br>  }<br>}</pre><pre>public interface Factory&lt;T&gt; {<br>  T build();<br>}<br><br>public class AccountStatementResponseConverterFactory implements Factory&lt;Converter&lt;Object, AccountStatementResponse&gt;&gt; {<br>    private final BankType bankType;<br>    public AccountStatementResponseConverterFactory(BankType bankType) {<br>        this.bankType = bankType;<br>    }<br>    @Override<br>    public Converter&lt;Object, AccountStatementResponse&gt; build() {<br>        return switch (bankType) {<br>            case A_BANK -&gt; new ABankAccountStatementResponseConverter();<br>            case B_BANK -&gt; new BBankAccountStatementResponseConverter();<br>        };<br>    }<br>}</pre><pre>public interface AccountStatementService {<br>    Object getAccountStatements(AccountStatementClient accountStatementClient, Object accountStatementRequest);<br>}<br><br>@RequiredArgsConstructor<br>@Service<br>public class AccountStatementServiceImpl implements AccountStatementService {<br><br>  @Override<br>  public Object getAccountStatements(AccountStatementClient accountStatementClient, Object accountStatementRequest) {<br>    return accountStatementClient.getAccountStatements(accountStatementRequest);<br>  }<br>}</pre><pre>@Builder<br>public record ABankAccountStatementRequest(String accountId,<br>                                           String startDate,<br>                                           String endDate) {<br>}<br><br>@Builder<br>public record BBankAccountStatementRequest(String accountId,<br>                                           String startDate,<br>                                           String endDate,<br>                                           String currency) {<br>}</pre><pre>public interface AccountStatementClient {<br>    Object getAccountStatements(Object accountStatementRequest);<br>}<br><br>public class ABankAccountStatementClient implements AccountStatementClient {<br>  private final String webServiceURL;<br>  private final String username;<br>  private final String password;<br>  public ABankAccountStatementClient(String webServiceURL, String username, String password) {<br>    this.webServiceURL = webServiceURL;<br>    this.username = username;<br>    this.password = password;<br>  }<br>  @Override<br>  public Object getAccountStatements(Object accountStatementRequest) {<br>    ABankAccountStatementRequest aBankAccountStatementRequest = (ABankAccountStatementRequest) accountStatementRequest;<br>    return String.format(&quot;&quot;&quot;<br>      [A Bank] web service has been invoked with these parameters<br>      webServiceURL: [%s]<br>      username: [%s]<br>      password: [%s]<br>      requestPayload: [%s]<br>      &quot;&quot;&quot;, webServiceURL, username, password, aBankAccountStatementRequest);<br>  }<br>}<br><br>public class BBankAccountStatementClient implements AccountStatementClient {<br>  private final String webServiceURL;<br>  private final String authURL;<br>  private final String clientId;<br>  private final String clientSecret;<br>  public BBankAccountStatementClient(String webServiceURL, String authURL, String clientId, String clientSecret) {<br>    this.webServiceURL = webServiceURL;<br>    this.authURL = authURL;<br>    this.clientId = clientId;<br>    this.clientSecret = clientSecret;<br>  }<br>  @Override<br>  public Object getAccountStatements(Object accountStatementRequest) {<br>    BBankAccountStatementRequest bBankAccountStatementRequest = (BBankAccountStatementRequest) accountStatementRequest;<br>    return String.format(&quot;&quot;&quot;<br>      [A Bank] web service has been invoked with these parameters<br>      authURL: [%s]<br>      webServiceURL: [%s]<br>      clientId: [%s]<br>      clientSecret: [%s]<br>      requestPayload: [%s]<br>      &quot;&quot;&quot;, authURL, webServiceURL, clientId, clientSecret, bBankAccountStatementRequest);<br>  }<br>}</pre><pre>public interface Converter&lt;I, O&gt; {<br>    O convert(I input);<br>}<br><br>public class ABankAccountStatementResponseConverter implements Converter&lt;Object, AccountStatementResponse&gt; {<br>  @Override<br>  public AccountStatementResponse convert(Object input) {<br>    // Let&#39;s suppose the values are come from the input parameter.<br>    return new AccountStatementResponse(&quot;1234&quot;, &quot;A Bank&quot;,<br>      &quot;USD&quot;, &quot;2022-04-30&quot;, &quot;REF123&quot;,<br>      &quot;1000&quot;, &quot;Credit&quot;, &quot;Salary Payment&quot;,<br>      &quot;TRX123&quot;, &quot;12:30 PM&quot;);<br>  }<br>}<br><br>public class BBankAccountStatementResponseConverter implements Converter&lt;Object, AccountStatementResponse&gt; {<br>  @Override<br>  public AccountStatementResponse convert(Object input) {<br>    // Let&#39;s suppose the values are come from the input parameter.<br>    return new AccountStatementResponse(&quot;5678&quot;, &quot;B Bank&quot;,<br>      &quot;EUR&quot;, &quot;2023-04-30&quot;, &quot;REF456&quot;,<br>      &quot;2000&quot;, &quot;Debit&quot;, &quot;Rent Payment&quot;,<br>      &quot;TRX456&quot;, &quot;10:00 AM&quot;);<br>  }<br>}</pre><p>You might download the source code from this link. =&gt; [<a href="https://github.com/semih/semih.github.io/raw/main/assets/java/banking-integration.zip">banking-integration.zip</a>].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b55f9f13f41c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decorator Design Pattern]]></title>
            <link>https://semihkirdinli.medium.com/decorator-design-pattern-b61658282a23?source=rss-bf035e5c6845------2</link>
            <guid isPermaLink="false">https://medium.com/p/b61658282a23</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[structural-design-pattern]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[decorators]]></category>
            <category><![CDATA[decorator-design-pattern]]></category>
            <dc:creator><![CDATA[Semih Kırdinli]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 23:10:00 GMT</pubDate>
            <atom:updated>2023-06-04T23:10:00.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*sW5XBmPGwKwVewCs0diiWg.png" /></figure><p><strong>Decorator Design Pattern</strong> is used for adding new behaviours to objects either statically or dynamically without affecting the behavior of other objects from the same class.</p><ul><li>We can extend object’s behaviour <strong>without making a new subclass</strong>.</li><li>We can <strong>add or remove responsibilities</strong> from an object at runtime.</li><li>We can <strong>combine several behaviors</strong> to an object.</li></ul><p>I will explain the purpose of the Decorator pattern in detail so we might use it correctly.</p><p><strong>Purpose:</strong> The decorator design pattern is used to add new functionality to an existing object without changing its structure.<br>It is often used when the desired behavior cannot be achieved through interface or when you want to add behavior to an object at runtime.</p><p>There are several key points to implement the decorator pattern.<br>It involves creating a decorator class that wraps around the original object and adds new behavior to it. The decorator class has the same interface as the original object, so it can be used in the same way.<br>You can wrap a component with any number of decorators.</p><p>The decorator pattern consists of four components:</p><ol><li><strong>Component Interface</strong> (defines the methods that will be implemented by the concrete component and any decorators.)</li><li><strong>Concrete Component</strong> (is the original object that the decorator will add new behavior to.)</li><li><strong>Decorator Abstract Class</strong> (is an abstract class that implements the component interface and contains a reference to the original object.)</li><li><strong>Concrete Decorator</strong> (is a subclass of the decorator abstract class that adds new behavior to the original object.)</li></ol><p>I’ll continue the article with encoding and compression decorators example. There is going to be a class could only read and write data in plain text. Then we are going to create several wrapper classes.</p><p>The first wrapper encrypts and decrypts data, and the second one compresses and extracts data. You can also combine these wrappers by one decorator with another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*erMr_6MBiA4JcX5xKX44LA.jpeg" /></figure><p>Let’s take a look at the implementation.</p><pre>package com.decorator;<br><br>public interface DataSource {<br>  void writeData(String data);<br>  String readData();<br>}</pre><pre>package com.decorator;<br><br>import java.io.File;<br>import java.io.FileOutputStream;<br>import java.io.FileReader;<br>import java.io.IOException;<br>import java.io.OutputStream;<br><br>public class FileDataSource implements DataSource {<br>  private String name;<br>  public FileDataSource(String name) {<br>    this.name = name;<br>  }<br>  @Override<br>  public void writeData(String data) {<br>    File file = new File(name);<br>    try (OutputStream fos = new FileOutputStream(file)) {<br>      fos.write(data.getBytes(), 0, data.length());<br>    } catch (IOException ex) {<br>      System.out.println(ex.getMessage());<br>    }<br>  }<br><br>  @Override<br>  public String readData() {<br>    char[] buffer = null;<br>    File file = new File(name);<br>    try (FileReader reader = new FileReader(file)) {<br>      buffer = new char[(int) file.length()];<br>      reader.read(buffer);<br>    } catch (IOException ex) {<br>      System.out.println(ex.getMessage());<br>    }<br>    return new String(buffer);<br>  }<br>}</pre><pre>package com.decorator;<br><br>public class DataSourceDecorator implements DataSource {<br>  private DataSource wrappee;<br><br>  DataSourceDecorator(DataSource source) {<br>    this.wrappee = source;<br>  }<br><br>  @Override<br>  public void writeData(String data) {<br>    wrappee.writeData(data);<br>  }<br><br>  @Override<br>  public String readData() {<br>    return wrappee.readData();<br>  }<br>}</pre><pre>package com.decorator;<br><br>import java.util.Base64;<br><br>public class EncryptionDecorator extends DataSourceDecorator {<br><br>  public EncryptionDecorator(DataSource source) {<br>    super(source);<br>  }<br><br>  @Override<br>  public void writeData(String data) {<br>    super.writeData(encode(data));<br>  }<br><br>  @Override<br>  public String readData() {<br>    return decode(super.readData());<br>  }<br><br>  private String encode(String data) {<br>    byte[] result = data.getBytes();<br>    for (int i = 0; i &lt; result.length; i++) {<br>      result[i] += (byte) 1;<br>    }<br>    return Base64.getEncoder().encodeToString(result);<br>  }<br><br>  private String decode(String data) {<br>    byte[] result = Base64.getDecoder().decode(data);<br>    for (int i = 0; i &lt; result.length; i++) {<br>      result[i] -= (byte) 1;<br>    }<br>    return new String(result);<br>  }<br>}</pre><pre>package com.decorator;<br><br>import java.io.ByteArrayInputStream;<br>import java.io.ByteArrayOutputStream;<br>import java.io.IOException;<br>import java.io.InputStream;<br>import java.util.Base64;<br>import java.util.zip.Deflater;<br>import java.util.zip.DeflaterOutputStream;<br>import java.util.zip.InflaterInputStream;<br><br>public class CompressionDecorator extends DataSourceDecorator {<br>  private int compLevel = 6;<br><br>  public CompressionDecorator(DataSource source) {<br>    super(source);<br>  }<br><br>  public int getCompressionLevel() {<br>    return compLevel;<br>  }<br><br>  public void setCompressionLevel(int value) {<br>    compLevel = value;<br>  }<br><br>  @Override<br>  public void writeData(String data) {<br>    super.writeData(compress(data));<br>  }<br><br>  @Override<br>  public String readData() {<br>    return decompress(super.readData());<br>  }<br><br>  private String compress(String stringData) {<br>    byte[] data = stringData.getBytes();<br>    try {<br>      ByteArrayOutputStream bout = new ByteArrayOutputStream(512);<br>      DeflaterOutputStream dos = new DeflaterOutputStream(bout, new Deflater(compLevel));<br>      dos.write(data);<br>      dos.close();<br>      bout.close();<br>      return Base64.getEncoder().encodeToString(bout.toByteArray());<br>    } catch (IOException ex) {<br>      return null;<br>    }<br>  }<br><br>  private String decompress(String stringData) {<br>    byte[] data = Base64.getDecoder().decode(stringData);<br>    try {<br>      InputStream in = new ByteArrayInputStream(data);<br>      InflaterInputStream iin = new InflaterInputStream(in);<br>      ByteArrayOutputStream bout = new ByteArrayOutputStream(512);<br>      int b;<br>      while ((b = iin.read()) != -1) {<br>        bout.write(b);<br>      }<br>      in.close();<br>      iin.close();<br>      bout.close();<br>      return new String(bout.toByteArray());<br>    } catch (IOException ex) {<br>      return null;<br>    }<br>  }<br>}</pre><pre>package com.decorator;<br><br>public class Demo {<br>  public static void main(String[] args) {<br>    String salaryRecords = &quot;Name,Salary\nJohn Smith,100000\nSteven Jobs,912000&quot;;<br>    DataSourceDecorator encoded = new CompressionDecorator(<br>      new EncryptionDecorator(<br>        new FileDataSource(&quot;OutputDemo.txt&quot;)));<br>    encoded.writeData(salaryRecords);<br>    DataSource plain = new FileDataSource(&quot;OutputDemo.txt&quot;);<br><br>    System.out.println(&quot;- Input ----------------&quot;);<br>    System.out.println(salaryRecords);<br>    System.out.println(&quot;- Encoded --------------&quot;);<br>    System.out.println(plain.readData());<br>    System.out.println(&quot;- Decoded --------------&quot;);<br>    System.out.println(encoded.readData());<br>  }<br>}</pre><p>Here are the output results.</p><pre>- Input ----------------<br>Name,Salary<br>John Smith,100000<br>Steven Jobs,912000<br>- Encoded --------------<br>Zkt7e1Q5eU8yUm1Qe0ZsdHJ2VXp6dDBKVnhrUHtUe0sxRUYxQkJIdjVLTVZ0dVI5Q2IwOXFISmVUMU5rcENCQmdxRlByaD4+<br>- Decoded --------------<br>Name,Salary<br>John Smith,100000<br>Steven Jobs,912000<br><br>Process finished with exit code 0</pre><p>To summarize, a decorator can be recognized by methods or constructors that accept objects of the same type. You can see the examples of decorator classes in core Java libraries. <strong><em>java.io.InputStream, OutputStream, Reader</em></strong> and <strong><em>Writer </em></strong>have constructors that accept objects of their own type.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b61658282a23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerize a Spring Boot Application]]></title>
            <link>https://semihkirdinli.medium.com/dockerize-spring-boot-application-8a0f5c02ac8c?source=rss-bf035e5c6845------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a0f5c02ac8c</guid>
            <category><![CDATA[docker-container]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[dockerize]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Semih Kırdinli]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 18:15:14 GMT</pubDate>
            <atom:updated>2023-01-28T09:31:25.753Z</atom:updated>
            <content:encoded><![CDATA[<p>Docker is a Linux container management tool that enables users to publish their own container images and download those that are published by others.</p><p>The way to containerize your application is to create a Dockerfile. A <strong>Dockerfile</strong> is a file that contains the instructions for creating a Docker image.</p><p>A <strong>container</strong> is a sandbox running on your computer that is isolated from all other processes. To make a docker image, you have to write script in Dockerfile. A container:</p><ul><li>is a runnable instance of an image</li><li>can be run on local machines, virtual machines or cloud</li><li>is portable</li><li>is isolated from other containers</li></ul><p>A <strong>docker image</strong> is an instance of a container. When running a container, it uses an isolated filesystem. A container image provides this customized filesystem. Because the image contains the container’s filesystem, it must contain everything required to run an application, all dependencies, configurations, scripts, binaries, and so on. The image also includes additional container configuration. To make container from image, you have to run <strong>docker run IMAGE</strong> command.</p><p>In this post, we are going to use the Docker to construct an image of a Spring Boot application and run it in a container. We can send this image we created to the DockerHub with the <strong>docker push</strong> command and let the application be downloaded and used by others. I’ll go through the steps required for this in order.</p><ol><li><strong>create a Spring Boot application</strong> Let’s generate a Spring Boot application with a standard maven plugin that includes Spring Web dependency.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*TC11HwrrmhH2BlEpS49FtQ.png" /></figure><p><strong>2. create a rest controller</strong> Basically, I added a rest controller to prove that the application is working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eytJrb4xsSiNgRnUrbZiRQ.png" /></figure><p><strong>3. add Dockerfile to the project</strong> I created a file called Dockerfile to the root directory without extension and put following 3 lines into it.</p><pre>FROM openjdk:17-alpine<br>COPY /target/*.jar app.jar<br>ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;app.jar&quot;]</pre><p><strong>4. add maven plugin as a plugin</strong> At this point, I need a maven plugin. Check the pom.xml file. You have to append it, if there is no such plugin.</p><pre>&lt;build&gt;<br>    &lt;plugins&gt;<br>        &lt;plugin&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>        &lt;/plugin&gt;<br>    &lt;/plugins&gt;<br>&lt;/build&gt;</pre><p><strong>5. define a bitbucket-pipelines(optional)</strong> I’m not going to talk about this right now because I’ll explain it in detail in the future. You don’t have to do this step right now.</p><p><strong>6. build the project</strong> If the maven plugin is available for you to use in the terminal, run the “mvn install” command to provide your project built. You are going to see that the target package and jar files in it are created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/0*kXDRcwKsbjZRKGoY.png" /></figure><p><strong>7. execute java jar command</strong></p><pre>java -jar target/docker-0.0.1-SNAPSHOT.jar</pre><p>Eventually, the project is up and running, and when I send a request from the browser, I expect to see “Hello World Docker” on the screen.</p><p>So far, our application has worked flawlessly, but not in any docker container. I guess everything we’ve done so far is clear, understandable, and the way we always do.</p><p>The commands we are going to write from now on will make the project run on a docker container.</p><p>You can use the commands below to check the containers and images running on docker.</p><pre>docker ps -a<br>docker images<br>docker rmi a67aecce36a5</pre><p><strong>8. run docker commands for containerization</strong></p><pre>docker build -t docker-example-service .<br>docker run -p 8085:8085 --name docker-example-service -d docker-example-service<br><br># to communicate with the remote database<br>docker run -p 8085:8085 -e PORT=8085 -e POSTGRESQL_HOST=192.168.X.X -e POSTGRESQL_PORT=5432 -e POSTGRESQL_DB_NAME=exampleDb -e POSTGRESQL_USER=postgres -e POSTGRESQL_PASSWORD=postgres --name docker-example-service -d docker-example-service<br><br>docker ps -a<br>docker logs -f 904957ee3ae2</pre><p>And Spring Boot application is running on the Docker container as expected. 👌</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i841hg1oxModeGHB.png" /></figure><p>Hope the information in this post is useful and sufficient for you. Please contact me if you have any questions or comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a0f5c02ac8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do you prefer to work from home or at an office?]]></title>
            <link>https://semihkirdinli.medium.com/do-you-prefer-to-work-from-home-or-at-an-office-1a97daec12b9?source=rss-bf035e5c6845------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a97daec12b9</guid>
            <category><![CDATA[work-life-balance]]></category>
            <category><![CDATA[work]]></category>
            <category><![CDATA[work-from-home]]></category>
            <dc:creator><![CDATA[Semih Kırdinli]]></dc:creator>
            <pubDate>Tue, 18 Jan 2022 06:01:09 GMT</pubDate>
            <atom:updated>2022-01-19T23:29:17.686Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*kIHz6ioCG7HWTEsVZohv8Q.jpeg" /></figure><p>How was your life about 2 years ago? Would you get up early every day and leave from your home as soon as possible? Sometimes in the dark, before sunrise, you were on the road. If you live in a big city and the traffic is heavy, get ready for a tiring day.</p><p>Let’s remember briefly. You wake up early. You must go to work and go back to your home. You spend all your time at work. After you come home, you can’t have enough energy to do something with your loved ones. You see less of your wife and children if any. You can’t spend enough quality time with them. And how were you holding your meetings or how many meetings were you holding a day? Was it difficult to organize? Let me guess, meetings were difficult to arrange and waiting time for someone else was longer.</p><p>Today, we don’t need to be physically there to carry out some work or meeting. Some of us have started working from home. Many workplaces closed their office. Trainings have started to be given online. People had the freedom to do something without going anywhere. How long does it take you to organize a meeting and connect participants? In a very short time, we can meet online with a person anywhere in the world. How many meetings do we have a day? How many trainings can we attend per month? The social communication has expanded considerably.</p><p>Although the pandemic negatively affects everyone’s life. Many businesses have closed. Most workplaces have told their employees not to come to the workplace. That was one of the positive things in the pandemic. It gives me flexibility I would never have in an office environment. I can get in a workout. I can do grocery shopping on my lunch break. I can prepare something for dinner. Plus, I don’t have to spend time and money commuting to an office.</p><p>There may be some distractions at home, but overall, I think that I work efficiently. Sometimes I found more distractions when I work from an office!</p><p><strong>Let me explain these distractions:</strong></p><p>I am sensitive to loud noise. That’s why I get distracted when someone around me talks loudly. This is a very common situation in business life. Loud conversations in the open office are one of the reasons that reduce productivity.</p><p>Another thing that distracts me is coffee breaks. I like to socialize at work, and I have friends with whom I get along well like everyone else. We usually get together in an open-air place during the coffee break time. Sometimes, these conversations take too much time. Long coffee breaks are a reason that reduces your productivity.</p><p>One of the other things that reduces productivity is to commute by a vehicle. First, you need to get up early for getting ready. These are reasons that take our time and bother us. I don’t know about you, but it absorbs my energy.</p><p><strong>As for the positive aspects of working from home:</strong></p><p>Health comes first. First, you isolate yourself from the coronavirus epidemic. Just as you are not sick yourself, you don’t infect others.</p><p>Even if you get up 5 minutes before, it is enough for you. You don’t have to grab something to wear on it urgently to go to work. You don’t feel tired or exhausted because you don’t commute by a vehicle.</p><p>On the other hand, it also has some difficulties. It is hard to concentrate. If there is a someone in the house, we need to tell them well that we are working. That’s why sometimes they may forget you are working. Without a separate room and a quiet environment, you can quickly become distracted. You may have difficulty socializing. These are some of the challenges of working from home. However, I would like to give some tips based on my experience in order to overcome these difficulties and work more efficiently from home:</p><ul><li>You should have a dedicated workspace. Work at a table and an ergonomic chair.</li><li>When you have started to work, start the timer. Pause the timer when you stand up from the chair and take a break. Thus, you will see that you have completed the time you need to work in a day. When you reach enough time, you may have peace of mind.</li><li>Stay in touch with your colleagues. Check in with them every day, so you can stay connected to them.</li><li>Let people know when you have a meeting. You don’t want to be disturbed when you are in a meeting.</li><li>Take time not to forget the stove is on.</li><li>Before you start working, you should put a bottle of water, a cup and a thermos of tea or coffee on your desk. You don’t have to stand up all the time.</li><li>Wear comfortable clothes, it makes you feel good.</li><li>You should ventilate by opening the door or window of your study room from time to time.</li><li>If you have time during your lunch break, go for a walk and try to get fresh air or go out to the balcony and enjoy the view.</li><li>If you don’t want to feel waist, back, joint or muscle pain, you should workout regularly every day.</li><li>Cook the meals you’re going to eat next week at the weekend. You may not have time to prepare meals during the week. Consuming unhealthy foods from outside is not a long-term solution.</li><li>I recommend getting a screen glass for eye protection. Blue light blocking glasses can help reduce eye strain.</li><li>Working from home can become unbearable if the weather is very hot in the summer. That’s why I recommend having an air conditioner in your home.</li><li>If you don’t have to look at the screen during the meeting, put on your headphones and walk around the house.</li></ul><p>These are the tips that have helped me so far.</p><p>Finally, life sometimes pushes us we couldn’t expect. In this transition period, some people lost their jobs. Some people have a new job created. Many entrepreneurs turned the crisis into an opportunity. So, we should be alerted. Are we prepared for these kinds of changes? We should enhance our skills to keep up with the changing life, sometimes to just survive, sometimes to do better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a97daec12b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Primitive Types, Operators and Flow Control Statements]]></title>
            <link>https://semihkirdinli.medium.com/primitive-types-operators-and-flow-control-statements-7a35c7b7429e?source=rss-bf035e5c6845------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a35c7b7429e</guid>
            <category><![CDATA[operators]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[control-flow-statement]]></category>
            <category><![CDATA[primitive-type]]></category>
            <dc:creator><![CDATA[Semih Kırdinli]]></dc:creator>
            <pubDate>Sun, 02 May 2021 23:51:55 GMT</pubDate>
            <atom:updated>2023-06-04T22:07:27.453Z</atom:updated>
            <content:encoded><![CDATA[<h4>Java Primitives:</h4><p>Java language provides 8 primitive types to represent simple numeric, character and boolean values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*aEhPNJo0BWWp5Gl66MqziQ.png" /></figure><h4>Declare and Initialize Primitive Variables:</h4><p>Primitive declaration and initialization rules:<br><em>&lt;type&gt; &lt;variable name&gt; = &lt;value&gt;;<br>- </em>Numeric values can be expressed as <em>binary</em>, <em>octal</em>, <em>decimal</em> and <em>hex</em>.<br>- Smaller types are automatically casted (promoted) to bigger types.<br><em>byte -&gt; short -&gt; char -&gt; int -&gt;long -&gt; float -&gt; double</em></p><pre>int a= 0b101010; // binary         float e = 1.99E2F;<br>short b = 052;    // octal         double f = 1.99;<br>byte c = 42;      // decimal       long g = 5, h = c;<br>long d = 0x2A     // hex           float i = g;<br>                                   char j = &#39;A&#39;;<br>                                   char k = &#39;\u0041&#39;, l = &#39;\101&#39;;<br>                                   int s; s = 77;</pre><h4>Restrictions on Primitive Declarations and Initialization:</h4><p>- Variables must be initialized before use.<br>- A bigger type value cannot be assigned to a smaller type without explicit type casting. Type can be explicitly casted using the following syntax.<br> <em>(new type)&lt;variable or expression&gt;</em><br>- Character values must be enclosed in single quotation marks.<br>- Boolean values can be expressed only as true or false.</p><pre>byte a;                             boolean h = &quot;true&quot;;<br>byte b = a;                         boolean i = &#39;false&#39;;<br>byte c = 128;                       boolean j = 0;<br>int d = 42L;                        boolean k = False;<br>float e = 1.2;<br>char f = &quot;a&quot;;<br>char g = &#39;AB&#39;;                      // these are wrong examples</pre><h4>Java Operators:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*seXrqpD3Mu4F6Nx4uqWzLQ.png" /></figure><pre>byte a = 127, b = 5;<br>byte c = a + b;         //compilation fails<br>int d = a + b;          //d is 132<br>byte e = (byte)(a + b); //e is -124 (type overflow 127 max)<br>int  f = a / b;         //f is 25<br>float g = a / b;        //g is 25.0F implicitly casted to float<br>float h = (float)(a/b); //h is 25.0F explicitly casted to float<br>float i = (float)a/b;   //i is 25.4F when either a or b is float<br>float j = a/(float)b;   //j is 25.4F float the a/b becomes float<br>b = (byte)(b+1);        //explicit casting is required,b+1 is an int<br>b++;                    //no casting is required for ++ and --<br>char x = &#39;x&#39;;           //arithmetic operations work with character char y = ++x;           //codes</pre><h4>Binary Number Representation:</h4><p>All Java numeric primitives are signed.<br>- For example a byte zero value is represented as the 00000000 sequence of bits.<br>- Changing a sign(negative or positive) is done by inverting all the bits and then adding one to the result.<br>- For example a byte value of one is represented as 00000001 and minus one is 11111111.<br>- Bitwise Compliment operator inverts all bits of a number. The result of the bitwise compliment operator ~a would be its “mirrored” binary value: -(a+1)</p><pre>int a = 2;<br>int b = ~a;             //b is -3</pre><h4>Equality, Relational and Conditional Operators:</h4><p>Returns true or false values as a result.<br>==, !=, &gt;, &gt;=, &lt;, &lt;=, !, &amp;&amp;, ||, &amp;, |, ^<br><strong><em>Note:</em></strong><em> Compilation fails because a block containing more than one statement must be enclosed with { }.</em></p><pre>int a = 2, b = 3;<br>if(a &gt; b)<br>   a--;                 //it fails<br>else<br>   a++;</pre><h4>Flow Control Using switch Construct:</h4><p>Switch expression must be of one of the following types: <em>byte, short, int, char, String, enum</em>.<br>- Execution flow continuous until it reach the end of switch or encounters an optional <em>break</em> statement.</p><pre>char status = &#39;N&#39;;<br>double price = 10;<br>switch (status) {<br>   case &#39;S&#39;:<br>      price += 1;<br>   case &#39;N&#39;: <br>      price += 2;       //price is 12<br>   case &#39;D&#39;:<br>      price -= 4;       //price is 8<br>      break;            //flow is completed , break statement<br>   case &#39;E&#39;:<br>      price = 0;<br>      break;<br>   default:<br>      price = 3;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a35c7b7429e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Java]]></title>
            <link>https://semihkirdinli.medium.com/introduction-to-java-6fdd9c46a153?source=rss-bf035e5c6845------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fdd9c46a153</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-language]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[java-se-8]]></category>
            <dc:creator><![CDATA[Semih Kırdinli]]></dc:creator>
            <pubDate>Sun, 02 May 2021 23:45:55 GMT</pubDate>
            <atom:updated>2021-05-03T00:33:01.031Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’m going to try to explain how to write code in Java programming language. This will be a series of article that begin with an Introduction to Java.</p><p>You will be learning the basics as well as the information that is not used much. These articles covers <strong>Java SE(Standart Edition)</strong>.</p><p>Let’s begin.</p><p><strong>What is Java?</strong><br>- Java is an object oriented programming language inspired by the C ++ programming language.<br>- It is platform independent. It can work on any platform.<br>- Java source code is written as plain text <strong>.java </strong>files, and compiled into byte-code <strong>.class</strong> files for JVM. Java Virtual Machine must be installed on a target computer.<br>- JVM translates Java byte-code instructions to platform-specific code.</p><p><em>javac HelloWorld.java -&gt; HelloWorld.class (compiled class)</em></p><p><strong>Classes and Objects:<br></strong>Class and Object are two key of object oriented concept. Java code is structured with classes. <br>- Class represents a type of thing or a concept, such as <em>Car</em>.<br> Each class can store some information<strong>(attributes): </strong><em>color, type, size.</em><br> Each class can contain program logic<strong>(behaviors): </strong><em>Car could go fast or slow, but could not fly.</em><br>- Object is a specific type of a class. Each object has specific values: A car has white color, another car may be black.</p><pre>class HelloWorld { //attributes and behaviours }</pre><p><strong>Inheritance(extends): <br>- </strong>Inheritance is an idea that you could have classes that are very generic and quiet specific. <br>- Generic classes describe some attributes and behaviours that should be common for many other classes. <br>- Specific classes can inherit these common attributes and behaviours from generic ones.</p><pre>class Car extends Vehicle { // generic attributes and behaviours }<br>class Maruti extends Car { // specific attributes and behaviours }</pre><p><strong>Java APIs:<br></strong>JDK provides hundreds of classes for various programming purposes such as String, ArrayList. Application Program Interface(API) is a term that describes a collection of classes that are designed to serve a common purpose. All Java APIs are documented for each version of language.<br><a href="https://docs.oracle.com/en/java/javase/16/docs/api/"><em>https://docs.oracle.com/en/java/javase/16/docs/api/</em></a></p><p><strong>Define Java Class:<br>- </strong>Class name is typically represented by one or more nouns.<br>- Class must be saved into a file with the same name as the class and extension .java<br>- Classes grouped into packages. Packages are folders where class files are saved.<br>- To access a class in another package, prefix the class name with the package name or <strong>import</strong> statement (java.lang.* package is implicitly assumed).</p><pre>package vehicle;<br>public class Car { }</pre><pre>package anotherPackage;<br>import vehicle;<br>public class Owner { Car car; }</pre><p><strong>Use Access Modifiers:<br></strong>Access modifiers describe the visibility of classes, variables, methods.<br><strong>public:</strong> Visible to any other class.<br><strong>protected:</strong> Visible to classes that are in the same package or to subclasses.<br><strong>&lt;default&gt;:</strong> Visible only to classes in the same package.<br><strong>private:</strong> Visible only to within the same class.</p><p><strong>Create Main Application Class:<br>- </strong>The main method is the entry point into your application.<br>- The method must be public, static, void. Method name must be called main and accept array of String objects as the only parameter.</p><pre>public class HelloWorld { <br>   public static void main(String[] args) {<br>      // program execution starts here<br>   }<br>}</pre><p><strong>Compile Java Program:<br></strong>Compile classes with the <strong>javac </strong>Java compiler.<br>The <strong>-classpath</strong> or <strong>-cp</strong> parameter points to location of the other classes that may be required to compile your code.<br>The <strong>-d</strong> parameter points to a path to store compilation results.</p><p><em>$javac </em><strong><em>-cp</em></strong><em> target/classes </em><strong><em>-d</em></strong><em> target/classes src/main/java/HelloWorld.java</em></p><p><strong>Execute Java Program:<br>- </strong>Execute program using java executable JVM.<br>- Specify -classpath or -cp to point to folders where your classes are located.<br>- Specify fully qualified class name. Use package prefix, don’t use the .class extension.<br>- Provide a space separated list of parameters after the class name.</p><p><em>$java </em><strong><em>-cp</em></strong><em> target/classes src/main/java/HelloWorld.java x y “z”</em></p><p>Since Java 11, it is also possible to run single-file source code as if it is a compiled class. JVM will interpret your code, but not compiled class file would be created.</p><p><em>$java src/main/java/HelloWorld.java</em></p><p><strong>Comments and Documentation:<br>- </strong>Code comments can be placed anywhere in your source code.<br>- Documentation comments:<br> *May contain HTML markups.<br> *May contain descriptive tags prefixed with @ sign.<br> *Are used by the <em>javadoc</em> tool to generate documentation.</p><pre>// single-line comment</pre><pre>/* <br>   multi-line comment <br>*/</pre><pre>/**<br> * documentation comment {@code Whatever} * @version 1.0<br> * @author oracle<br> */</pre><p><em>$javadoc </em><strong><em>-d</em></strong><em> &lt;documentation path&gt; </em><strong><em>-sourcepath</em></strong><em> &lt;source code path&gt;</em><strong><em>-subpackages</em></strong><em> &lt;name of the root package&gt;</em></p><p><strong>Java Keywords, Reserved Words, and a Special Identifier:</strong><br><em>if, else, continue, break, for, do, while, switch, case, default, private, protected, public, import, package, abstract, implements, extends, interface, class, static, final, return, transient, void, byte, short, int, long, char, float, double, boolean, try, catch, finally, throw, throws, new, this, super, instanceof, native, synchronized, volatile, strictfp, assert, enum, module, requires, transitive, exports to, uses, provides, with, opens to, true, false, null, var</em></p><p>See the next episode:<br><a href="https://semihkirdinli.medium.com/primitive-types-operators-and-flow-control-statements-7a35c7b7429e"><strong>Primitive Types, Operators and Flow Control Statements</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fdd9c46a153" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nesne Yönelimli Programlama’nın Temel Prensipleri]]></title>
            <link>https://semihkirdinli.medium.com/nesne-y%C3%B6nelimli-programlaman%C4%B1n-temel-prensipleri-8d8afd034e49?source=rss-bf035e5c6845------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d8afd034e49</guid>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[soyutlama]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[abstraction]]></category>
            <category><![CDATA[encapsulation]]></category>
            <dc:creator><![CDATA[Semih Kırdinli]]></dc:creator>
            <pubDate>Tue, 08 Sep 2020 20:50:02 GMT</pubDate>
            <atom:updated>2021-05-02T23:53:12.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*dabhHRT1LU5B982nQFRQlw.png" /></figure><p>Nesne Yönelimli Programlama(Object Oriented Programming) Java’nın temelidir. Tüm nesne yönelimli programlama dilleri, nesne yönelimli modeli uygularken size yardımcı olan mekanizmaları içerir.</p><p>Nesne Yönelimli Programlama teorisinde 4 temel özelliğin gerçekleştirilmesi zorunlu sayılmıştır. Bir tanesi bile eksik olduğunda dil saf Nesne Yönelimli Programlama yaklaşımına uygun olmamaktadır. Bu özellikler:</p><ul><li>Sarmalama(Encapsulation),</li><li>Kalıtım(Inheritance),</li><li>Çok Biçimlilik(Polymorphism),</li><li>Soyutlama(Abstraction)</li></ul><h3>Sarmalama(Encapsulation)</h3><p>Bu özellik, dilin nesne kullanıcısından gereksiz uygulama ayrıntılarını saklar. Oluşturulan bir sınıf(class) içinde kullanıcının işlemleri daha kolay gerçekleştirebilmesi için bazı işlemler birleştirilerek tek bir işlem gibi gösterilir. Bu birleştirme işlemine <strong>sarmalama(encapsulation)</strong> denir.</p><p>Erişim belirteçleri(access modifier) sayesinde encapsulation çok daha kolay yapılmaktadır. Erişim belirteçleri, oluşturulan sınıf veya sınıf içindeki elemanların erişim seviyelerini belirlemek için kullanılan anahtar kelimeler grubuna verilen isimdir. Encapsulation <strong>private</strong> değişkenlerin metotlar gibi kullanılmasına yardımcı olur. Okuma(read only) işleminin yanısıra okuma-yazma(read-write) işleminin yapılmasını sağlar. Özetle sınıfı kontrolsüz değişime kapamak için kullanılır diyebiliriz. Böylelikle yanlış işlemlerin gerçekleşmeyeceğinden emin olabiliriz.</p><pre>package encapsulation;</pre><pre>public class Student {<br>  public int id;<br>  public String name;<br>  public String schoolNumber;<br>  private double score;</pre><pre><em>  // set metoduyla uygun değer geldiğinde score alanına atama yapılır.<br>  </em>public void setScore(double value) {<br>    if (value &gt; 0 &amp;&amp; value &lt; 100) <br>      score = value;</pre><pre>    else //uygun olmaması durumunda kullanıcıya hata mesajı verilir.<br>      System.out.println(&quot;score is invalid&quot;);<br>  }<br>    <br>  public double getScore() {<br>    return score;<br>  }<br>}</pre><p>Program sınıfında bir student nesnesi oluşturulup değer ataması aşağıdaki şekilde yapılır:</p><pre>package encapsulation;<br>import java.util.Scanner;</pre><pre>public class Program {<br>  public static void main(String[] args) {<br>    <br>    double value;<br>    Student student = new Student();<br>        <br>    Scanner scanner = new Scanner(System.in);<br>    value = scanner.nextDouble();<br>    student.setScore(value);<br>    System.out.print(student.GetScore());<br>  }<br>}</pre><p>Örnekte student nesnesinin score bilgisine doğrudan değer atanmadığı görülüyor. Program.java sınıfı içinde student.score=value şeklinde atama yapılmak istendiğinde(score değişkeninin erişim belirteci private olduğundan) kod parçası hata verecektir. Bunun yerine student.setScore(value) şeklinde metot çağrılarak değer atamasının yapılması sağlanmıştır. Setter metotlarını kaldırsaydık ve yeni bir constructor oluşturarak sınıfın içinde yer alan tüm değişkenleri bu constructor&#39;da set etseydik, bu sınıfı kullanan istemci sadece nesne üretirken değer ataması yapabilecek, sonradan bu değerler değiştirilemeyecekti. Böyle sınıflara immutable sınıf adı verilir. Immutable olarak tasarlanan sınıflar çok kanallı programlamada thread korumalıdır(thread safe). Değişmez sınıf nesnelerinin içerikleri değişmeyeceği için program akışı içinde içerikte istenmeyen değişikliklerin olmasının önüne geçecektir.</p><h3>Kalıtım(Inheritance)</h3><p>Bir nesnenin başka bir nesnenin özelliklerini devralması olayına <strong>kalıtım(inheritance)</strong> denir. Bu, hiyerarşik sınıflandırma kavramını desteklediği için önemlidir. Örnek vermek gerekirse köpek, memeli ve hayvan sınıfları olduğunu düşünelim. Örneğin Golden, hayvanlar sınıfı altındaki memeliler sınıfının bir parçası olan köpek sınıflandırmasındadır. Hiyerarşi kullanımı olmasaydı, her bir sınıfın ihtiyacı olan tüm karakteristiklerin açıkça tanımlanması gerekirdi. Ancak kalıtımın kullanılmasıyla sadece sınıf içinde kendine has özelliklerin tanımlanması yeterli olur. Genel nitelikler üst sınıftan devralınabilir. Böylece kalıtım sayesinde bir nesne daha genel bir başka nesnenin belirli bir örneği olabilir.</p><ul><li><strong>Hayvan</strong> -&gt; Büyüklük, Zeka, İskelet Sistemi Tipi, Yerler, Nefes Alırlar, Uyurlar</li><li><strong>Memeliler</strong> -&gt; Diş Tipi, Meme Bezleri</li></ul><p>Memeliler, daha kesin olarak tanımlanmış hayvanlar olduğundan, hayvanların tüm niteliklerini devralırlar. Türetilen bir alt sınıf, sınıf hiyerarşisinde atalarının tüm niteliklerini devralır.</p><h3>Çok Biçimlilik(Polymorphism)</h3><p>Birden fazla sınıfın ortak kullanacağı bir metot varsa, bu metot her bir sınıfın kalıtım alacağı ana sınıf içerisinde tanımlanabilir. Davranış şekillerindeki farklılıklar ise her sınıfın kendi yapısı içinde ifade edilir.</p><p>Bir kalıtım ağacına ait sınıflarda aynı imza(dönüş tipi, ad, parametreler) ile tanımlanmış bir metot varsa, Java ortamı çalıştırma zamanında metodun hangi sınıfa ait tanımdan çalıştırılacağını dinamik olarak belirleyebilir. Bu özelliğe <strong>çok biçimlilik(polymorphism)</strong> denir.</p><p>Aşağıdaki örnekte Animal ana sınıfına ait sound metodu çağrılıyor. Hayvan ana sınıfından domuz, kedi, köpek, kuş gibi sınıflar türetilebilir. Onlar hayvan sesini kendi içlerinde farklılaştırabilir ve sound metoduna farklı görevler yükleyebilir. Böylece nesne yönelimli programlanın çok biçimlilik özelliği, tek bir eylemi farklı şekillerde gerçekleştirmemizi sağlar.</p><pre>package polymorphism;</pre><pre>public class Animal {<br>  public void sound() {<br>    System.out.println(&quot;The animal makes a sound&quot;);<br>  }<br>}</pre><pre>public class Pig extends Animal {<br>  public void sound() {<br>    System.out.println(&quot;The pig says: wee wee&quot;);<br>  }<br>}</pre><pre>public class Dog extends Animal {<br>  public void sound() {<br>    System.out.println(&quot;The dog says: bow wow&quot;);<br>  }<br>}</pre><pre>public class Program {<br>  public static void main(String[] args) {<br>    Animal myAnimal = new Animal();  // Create an Animal object<br>    Animal myPig = new Pig();  // Create a Pig object<br>    Animal myDog = new Dog();  // Create a Dog object<br>    myAnimal.sound();<br>    myPig.sound();<br>    myDog.sound();<br>  }<br>}</pre><h3>Soyutlama(Abstraction)</h3><p>Alt sınıfların ortak özelliklerini, işlevlerini taşıyan ancak bir nesne oluşturulamayan üst sınıflara <strong>soyut(abstract) sınıflar</strong> denir. Soyut sınıf içinde şablon olması açısından metot tanımları yapılabilir veya <strong>soyut metotlar</strong> yazılabilir. Soyut metoda sahip bir sınıf soyut hale gelir ve soyut sınıflardan nesne oluşturulamaz.</p><p>Java dilinde bir sınıfı soyut olarak tanımlamak için <strong>abstract</strong> veya <strong>interface</strong> anahtar sözcükleri kullanılır.</p><p>Aşağıda yer alan kod parçasında Employee tipinde bir soyut sınıf ve bu soyut sınıftan türeyen Contractor ve FullTimeEmployee tipinde 2 farklı alt sınıf vardır.</p><p>Her iki tip Employee nesnesinin de name ve paymentPerHour bilgisi olacağından bu özellikler üst sınıfta tanımlanmıştır. Ancak çalışanların saatlik çalışma ücretini hesaplayan metot calculateSalary(), alt sınıfların kendi içinde farklılık göstermektedir. Bu implementasyonun abstract sınıf kullanılarak soyutlanması sağlanmıştır.</p><pre>package abstraction;</pre><pre>public abstract class Employee {<br>    <br>    private String name;<br>    private int paymentPerHour;<br>    <br>    public Employee(String name, int paymentPerHour) {<br>        this.name = name;<br>        this.paymentPerHour = paymentPerHour;<br>    }<br>    <br>    public abstract int calculateSalary();</pre><pre>    public String getName() {<br>        return name;<br>    }</pre><pre>    public void setName(String name) {<br>        this.name = name;<br>    }</pre><pre>    public int getPaymentPerHour() {<br>        return paymentPerHour;<br>    }</pre><pre>    public void setPaymentPerHour(int paymentPerHour) {<br>        this.paymentPerHour = paymentPerHour;<br>    }<br>}</pre><pre>public class Contractor extends Employee {<br>    private int workingHours;</pre><pre>    public Contractor(String name, int paymentPerHour, int workingHours) {<br>        super(name, paymentPerHour);<br>        this.workingHours = workingHours;<br>    }</pre><pre>    @Override<br>    public int calculateSalary() {<br>        return getPaymentPerHour() * workingHours;<br>    }<br>}</pre><pre>public class FullTimeEmployee extends Employee {<br>    public FullTimeEmployee(String name, int paymentPerHour) {<br>        super(name, paymentPerHour);<br>    }<br>    <br>    @Override<br>    public int calculateSalary() {<br>        return getPaymentPerHour() * 8;<br>    }<br>}</pre><p>Bir sonraki makalede görüşmek üzere…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d8afd034e49" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>