<?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 ugur suicmez on Medium]]></title>
        <description><![CDATA[Stories by ugur suicmez on Medium]]></description>
        <link>https://medium.com/@ugur.suicmez?source=rss-7521e143f46d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-kQzNUA0VtkIK8vO</url>
            <title>Stories by ugur suicmez on Medium</title>
            <link>https://medium.com/@ugur.suicmez?source=rss-7521e143f46d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 20:45:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ugur.suicmez/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[REST API]]></title>
            <link>https://medium.com/@ugur.suicmez/rest-api-a25d6b638723?source=rss-7521e143f46d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a25d6b638723</guid>
            <dc:creator><![CDATA[ugur suicmez]]></dc:creator>
            <pubDate>Mon, 14 Feb 2022 21:20:19 GMT</pubDate>
            <atom:updated>2022-02-15T06:10:48.621Z</atom:updated>
            <content:encoded><![CDATA[<p>What is REST API? What are the features of REST, what is URI? WHich http methods do REST APIs use?</p><p>In this article, I’ii try to mention about What REST API is, What the features of REST , what URI is and WHich http methods REST APIs use.</p><h3>What is REST API?</h3><p><strong>RE</strong>presentational <strong>S</strong>tate <strong>T</strong>ransfer. A REST API (also known as RESTful API) is an application programming interface (API or web API) that conforms to the constraints of REST architectural style and allows for interaction with RESTful web services. REST stands for representational state transfer and was created by computer scientist Roy Fielding.</p><p>REST is a set of architectural constraints, not a protocol or a standard. API developers can implement REST in a variety of ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*wxBxfz07euAE5sH4.png" /></figure><h3>Features:</h3><ol><li>Stateless</li><li>Uniform Interface</li><li>Cacheable</li><li>Client-Server</li><li>Layered System</li><li>Code on Demand</li></ol><h4>Stateless</h4><p>client-server communication, meaning no client information is stored between get requests and each request is separate and unconnected.</p><h4>Uniform Interface</h4><ul><li>resources requested are identifiable and separate from the representations sent to the client. <a href="https://tools.ietf.org/html/rfc3986">URI</a>. is used to provide this.</li><li>resources can be manipulated by the client via the representation they receive because the representation contains enough information to do so.</li><li>self-descriptive messages returned to the client have enough information to describe how the client should process it.</li><li><em>Client uses </em>request <em>body</em>, <em>query-string</em> parameters, <em>header</em>s and URI.during sending request. Server use <em>response </em>body, <em>response code </em>and <em>response header in order to sending response.</em></li></ul><h4>Cacheable</h4><p>Server gives information that resource is <em>cacheable </em>or <em>uncacheable </em>during <em>sending response</em></p><h4>Client-Server</h4><p>high scability</p><h4>Layered System</h4><p>security layer, caching layer</p><h4>Code On Demand</h4><p>client can send executable <em>scripts</em> ve <em>applets to server</em></p><h3>URI</h3><p>URI (<em>Uniform Resource Identifier)</em> is used in order to adressed REST resources</p><h4>URI Hierarchy</h4><p>URI uses <em>forward slash(/) character to </em>provide hierarchy</p><p><a href="https://api.ornek.com/v1/users/234234/unread-messages/1">https://api.example.com/v1/users/234234/unread-messages/1</a></p><ul><li>under score (_) is not used. using (-) instead of.</li><li>always use lower case. Fragments in URI except host and scheme are case-sensitive. Examples below express different things</li></ul><blockquote><a href="https://api.ornek.com/users/123/docs/456">https://api.example.com/users/123/docs/456</a><br>https://api.<a href="https://api.ornek.com/users/123/docs/456">example</a>.com/users/123/Docs/456</blockquote><p><em>scheme is</em>https and <em>host</em> is api.ornek.com</p><ul><li>URI doesnt include file extention. instead of this, using <em>Content-Type in header is </em>a better approach</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*3FUxxUDA71KfLPL7.png" /></figure><h4>Resource Models</h4><h4>Document:</h4><p>it can be instance or database record. Singular nomenclature is used.</p><p><a href="https://api.ornek.com/v1/artists/54352">https://api.example.com/v1/artists/54352</a><br>https://api<a href="https://api.ornek.com/v1/artists/54352">.example</a>.com/v1/artists/54352/albums/2<br>https://api<a href="https://api.ornek.com/v1/artists/54352">.example</a>.com/v1/cities/ankara<br>https://api<a href="https://api.ornek.com/v1/artists/54352">.example</a>.com/v1/cities/ankara/districts/yenimahalle</p><h4>Collection:</h4><p>document resource list. Plural nomenclature is used</p><blockquote><a href="https://api.ornek.com/v1/artists">https://api</a><a href="https://api.ornek.com/v1/artists/54352">.example</a><a href="https://api.ornek.com/v1/artists">.com/v1/artists</a><br>https://api<a href="https://api.ornek.com/v1/artists/54352">.example</a>.com/v1/artists/54352/albums<br>https://api<a href="https://api.ornek.com/v1/artists/54352">.example</a>.com/v1/cities<br>https://api<a href="https://api.ornek.com/v1/artists/54352">.example</a>.com/v1/cities/ankara/districts</blockquote><h4>Store:</h4><p>resource managed by client. Plural nomenclature is used</p><blockquote><a href="https://ornek.com/api/v1/playlists/123/songs">https://exa.com/api/v1/playlists/123</a>/songs</blockquote><h4>Controller:</h4><p>if HTTP method doesnt meet the need Controller method is used. Contoller is a POST method with using verbs instead of documents.</p><blockquote><em>https://api.Example.com/v1/alerts/4234/resend</em></blockquote><h4>Using query in URI</h4><p>it is used adressing unhierarchical things.</p><blockquote><a href="https://ornek.com/api/v1/categories/1/posts?page=4">https://example.com/api/v1/categories/1/posts?page=4</a><br>https://<a href="https://ornek.com/api/v1/categories/1/posts?page=4">example</a>.com/api/v1/categories/1/posts?orderby=desc&amp;name=bob</blockquote><h3>URI Query Design</h3><h4>Rule 1: As a component of a URI, the query contributes to the unique identification of a resource. Consider the following example:</h4><pre>api.college.restapi.org/students/morgan/send-sms<br>api.college.restapi.org/students/morgan/send-sms?text=hello</pre><p>The URI of a controller resource that sends an sms message.</p><ol><li>The URI of a controller resource that sends an sms message with a text value of hello</li></ol><h4>Rule 2: The query component of a URI may be used to filter collections or stores</h4><p>A URI’s query component is a natural fit for supplying search criteria to a collection or store. Let’s take a look at an example:</p><pre>GET /users <br>GET /users?role=admin</pre><p>The response message’s state representation contains a listing of all the users in the collection. The response message’s state representation contains a filtered list of all the users in the collection with a “role” value of admin.</p><h4>Rule 3: The query component of a URI should be used to paginate collection or store results</h4><p>A REST API client should use the query component to paginate collection and store results with the pageSize and pageStartIndex parameters. The pageSize parameter specifies the maximum number of contained elements to return in the response. The pageStartIndex parameter specifies the zero-based index of the first element to return in the response. For example:</p><pre>GET /users?<strong>pageSize</strong>=25&amp;<strong>pageStartIndex</strong>=50</pre><h3>Identifier Design with URIs</h3><h4>Rule 1: Forward slash separator / must be used to indicate a hierarchical relationship</h4><p>The forward slash / character is used in the path portion of the URI to indicate a hierarchical relationship between resources.</p><p>Example:</p><pre>api.canvas.restapi.org/shapes/polygons/quadrilaterals/squares</pre><blockquote><em>Adding </em><em>/slash to end of the url not give any meaning, it’s only make confusion.<br>The basically REST API must generate and communicate clean URIs.</em></blockquote><h4>Rule 2: Hyphens (-) should be used to improve the readability of URIs</h4><p>To make your URIs easy for people to scan and interpret, use the hyphen (-) character to improve the readability of names in long path segments. Anywhere you would use a space or hyphen in English, you should use a hyphen in a URI. For example:</p><pre>api.example.restapi.org/blogs/mark-masse/entries/my-first-post</pre><h4>Rule 3: Underscores (_) should not be used in URIs</h4><p>Text viewer applications (browsers, editors, etc.) often underline URIs to provide a visual cue that they are clickable. Depending on the application’s font, the underscore (_) character can either get partially obscured or completely hidden by this underlying.</p><p>To avoid this confusion, use hyphens (-) instead of underscores (as described in “Rule: Hyphens (-) should be used to improve the readability of URIs” on Rule 3).</p><h4>Rule 4: Lowercase letters should be preferred in URI paths</h4><p>When convenient, lowercase letters are preferred in URI paths since capital letters can sometimes cause problems. RFC 3986 defines URIs as case-sensitive except for the scheme and host components. For example:</p><pre><a href="http://api.example.restapi.org/my-folder/my-doc">http://api.example.restapi.org/my-folder/my-doc</a> <a href="http://http//API.EXAMPLE.RESTAPI.ORG/my-folder/my-doc">HTTP://API.EXAMPLE.RESTAPI.ORG/my-folder/my-doc</a></pre><p><em>The above URI is fine. The URI format specification (RFC 3986) considers this URI to be identical to URI #1.</em></p><pre><a href="http://api.example.restapi.org/My-Folder/my-doc">http://api.example.restapi.org/My-Folder/my-doc</a></pre><p><em>This URI is not the same as URIs 1 and 2, which may cause unnecessary confusion.</em></p><h4>Rule 5: File extensions should not be included in URIs</h4><p>A REST API should not include artificial file extensions in URIs to indicate the format of a message’s entity body. Instead, they should rely on the media type, as <strong>communicated through the Content-Type header</strong>, to determine how to process the body’s content.</p><pre>api.college.restapi.org/students/3248234/transcripts/2005/<strong>fall.json<br></strong>api.college.restapi.org/students/3248234/transcripts/2005/<strong>fall</strong></pre><p>To enable simple links and easy debugging, a REST API may support media type selection via a query parameter as discussed in next Rule 6.1</p><h4>Rule 6: Consistent subdomain names should be used for your APIs</h4><p>The top-level domain and first subdomain names (e.g., soccer.restapi.org) of an API should identify its service owner. The full domain name of an API should add a subdomain named api.<br>For example:</p><p><a href="http://api.soccer.restapi.org/">http://<strong>api</strong>.soccer.restapi.org</a></p><h4>Rule 7: Consistent subdomain names should be used for your client developer portal</h4><p>Many REST APIs have an associated website, known as a <strong>developer portal</strong>, to help onboard new clients <strong>forums,</strong> and <strong>self-service provisioning of secure API access keys</strong>.</p><pre><a href="http://developer.soccer.restapi.org/">http://<strong>developer.</strong>soccer.restapi.org</a></pre><h3>Resource Modeling</h3><p>The URI path conveys a REST API’s resource model, with each forward slash separated path segment corresponding to a unique resource within the <strong>model’s hierarchy.</strong></p><pre><a href="http://api.cricket.restapi.org/leagues/ipl/teams/mumbai-indians">http://api.cricket.restapi.org/<strong>leagues/ipl/teams/mumbai-indians</strong></a></pre><p>indicates that each of these URIs should also identify an <strong>addressable resource</strong>:</p><pre><a href="http://api.cricket.restapi.org/leagues/ipl/teams">http://api.cricket.restapi.org/leagues/ipl/teams</a> <a href="http://api.cricket.restapi.org/leagues/ipl">http://api.cricket.restapi.org/leagues/ipl</a> <a href="http://api.cricket.restapi.org/leagues">http://api.cricket.restapi.org/leagues</a> <br>http://api.cricket.restapi.org</pre><p>Resource modeling is an exercise that establishes your API’s key concepts. This process is similar to the <strong>data modeling for a relational database schema or the classical modeling of an object-oriented system.</strong></p><h3>Using HTTP method in REST</h3><ul><li><strong>GET</strong></li></ul><p>use to get resources. Get request doesnt include body. it has only header.</p><blockquote>curl -XGET ‘https://jsonplaceholder.typicode.com/todos/1&#39;</blockquote><ul><li><strong>HEAD</strong></li></ul><p>body isn’t sent in response. The method is used due to checking URI exists or not or getting URI last modifed date or etc.</p><ul><li><strong>POST</strong></li></ul><p>it is used in order to create new resource’s record along server side or prepare controllers. Body is sent in request.</p><ul><li><strong>PUT</strong></li></ul><p>it is used in order to update existing resource along server. Body is sent in request.</p><ul><li><strong>DELETE</strong></li></ul><p>it is used in order to delete existing resource physically along server. Body is not sent in request. if needed soft delete, <em>application-spesific controller should be written.</em></p><ul><li><strong>OPTIONS</strong></li></ul><p>it is used due to getting information of which methods supports inURI is sent request.</p><ul><li><strong>PATCH</strong></li></ul><p>although it is similar to PUT method. PATCH is used partial updates to the resource.</p><h4>Safe ve Idempotent Metods</h4><p>Read-only methods <em>GET</em>, <em>HEAD</em>, <em>OPTIONS</em> ve <em>TRAC E</em> are safe methods.</p><p>Methods which response the same result are idempotent. So entire methods except POST method are idempotent.</p><h3>Response Codes</h3><ul><li>1xx Information</li><li>2xx successful</li><li>3xx Redirect</li><li>4xx Client Error</li><li>5xx Server Error</li></ul><h3>HTTP response success code summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Y8g_NoeTulJvajYB" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*V0SSPe3BPxZ4m43B" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a25d6b638723" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Code]]></title>
            <link>https://medium.com/@ugur.suicmez/clean-colde-41ddb789da4e?source=rss-7521e143f46d------2</link>
            <guid isPermaLink="false">https://medium.com/p/41ddb789da4e</guid>
            <dc:creator><![CDATA[ugur suicmez]]></dc:creator>
            <pubDate>Tue, 04 Jan 2022 13:34:22 GMT</pubDate>
            <atom:updated>2022-02-10T17:15:29.665Z</atom:updated>
            <content:encoded><![CDATA[<p>clean code with real code practices</p><p><strong><em>“It’s not enough to write the code well. The code has to be kept clean over time … Leave the campground cleaner than you found it (Boy Scout Rule).”<br></em></strong> — Robert C. Martin</p><p>Clean code is characterized by being elegant, efficient, readable, minimal, doing only one thing well in a single way, and having unit tests. Like a broken window, wrong code is the beginning of disaster. We read 10:1 more code than we write, and we won’t be able to write code if the surrounding code is unreadable.</p><h3>General rules</h3><ul><li>Follow <strong>standard conventions.</strong><br>X <em>List&lt;Kullanici&gt; kullaniciListesi;</em> , <em>List&lt;Integer&gt; years;</em><br>✓ <em>List&lt;Kullanici&gt; kullanicis;</em> , <em>List&lt;Integer&gt; years; //able to use english naming except domain objects and functions</em></li><li>Keep it <strong>simple</strong>, stupid. Simpler is always better. Reduce complexity as much as possible.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vAQ1d4i2-Fw2Zu1t8w5CFw.png" /><figcaption>X</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8VaEadmAhMg2xeloIPoM-w.png" /><figcaption><em>✓</em></figcaption></figure><ul><li><strong>Boy scout rule</strong>: Leave the campground cleaner than you found it.</li><li>Always find the <strong>root cause</strong>. Always look for the root cause of a problem. dont do bypass</li><li><strong>Don’t repeat</strong> yourself (DRY).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37NG1Ftlqvyej0ztVRFDBA.png" /><figcaption>X</figcaption></figure><p>✓ should create a class and static function. The function should be called everywhere needed.</p><ul><li><em>You Ain’t Gonna Need It (</em>YAGNI<em>)</em></li></ul><h3>Design rules</h3><ul><li>Keep configurable data (e.g.: constants) at high levels. They should be <strong>easy to change.</strong><br>X klasorListesi.removeIf(k -&gt; k.getType().equals(“file”));<br>✓ klasorListesi.removeIf(k -&gt; k.getType().equals(FILE)); //use constant</li><li>Prefer <strong>polymorphism</strong> to if/else or switch/case.</li><li>Separate multi-threading code.</li><li>Prevent over-configurability.</li><li>Use <strong>dependency injection</strong>.</li><li>Follow the <strong>Law of Demeter</strong>: A class should know only its direct dependencies.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXkcFdBHgyvJu_cW4FSkvw.png" /><figcaption>X</figcaption></figure><p>✓ should know only projeYonetimService</p><h3>Understandability tips</h3><ul><li>Be <strong>consistent</strong>. If you do something a certain way, do all similar things in the same way.</li><li>Use <strong>explanatory </strong>variables.<br>X Calendar c = Calendar.getInstance();<br>✓ Calendar calendar = Calendar.getInstance();</li><li><strong>Encapsulate boundary conditions</strong>. Boundary conditions are hard to keep track of. Put the processing for them in one place.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*PGotFbm6l1zNx_xvHUFWtw.png" /><figcaption>X</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*rv8pjYamYkM-Q2U7BLrWpg.png" /><figcaption>✓</figcaption></figure><ul><li>Prefer dedicated value objects to a primitive type.<br>X int butceGerceklesme = (int) Math.round((toplamTLDeger / butce) * 100);<br>✓ Integer butceGerceklesme = (int) Math.round((toplamTLDeger / butce) * 100);</li><li><strong>Avoid negative conditionals</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*LzkFIDFOqtLPEVLvBaAeEg.png" /><figcaption>X</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*HV58uokHYNo9jtyxsDrOUw.png" /><figcaption>✓</figcaption></figure><h3>Names rules</h3><ul><li>Choose <strong>descriptive and unambiguous names.</strong><br>X double d; //available leave balance.<br>✓ double availableLeaveBalance;</li><li>Make <strong>meaningful distinctions.</strong><br>example: If you are using fetchValue() to return a value of something, use the same concept; instead of using fetchValue() in all the code, using getValue(), retrieveValue() will confuse the reader.</li><li>Use <strong>pronounceable names</strong>.</li><li>Use <strong>searchable names.</strong><br>X Date genymdhms; // generation timestamp<br>✓ Date generationTimeStamp;</li><li>Replace magic numbers with <strong>named constants.</strong><br>✓ private static final MAX_IMAGE_WIDTH = 100;<br>✓ private static final HOURS_PER_DAY = 24;</li><li><strong>Avoid encodings.</strong> Don’t append prefixes or type information.<br>X String nameString;<br>X List accountList;<br>X Double salaryDouble;<br>✓ accounts;<br>✓ String name;<br>✓ Double salary;</li></ul><h3>Functions rules</h3><ul><li><strong>Small</strong>.</li><li><strong>Do one thing</strong> and they should do it well.</li><li>Use <strong>descriptive names</strong>.</li><li>Prefer <strong>fewer arguments</strong>. No more than three, if possible.</li><li>Have <strong>no side effects</strong>.</li></ul><pre><strong>public boolean </strong>checkPassword(String userName, String password) {<br>    User user = UserGateway.findByName(userName);<br>    <strong>if </strong>(user !=User.NULL){<br>        String codedPhrase = user.getPhraseEncodedByPassword();<br>        String phrase = cryptographer.decrypt(codedPhrase, password);<br>        <strong>if </strong>(<strong>&quot;Valid Password&quot;</strong>.equals(phrase)) {<br>            Session.initialize();<br>            <strong>return true</strong>;<br>        }<br>    }<br>    <strong>return false</strong>;<br>}X</pre><ul><li>One level abstraction per method.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9YGAsVoF6PWWuOIIJXZ3qw.png" /><figcaption>X</figcaption></figure><ul><li>Don’t use flag arguments. Split method into several independent methods that can be called from the client without the flag.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UwBKY94Rw77AMsTm28qag.png" /><figcaption>X</figcaption></figure><h3>Comments rules</h3><ol><li>Always try to <strong>explain yourself in code</strong>. If it’s not possible, take your time to write a good comment.</li><li>Don’t be redundant (e.g.: i++; // increment i).</li><li>Don’t add obvious noise.</li><li>Don’t use closing brace comments (e.g.: } // end of function).</li><li><strong>Don’t comment out code</strong>. Just remove.</li><li>Use as an <strong>explanation of intent</strong>.</li><li>Use as <strong>clarification of code</strong>.</li><li>Use as a <strong>warning of consequences</strong>.</li></ol><h3>Source code structure</h3><ol><li><strong>Separate concepts vertically</strong>.</li><li><strong>Related code</strong> should appear <strong>vertically dense</strong>.</li><li>Declare <strong>variables close to their usage</strong>.</li><li><strong>Dependent functions</strong> should be <strong>closed</strong>.</li><li><strong>Similar functions</strong> should be <strong>closed</strong>.</li><li>Place functions in the <strong>downward direction</strong>.</li><li>Keep <strong>lines short</strong>.</li><li>Don’t use horizontal alignment.</li><li>Use <strong>white space to associate related things</strong> and disassociate weakly related.</li><li><strong>Don’t break indentation</strong>.</li></ol><h3>Objects and data structures</h3><ol><li>Hide internal structure.</li><li>Prefer data structures.</li><li>Avoid hybrid structures (half object and half data).</li><li>Should be <strong>small</strong>.</li><li><strong>Do one thing</strong>.</li><li><strong>A small number of instance variables</strong>. If your class has too many instance variables, then it is probably doing more than one thing.</li><li>Base class should know nothing about their derivatives.</li><li><strong>Better to have many functions</strong> than to pass some code into a function to select a behavior.</li><li><strong>Prefer non-static methods</strong> to static methods.</li></ol><h3>Tests</h3><ol><li><strong>One assert</strong> per test.</li><li><strong>Fast</strong>.</li><li><strong>Independent</strong>.</li><li><strong>Repeatable</strong>.</li><li><strong>Self-validating</strong>.</li><li><strong>Timely</strong>.</li><li><strong>Readable</strong>.</li><li><strong>Easy to run</strong>.</li><li>Use a <strong>coverage tool</strong>.</li></ol><h3>Code smells</h3><ol><li><strong>Rigidity</strong>. The software is difficult to change. A small change causes a cascade of subsequent changes.</li><li><strong>Fragility</strong>. The software breaks in many places due to a single change.</li><li><strong>Immobility</strong>. You cannot reuse parts of the code in other projects because of involved risks and high effort.</li><li><strong>Needless Complexity</strong>.</li><li><strong>Needless Repetition</strong>.</li><li><strong>Opacity</strong>. The code is hard to understand.</li></ol><h3>Error handling</h3><ol><li><strong>Don’t mix</strong> error handling and code.</li><li>Use <strong>Exceptions</strong> instead of returning error codes.</li><li><strong>Don’t return null</strong>, don’t pass null either.</li><li>Throw exceptions <strong>with context</strong>.</li></ol><p><strong><em>“Clean code is code that is written by someone who cares”</em></strong></p><p>– Michael Feathers</p><h3>Guidelines</h3><p><em>Clean Code…<br>✓ is elegant and efficient<br>✓ is simple and direct<br>✓ has meaningful names and is self-documenting<br>✓ is pleasing to read, and reads like well-written prose<br>✓ does one thing well<br>✓ does not tempt the developer to write bad code — on the flip side, when others change bad code, they tend to make it worse<br>✓ never hides the designer’s intent but is rather full of crisp abstractions and straightforward lines of control<br>✓ is when each method you read turns out to be pretty much what you expected (Least Astonishment Principle)<br>✓ can be read, and enhanced by a developer other than its original author<br>✓ has unit and acceptance tests<br>✓ is minimal (</em><a href="http://wiki.c2.com/?KeepItSimple"><em>KISS</em></a> <em>and </em><a href="http://wiki.c2.com/?YouArentGonnaNeedIt"><em>YAGNI</em></a><em>)<br>✓ does not repeat itself (DRY Principle)</em></p><h3>Meaningful Naming for Variables &amp; Classes</h3><p><strong>Use intention-revealing names</strong><br>X int d;<br><em>✓</em> int elapsedTimeInDays;<br><em>✓</em> int daysSinceCreatedDate;<br><em>✓</em> int daysSinceLastModifiedDate;<br>X function calc (int num1, int num2) {return num1*num2}<br><em>✓</em> function multiply (int num1, int num2) {return num1*num2}</p><p><strong>Make meaningful distinctions</strong></p><p><strong>Avoid ordering/number series naming<br></strong>X string date1, date2;<br><em>✓</em> string startDate, endDate;</p><p><strong>Avoid mispelling.<br>X </strong>float pft, profit<br><em>✓</em> float profitBeforeTax, profitAfterTax</p><p><strong>Avoid synonyms / closely-related terms<br>X</strong> let productData, productInfo<br><em>✓</em> let productData, productDescription</p><p><strong>Choose descriptive and unambiguous names<br>X</strong> string sd, ed;<br><em>✓</em> string startDate, endDate;</p><p><strong>Use pronounceable names<br>X</strong> float chqRetVal<br><em>✓</em> float chequeReturnsValue</p><p><strong>Use searchable names</strong></p><p><strong>Replace magic numbers with named constants<br>X</strong> 7<br><em>✓</em> int MAX_CLASSES_PER_STUDENT = 7</p><p><strong>Use comments to reveal additional information such as complex business logic, behaviors, assumptions, future suggestions, etc.<br>X</strong> string requestId;<br><em>✓</em> string requestId; // must be unique</p><p><strong>Use nouns for classes, packages, and variables<br>X</strong> class HandleAccounts {…}<br><em>✓</em> class AccountsHandler {…}</p><p><strong>Use verbs/verb phrases for functions<br>X </strong>function accounts() {…}<br><em>✓</em> function getAccounts() {…}</p><p><strong>Pick a single word per concept and use it consistently throughout the source code.<br>X </strong>function findUserByID(string id) {…}<br><strong>X</strong> function getRoleByKey(string key) {…}<br><strong>X</strong> function fetchAllUsers() {…}<br><strong>X</strong> function findRoles() {…}<br><em>✓</em> function getUserById(string id) {…}<br><em>✓</em> function getRoleById(string id) {…}<br><em>✓</em> function getAllUsers() {…}<br><em>✓</em> function getAllRoles() {…}</p><p><strong>Prioritize using domain-related terms<br>X</strong> transactionsStorage<br><em>✓</em> transactionsCache</p><p><strong>Avoid dis-information</strong></p><p><strong>Avoid using a word with an accepted meaning for something else.<br>X</strong> User[] activeUsersList;<br><em>✓</em> User[] activeUsers;</p><p><strong>Avoid using the variable name’s implementation details (such as data structure, container type, length) in the variable name.<br></strong>X User[] activeUsersArray;<br><em>✓</em> User[] activeUsers;<br>X User[] fiveAdminUsers;<br><em>✓</em> User[] adminUsers;</p><p><strong>Avoid unpopular acronyms and other names that don’t make sense.<br></strong>X float topm, topw;<br><em>✓</em> float turnoverPerMonth, turnoverPerWeek;</p><p><strong>Avoid using comments for introducing variables/functions.<br></strong>X int d; // elapsed time in days<br><em>✓</em> int elapsedTimeInDays;</p><p><strong>Avoid using confusing letters for names (e.g. l (simple L), I (capital i), O (capital O)).<br></strong>X int l, O;<br><em>✓</em> int limit, option;</p><p><strong>Don’t encode additional details in names.</strong></p><p><strong>Hungarian notation to encode data type is bad. Instead, use types.<br></strong>X var strFirstName;<br><em>✓</em> string firstName;<br>X var nUsers;<br><em>✓</em> int usersCount;</p><p><strong>Avoid meaningless prefixes or suffixes.<br></strong>X var orderInfo;<br><em>✓</em> var order;<br>X var userData;<br><em>✓</em> var user;</p><p><strong>Related classes and variables should follow a common pattern.<br></strong>X UserDataService, UserRecordsDAO, UserInfoExporter<br><em>✓</em> UserService, UserDAO, UserExporter</p><p><strong>Follow a common case convention.<br>E.g.<br>Routes — URLs: lower case with hyphens (kebab-case)<br></strong>&gt; hello-world-in-the-snow</p><p><strong>Routes — Names: lower case with underscores (snake_case)<br></strong>&gt; hello-world-in-the-snow</p><p><strong>Models and Controllers: begin with an Uppercase letter (CamelCase)<br></strong>&gt; HelloWorldInTheSnow<br>&gt; SnowController</p><p><strong>Method: begin with a lower case letter (camelCase)<br></strong>&gt; getHelloWorldWithSnow()</p><p><strong>HTML Attributes. lowercase with hiphens (kebab-case)<br></strong>&gt; id=”hello-world”<br>&gt; class=”snow”<br>&gt; name=”hello-world-with-snow</p><p><strong>Migrations. lowercase with an underscore (snake_case)</strong></p><pre>@JsonProperty(<strong>&quot;tedarikci_id&quot;</strong>)<br><strong>private </strong>String <strong>tedarikciId</strong>;</pre><pre><strong>public static final </strong>String <strong><em>PATH_SATINALMA </em></strong>= <strong>&quot;/satinalma/satinalma-list&quot;</strong>;</pre><h3>Functions</h3><ul><li><strong>A function should be readable from top to bottom, as a paragraph.</strong></li><li><strong>A set of functions should be readable from top to bottom, as a set of paragraphs.</strong></li><li><strong>Keep functions small — short </strong>(Ideal: 4 lines, maximum: 60 lines, the whole function must fit into the screen, so that it’s easy to read without vertical scrolling) and<strong> not too wide </strong>(Up to 70 to 120 characters, it’s easy to read the whole line without horizontal scrolling).</li><li><strong>Less number of arguments (≤3) is better. </strong>Make argument lists/objects/object arrays to pass large data chunks into functions.</li><li><strong>A function should remain at a constant level of abstraction. </strong>It shouldn’t deal with both low level and high-level stuff at the same time.</li><li><strong>Avoid duplications </strong>(DRY — Don’t Repeat Yourself).</li><li><strong>A function should do only one thing </strong>(Keep it atomic).<strong> Avoid causing side effects </strong>(Do what its name suggests and nothing else).</li><li><strong>Error handling is one thing. Keep functions that do only that. </strong>Start them with try and end with catch and/or finally.</li><li><strong>Use try/ catch instead of conditions if possible </strong>(Asking for forgiveness is easier than requesting permission).</li><li><strong>At lower levels, throw exceptions instead of returning error codes.</strong></li><li><strong>Avoid nested control structures.</strong> Replace such scenarios with functions or alternative strategies.</li><li><strong>Avoid switch statements </strong>(Hint: use polymorphism and bury the switch statement in an abstract factory).</li><li><strong>It’s better to have many functions than to pass some code into a function to select a behavior.</strong></li></ul><p><strong>Avoid using boolean variables as function arguments. </strong>Using booleans with other arguments usually means that the function does more than one thing. Always split such functions into smaller functions.<br>X function getUsers(boolean status) {…}<br><em>✓</em> function getActiveUsers() {…}<br><em>✓</em> function getInactiveUsers() {…}<br>X function removeOrders(int id, boolean cleanCache, boolean updateLog) {…}<br><em>✓</em> function removeOrders(int id) {…}<br><em>✓</em> function cleanOrdersCache(int id) {…}<br><em>✓</em> function updateOrdersLog(int id) {…}</p><p><strong>Avoid output arguments<br></strong>(Hint: If returning something is not enough, then your function is probably doing more than one thing).</p><p><strong>Pass by reference for a modification is bad.<br></strong>X activate(user);<br><em>✓</em> user.activate();</p><p><strong>A function can be a command or a query, but not both.</strong></p><p><strong>A setter is a command function. It should not return any value.<br></strong>X function setRole(…): boolean {…}<br><em>✓ </em>function setRole(…) {…}</p><p><strong>A boolean function must answer yes/no.<br></strong><em>✓</em> function isActiveUser(…): boolean {…}<br><em>✓</em> function usersAreValid(…): boolean {…}</p><p><strong>Keep boolean functions in a positive tone.<br></strong>X function isInactive(): boolean {…}<br><em>✓</em> function isActive(): boolean {…}</p><h3>Code Organization &amp; Formatting</h3><ul><li><strong>Group code by their functionality. </strong>Related functions must be close. Related code must appear vertically dense.</li><li><strong>Declare temporary variables close to their usage.</strong></li><li><strong>Adapt company/team-wide code conventions. Agree on a common standard for code formatting. </strong>Either use an external tool or IDE options for auto-formatting.</li><li><strong>Avoid too long files. </strong>1000–2000 lines are okay. Shorter, the better.</li><li><strong>Avoid too-wide code lines</strong>. Make sure they fit into the screen (Up to 70 to 120 characters). If they don’t fit, try to split them into multiple lines.</li><li><strong>Write high-level code first in a file and keep lower-level implementations towards the end of the file. </strong>(Good files are like newspaper articles, with a heading, the important stuff first, and details later.)</li><li><strong>Make sure the code is ordered as of the calling sequence.</strong> The caller should be before the callee.</li><li><strong>Follow proper indentation across code files.</strong> Use an external tool or IDE’s support.</li></ul><h3>Objects and Data Structures</h3><ul><li><strong>A data structure must expose data while having no behavior.</strong></li><li><strong>An object must hide data while exposing the behaviors </strong>(via methods).</li><li><strong>Avoid accessing unknown data via method chaining</strong>. Only access the immediate methods (methods of own class, of objects, just created), immediate parameters (of instance variables or objects just created), but not further methods/parameters through chaining them (a.k.a. Law of Demeter / Principle of Least Knowledge).</li><li><strong>Functions and data structures can have some coupling by nature</strong>. It may be easier to add new functions than to change data structures (adding new data structures can cause breaking changes in functions).</li><li><strong>Functions and classes can have some coupling by nature</strong>. It may be easier to add new classes than to change functions (adding new functions can cause breaking changes in classes).</li></ul><h3>Error Handling</h3><ul><li><strong>At lower levels, throw exceptions instead of returning error codes. </strong>Keep error codes for communication between different layers, interfaces, or systems.</li><li><strong>Errors and exceptions must provide adequate context</strong> (such as intent, failure stage, error type, failed values, etc.).</li><li><strong>Map foreign errors to adhere to common standards. </strong>Wrap all errors and exceptions raised from external systems, third-party libraries, and APIs. Use a generic error type for unknown/unhandled cases.</li><li><strong>Reduce the reliance on return type and null checks </strong>(since they strongly link failure path information to the main flow). Instead of returning null/false, return a proper error object or throw an exception. Passing null to a function / next stage is also bad, avoid such practices.</li></ul><h3>Boundaries</h3><ul><li><strong>Map foreign behaviors into wrapper classes when integrating external systems and third-party code. </strong>Expose only limited capability for local use.</li><li><strong>Use the Adapter pattern to handle things that don’t exist</strong> (e.g. external systems not yet implemented / integrated). Make adapters consume the agreed API via proper use of interfaces. When a foreign API changes, only the adapter must change, without any major impact on local code.</li></ul><h3>Classes &amp; Interfaces</h3><ul><li><strong>Inside a class/interface, arrange code in order</strong>: static variables in order of visibility (start from public) → instance variables in order of visibility (start from public) → constructors → methods grouped by functionality → getters, setters, equals, variable conversions, utility &amp; helper methods, etc.</li><li><strong>Encapsulate utility methods</strong>. Make them private (or protected if they are exposed to tests).</li><li><strong>Make classes small</strong>. Shorter, the better (Ideal: 100 lines, Maximum: 1000 lines).</li><li><strong>Classes with exactly one responsibility and one reason to change are easy to manage.</strong> a.k.a. The Single Responsibility Principle.</li><li><strong>The class name must show its responsibility. </strong>Class names with Processor, Manager, Super often hints at an unfortunate aggregation of responsibilities.</li><li><strong>Multiple small classes are preferred over very few large classes.</strong> During change requests, such code reduces the affected code surface due to high separation of concerns.</li><li><strong>Organize code based on abstractions, not concrete implementation details</strong>. Build abstract agreements to facilitate interactions between code.</li><li><strong>Maintain high cohesion</strong>. In general, classes have a fewer number of instance variables and they are co-dependant with methods as a whole. If that cohesion is getting low, break the class apart.</li><li><strong>Too much inheritance is bad</strong>. Try to use composition more often.</li></ul><h3>Concurrency</h3><ul><li><strong>Keep concurrency-related code separate from other code.</strong></li><li><strong>Severely limit access to any data that may be shared</strong>. Unless there are performance concerns, using copies of data is more preferred than sharing.</li><li><strong>Try to maintain data as independent subsets that can be processed by separate threads</strong>.</li><li><strong>Avoid using more than one Synchronized method on a shared object</strong>.</li><li><strong>Keep synchronized sections as small as possible.</strong></li><li><strong>Think about shut-down early and get it working early.</strong></li></ul><h3>Comments</h3><ul><li><strong>Express yourself in the code, but not in the comments</strong>. Keep comments for delivering any extra information. If the code is readable, the need for comments is very low.</li><li><strong>Warn the consequences of potential scenarios/actions</strong>. If the code is too brittle, instead of commenting, fix the code.</li><li><strong>Avoid noise and weak comments </strong>(negativity, complaints, humor, misleading opinions, redundant statements, changelog, too much information, irrelevant facts, comments needing additional explanations).</li><li><strong>Avoid commenting out code chunks. </strong>If the code is bad, rewrite it.<strong> </strong>Use version control systems for handling code that is expired, deprecating, or experimental. (Pro tip: If you comment out code for a very short term, consider using a TODO comment as a reminder to clean things up later).</li></ul><h3>Application Logging</h3><ul><li><strong>Follow a common logging practice across code.</strong></li><li><strong>Use correct log levels and provide adequate context in log messages </strong>(e.g. timestamp, log level, code location, state information, parameter values, error descriptions, system banners)<strong>.</strong></li><li><strong>Do not log sensitive information </strong>(e.g. personally identifiable information, financial values, business data, auth info).</li></ul><p>Clean code is not written following a set of rules. You do not become a software professional just by learning a list of what you do and what you’ve done. Professionalism and craftsmanship come from values and discipline in lists of what you should and should not do when creating a code.</p><p>At <strong>Softensity</strong> we promote clean code because the implications are versatile:</p><ul><li>Lowered maintenance costs</li><li>Better security</li><li>Better employee satisfaction</li><li>Higher predictability in software development costs and releases</li><li>Better software design that enables flexibility to deployments</li><li>Better test automation</li><li>Higher test coverage</li><li>And fewer customer-facing quality problems</li></ul><p>Related Resources</p><ul><li>Presented as <a href="https://cheatography.com/costemaxime/cheat-sheets/summary-of-clean-code-by-robert-c-martin/"><strong>cheat sheet</strong></a> by CosteMaxime.</li><li><a href="http://www.inf.fu-berlin.de/inst/ag-se/teaching/K-CCD-2014/Clean-Code-summary.pdf"><strong>The essence of “Clean Code”</strong></a> [PDF] — a different summary</li><li><a href="https://medium.com/mindorks/how-to-write-clean-code-lessons-learnt-from-the-clean-code-robert-c-martin-9ffc7aef870c"><strong>How to write clean code? Lessons learned from “The Clean Code”</strong></a> [article]</li><li><a href="https://blog.gojekengineering.com/the-basics-of-writing-clean-code-39ed770b626d"><strong>A summary of the fundamental principles of writing great code</strong></a> [article]</li><li><a href="https://www.youtube.com/watch?v=7EmboKQH8lM&amp;list=PLmmYSbUCWJ4x1GO839azG_BBw8rkh-zOj"><strong>Clean Code — “Uncle” Bob</strong></a> [videos]</li></ul><p>Recommended Books</p><ul><li><a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882"><strong>Clean Code: A Handbook of Agile Software Craftsmanship</strong></a> [2007] by Robert C. Martin (“Uncle Bob”) — This book explains coding best practices to improve the readability of code and maintain quality with TDD.</li><li><a href="https://www.amazon.com/Refactoring-Improving-Existing-Addison-Wesley-Signature/dp/0134757599"><strong>Refactoring: Improving the Design of Existing Code (2nd Edition)</strong></a> [2018] by Martin Fowler — explains coding best practices to improve existing code for better understandability and maintainability.</li><li><a href="https://www.amazon.com/Pragmatic-Programmer-journey-mastery-Anniversary-ebook/dp/B07VRS84D1"><strong>The Pragmatic Programmer (2nd Edition): Your Journey to Mastery, 20th Anniversary Edition</strong></a> [2019] by Andrew Hunt, David Thomas — This book provides practical insights and advice on creating better software and rediscovering the joy of coding.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41ddb789da4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>