<?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 Okan YÜKSEL on Medium]]></title>
        <description><![CDATA[Stories by Okan YÜKSEL on Medium]]></description>
        <link>https://medium.com/@okn_yuksel?source=rss-815d08a6d42c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*K2o52Lp9Zko-0SPoU5P0rg.jpeg</url>
            <title>Stories by Okan YÜKSEL on Medium</title>
            <link>https://medium.com/@okn_yuksel?source=rss-815d08a6d42c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 15:53:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@okn_yuksel/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[Hepsiburada Market Software Development Manifesto]]></title>
            <link>https://medium.com/hepsiburadatech/hepsiburada-market-software-development-manifesto-5089773dffbb?source=rss-815d08a6d42c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5089773dffbb</guid>
            <category><![CDATA[hepsiburada]]></category>
            <category><![CDATA[engineering-culture]]></category>
            <category><![CDATA[culture]]></category>
            <category><![CDATA[software-development-team]]></category>
            <category><![CDATA[manifesto]]></category>
            <dc:creator><![CDATA[Okan YÜKSEL]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 08:57:36 GMT</pubDate>
            <atom:updated>2024-03-12T08:57:36.199Z</atom:updated>
            <content:encoded><![CDATA[<p>As Hepsiburada Market technology team, we are proud of our ever-increasing count of active users and order volume. This success is a clear result of our dedicated efforts towards reliable, uninterrupted, and user-focused experiences.</p><p>We provide services to our customers with expanding business partners and product categories.</p><p>With this manifesto, we aim to explain how we achieve this by outlining the strategies applied in the development of our expanding teams and software products.</p><h4><strong>Software Development Culture</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-glcLsJMxRJ2v5xt.jpg" /><figcaption><a href="https://www.ualberta.ca/china-institute/research/other/shaolin-kungfu.html">https://www.ualberta.ca/china-institute/research/other/shaolin-kungfu.html</a></figcaption></figure><p>We adhere to development practices aligned with ‘Clean Code’ and ‘Domain Driven Design.’ As a team, we consider the guidance provided by Robert C. Martin, the author of ‘Clean Code: A Handbook of Agile Software Craftsmanship,’ and Eric Evans, the author of ‘Domain-Driven Design: Tackling Complexity in the Heart of Software.’</p><p>We document our architecture to correctly position new or existing services within the architecture.</p><p>Pair programming and code review are integrated into our software development processes.</p><p>We ensure the reliability of our developed code by subjecting it to unit tests, integration tests, and load tests.</p><p>To quickly identify and intervene in case of issues, we implement logging (never excessive!) using appropriate methods and adhere to best practices.</p><p>Rather than focusing on documentation, we emphasize naming services, class names, functions, and variables correctly to ensure that the code can be read without the need for extensive documentation. When necessary, we provide an adequate (never excessive!) number of comments and/or documents to explain the code.</p><p>To achieve short-term project delivery, we may incur technical or business debt. However, we promptly plan for technical debts (opening a backlog task and including it in the current or next sprint items) and address them at the right times.</p><p>We standardize our branch management strategy across all projects. We ensure that developments in feature branches are secure, performant, accurate, complete, and have successful test results before merging into the master branch, followed by QA Engineer review and prompt deployment to production. Feature branches should be deployable to test environments unaffected by other developments.</p><p>New team members joining us have a first peer in the team, preferably someone in a similar position, to facilitate a smoother onboarding process. If they prefer, we include them in pair programming sessions as much as they desire.</p><p>We believe in strong communication within the team, enabling quick organization.</p><p>After deploying developments to production, we monitor our systems for any negative impact using monitoring tools.</p><p>For completed or nearly completed tasks, especially those in the QA test, sign-off, or dependent stages, we prioritize them to focus on producing the maximum output at the end of the sprint.</p><p>The product team clearly defines requirements. After determining technical requirements, the development team comes together for discussion. At the end of this meeting, we answer the following questions as a team, defining the target the story aims to achieve, the necessary technical developments, and metrics: <em>What are we doing? Why are we doing it? How will we do it? How do we collect metrics? How do we monitor it? Do we need toggles for development?</em></p><p>We gather for tech storming, proposing points of improvement in our systems or learning about new technologies we can incorporate into our tech stack. We identify systems where we can apply these suggestions and plan when the work will be done.</p><p>At the end of the first week of the sprint, we come together for a sprint review and try to find solutions for stories with risks.</p><p>We estimate stories by each member of the Agile team according to the Agile Manifesto.</p><p>We regularly plan retrospective meetings, and upon the request of any team member, we schedule retrospective meetings.</p><h4>Story Leadership</h4><p>We define ourselves as product engineers, actively participating in product development and design stages, aiming for the highest level of success for the product.</p><p>During our planning meetings, we select a ‘Story Leader’ for each story. The Story Leader is typically one of the developers working on the story.</p><p>The ‘Story Leader’ is responsible for the complete and timely delivery of the story, in line with the commitment made by the team. The ‘Story Leader’ organizes developers working on different parts of the story and takes preventive measures by anticipating blocking situations.</p><p>We strive to deliver tasks in the smallest possible units. By leaving the part of development that is lagging or dependent on other teams as technical debt, we quickly provide solutions to business needs. Once the blocking situation is resolved, we prioritize and eliminate technical debts.</p><h4>Technical Guide For Developers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DS9_EAVxKM8jIrwzgOeTkw.jpeg" /><figcaption><a href="https://wallpapercosmos.com/shaolin-kung-fu-wallpapers">https://wallpapercosmos.com/shaolin-kung-fu-wallpapers</a></figcaption></figure><p>Resources we find beneficial for enhancing domain-driven design competency and recommend include the book ‘Domain-Driven Design: Tackling Complexity in the Heart of Software’ by Eric Evans and the <a href="https://github.com/ddd-crew"><strong>ddd-crew</strong></a> GitHub account.</p><p><strong>Domain Driven Design Practices That We Offen Apply</strong></p><p>Bounded contexts are smaller logical boundaries within a domain that are consistent and as independent as possible. When developing, we consider these boundaries. A context should have all the concepts required by the business but should not include any concepts unrelated to itself, preventing leakage between contexts.</p><p>We avoid complexity by keeping business logics on aggregates, reducing code repetition and requiring minimal dependencies when developing tests. Writing unit tests becomes easier.</p><p>Value objects and aggregates should have a load method. Load methods should contain domain guards. This way, the object to be created is created through a single method, passing through the control of domain guards.</p><p>Domain guards exist only within the domain.</p><p>Value objects should be immutable. They should not have setter methods. If an update is needed, we should recreate them using the load method.</p><p>We develop getter methods or single-line functions for calculations that contain logic (using more than one property) on our structures, such as aggregates, entities, value objects, to prevent these operations from being done in domain services and thus eliminate code repetition.</p><p><strong>Our Clean Code Practices</strong></p><p>We detailed this episode in our article ‘<a href="https://medium.com/hepsiburadatech/motivation-for-clean-code-dd4a642984b8"><strong>Motivation For Clean Code</strong></a>’, which we strongly recommend you to read.</p><p>In addition to what we mentioned;</p><p>We use ‘Fluent Validation’. Using complex if-else blocks or attributes is not very compatible with SOLID principles. Therefore, we collect our validations in a single method.</p><p>We avoid overengineering and prefer simple solutions over complex ones. If we cannot get rid of complexity and have to come up with work-around solutions, we discuss and brainstorm together as a team.</p><p>When logging, we follow best practices such as determining log levels and using structured logging.</p><p><strong>General Acceptances</strong></p><p>RestClients, HttpClients etc. are encapsulated in all our systems. Our domain services are unaware of the technology used for network communication. This precaution reduces technology dependencies.</p><p>Our projects are ready to run as much as possible after the repository is cloned. We create config files for IDEs commonly used by the team and Readme.md files for requirements.</p><p>We apply the ‘CQRS’ pattern, choosing to separate our ‘Read’ operations from ‘Write’ operations in interfaces.</p><p>For our needs, we develop feature toggles, compare toggles, and internal toggles.</p><ul><li>If we need to activate/deactivate a developed feature based on business needs, we manage this situation with feature toggles, gaining this capability without deployment.</li><li>If we need to replace an existing development or integration with a different alternative that produces the same data, we compare application outputs, log differences, observe them for a while, and activate our new developments later.</li><li>If a developed feature needs to be activated for Hepsiburada personnel only, we can achieve this by developing an internal toggle.</li></ul><p><strong>Our Hunting Spots In Code Review Sessions</strong></p><p><em>(I am grateful to Mert TALAYOĞLU for his support in this episode.)</em></p><p>During our development process, in order to ensure the quality and maintainability of our codebase, we, as a team, seek answers to the following questions during code reviews:</p><ul><li>Models, Entities, Value Objects (immutable), and DTOs encapsulate their own business logic in accordance with DDD?</li><li>Has attention been given to data structure alignment/memory management?</li><li>Is it in compliance with Restful principles? (Defensive validation, correct usage of method types, and response status codes)</li><li>Was the development conducted in accordance with clean code practices? (Naming conventions, readable code, low complexity, DRY — Don’t Repeat Yourself etc.)</li><li>To what extent have issues such as response time increase, performance loss, and information security been evaluated? Can optimizations like caching and projection be considered for resource-intensive operations?</li><li>Does the development fully meet the business requirements? Are there any technical debts left behind?</li><li>Are there any hard coded variable definitions? Can these values be read from sidecars or configuration files? Can they be defined as constant variables?</li><li>Does it adhere to OOP principles (encapsulation, dependency injection, etc.) and SOLID principles?</li><li>Has the distance between where variables are defined and where they are used been kept short?</li><li>Are the parameter counts of methods low? Has a DTO been used for more than three parameters?</li><li>Logic should not be built on null or exceptions. Has exception handling been done correctly? Can it be monitored?</li><li>Flag parameters should not complicate logic within methods. Is it appropriate?</li><li>Have design patterns been used in a solution-oriented and requirement-driven manner?</li><li>Is business logic located in the domain layer?</li><li>Has the use of reflection been avoided?</li><li>Has attention been given to Command &amp; Query Separation? Is CQRS applicable?</li><li>Is there sufficient monitoring? Have necessary logs been written with correct practices?</li><li>Is there any unnecessary overengineering or forced code?</li><li>Have project dependencies been structured to meet requirements, without adding excessive dependencies/libraries?</li><li>Have Git practices been followed? (Small commits, commit messages, clean history, ignored files etc.)</li></ul><h4><strong>Security</strong></h4><p>The security of our systems is of utmost importance to us. It is our responsibility towards our users.</p><p>First of all, we constantly educate ourselves by following guidelines such as “<a href="https://github.com/OWASP/API-Security"><strong>OWASP API Security</strong></a>”.</p><p>We ensure the security of all our internal and external services before taking them to the production stage.</p><p>Personal data should be processed/hosted in a legal, fair, and transparent manner.</p><p>We conduct penetration tests on all systems at regular intervals.</p><p>To ensure our security, we host internal and public services in different layers.</p><p>We only communicate our microservices through APIs and message queues. In accordance with the Microservice architecture, we prevent sharing a common data source.</p><p>Entity models are never directly included in API responses. Communication is established through contract models.</p><p><strong><em>Some wishes at the end of story</em></strong></p><p><em>I hope that it will help software teams who read it to determine their software development processes and develop successful software products.</em></p><p><em>Thanks for your time.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5089773dffbb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hepsiburadatech/hepsiburada-market-software-development-manifesto-5089773dffbb">Hepsiburada Market Software Development Manifesto</a> was originally published in <a href="https://medium.com/hepsiburadatech">hepsiburadatech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Providing Real Time Order Status Changes Via Socket Connection — Socket.IO]]></title>
            <link>https://medium.com/@okn_yuksel/providing-real-time-order-status-changes-via-socket-connection-socket-io-4340495619a4?source=rss-815d08a6d42c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4340495619a4</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[socket-programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[socketio]]></category>
            <dc:creator><![CDATA[Okan YÜKSEL]]></dc:creator>
            <pubDate>Fri, 08 Dec 2023 07:08:35 GMT</pubDate>
            <atom:updated>2023-12-08T07:08:35.711Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Providing Real Time Order Status Changes Via Socket Connection — Socket.IO / Redis Adapter Implementation In GoLang</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*h1s5-MoBfLelWHerlng2zw.png" /></figure><h4><strong>Requirement</strong></h4><p>We develop solutions to address various technical issues/needs in order to <em>ensure the satisfaction of our customers and the stable, secure, and high-performance operation of our architecture. These needs can arise based on customer</em> requests as well as the demands of product teams, monitoring teams, or commercial teams.</p><p>The seamless and timely delivery of orders created by users is crucial for both customer satisfaction and our commercial success. Therefore, orders are constantly monitored by commercial teams through various back-office interfaces.</p><p>Orders can be tracked through dashboards that provide the total number of orders in different statuses (pending, in picking, in transit, delivered, etc.), as well as through interfaces that allow us to query a detailed order list with various filters, as shown below. These interfaces can be accessed both through computers and mobile devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LKDxJX0IJDj9hEq7d9X_pw.png" /></figure><p><strong>We aim to enable real-time tracking of the current status of listed orders by addressing the deficiencies in these back-office interfaces.</strong></p><p>Currently, users of these interfaces have to trigger the refresh button or force-refresh their browsers in order to access the up-to-date status of orders. We want to eliminate this necessity and provide the ability to track order statuses instantaneously.</p><h4><strong>Challenges</strong></h4><ul><li>We need to continuously provide the real-time status of orders.</li><li>The architecture we establish should be resilient and easily monitorable.</li><li>It should be able to scale vertically and horizontally to handle heavy loads.</li><li>All clients should be notified of order status updates simultaneously.</li><li>This development should not strain the system, and the performance of the rest of the architecture should not be affected.</li></ul><h4><strong>Solution</strong></h4><p>To avoid overburdening the rest of the architecture, we prefer not to add additional database queries to the existing ones. Therefore, we have decided that establishing a distributed architecture would be the most suitable choice for us.</p><p>By using a message broker, we can build an event-based architecture. We can monitor our queues and we can set alarms for predefined threshold values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rkrdXFsHumiU779j" /></figure><p>In the designed architecture, as soon as order statuses change, events for order status changes are published to the message broker exchanges. The consumers listening to the queues bound to these exchanges also have other tasks. However, to stay focused on the topic, we will temporarily exclude these other tasks.</p><p>Considering the memory and CPU requirements of consumers in the cluster, the fetch sizes can be increased by allocating more resources (vertical scaling). Alternatively, the number of consumers can be increased by scaling up the number of pods (horizontal scaling).</p><pre>// Exchanges, Queues And Consumers Constructing<br><br>func (self *OrderStatusConsumer) Construct() {<br><br>self.messageBus.AddConsumer(&quot;In.OrderCreated&quot;).<br>  SubscriberExchange(&quot;*&quot;, rabbitmq.Topic, &quot;Events.V1.OrderCreated&quot;).<br>  HandleConsumer(self.consumeOrderCreated)<br><br> self.messageBus.AddConsumer(&quot;In.PickingStarted&quot;).<br>  SubscriberExchange(&quot;*&quot;, rabbitmq.Topic, &quot;Events.V1.PickingStarted&quot;).<br>  HandleConsumer(self.consumePickingStarted)<br><br> self.messageBus.AddConsumer(&quot;In.DeliveryCreated&quot;).<br>  SubscriberExchange(&quot;*&quot;, rabbitmq.Topic, &quot;Events.V1.DeliveryCreated&quot;).<br>  HandleConsumer(self.consumeDeliveryCreated)<br><br> ...<br><br>}</pre><p>After completing their respective tasks, these consumers will publish the order status changed notification event.</p><pre>func (self *OrderStatusConsumer) consumePickingStarted(message rabbitmq.Message) error {<br> <br>...<br><br> orderStatusChangedNotificationEvent := event.OrderStatusChangedNotificationEvent{<br>  OrderNumber: order.OrderNumber,<br>  Status: domain.OrderStatus_Picking,<br> }<br><br> self.messageBus.Publish(ctx, &quot;*&quot;, orderStatusChangedNotificationEvent)<br><br>...<br><br>}</pre><p>Another console application has been developed to serve as a socket server, which also acts as a consumer by listening to the “Out.Socket.BroadcastOrderStatus” queue, where OrderStatusChangedNotificationEvents are simultaneously published.</p><p>We used the “<strong>github.com/googollee/go-socket.io</strong>” package to create the socket server.</p><p>With the standalone Redis adapter implementation in this package, multiple socket servers that perform message broadcasting can establish a pub/sub mechanism with Redis. This way, all socket servers can be notified of and broadcast messages to their clients through the Redis channel. Without the Redis adapter, we would have had to build this architecture ourselves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/0*0AHtUfruPgpJLkcl" /><figcaption><a href="https://socket.io/docs/v4/redis-adapter/">https://socket.io/docs/v4/redis-adapter/</a></figcaption></figure><p>Let’s start with the implementation of our console application that will perform the broadcast.</p><pre>var orderStatusBroadcastCmd = &amp;cobra.Command{<br> Use:   &quot;orderchangednotificationbroadcast&quot;,<br> Short: &quot;order status stream&quot;,<br> Long:  `order status stream`,<br> RunE:  runOrderStatusBroadcast,<br>}<br><br>func init() {<br> RootCmd.AddCommand(orderStatusBroadcastCmd)<br>}<br><br>func runOrderStatusBroadcast(cmd *cobra.Command, args []string) error {<br><br> ...<br><br> var messageBus = rabbitmq.NewRabbitMqClient(<br>  configuration.RabbitMQ.Host,<br>  configuration.RabbitMQ.Username,<br>  configuration.RabbitMQ.Password,<br>  &quot;&quot;,<br>  rabbitmq.RetryCount(configuration.RabbitMQ.RetryCount),<br>  rabbitmq.PrefetchCount(configuration.RabbitMQ.FetchSize))<br><br> ctx := logger.WithCorrelationId(context.Background(), uuid.NewV4().String())<br><br> var allowOriginFunc = func(r *http.Request) bool {<br>  return true<br> }<br><br> var server = socketio.NewServer(&amp;engineio.Options{<br>  Transports: []transport.Transport{<br>   &amp;polling.Transport{<br>    CheckOrigin: allowOriginFunc,<br>   },<br>   &amp;websocket.Transport{<br>    CheckOrigin: allowOriginFunc,<br>   },<br>  },<br> })<br><br> if _, err = server.Adapter(&amp;socketio.RedisAdapterOptions{<br>  Addr:     configuration.RedisStandAlone.Host,<br>  Prefix:   configuration.RedisStandAlone.Prefix,<br>  Password: configuration.RedisStandAlone.Password,<br> }); err != nil {<br>  panic(err)<br> }<br><br> handleOrderStatusSocketDisconnect(ctx, server, logger)<br> handleOrderStatusSocketError(ctx, server, logger)<br><br> runOrderStatusSocket(ctx, server, logger)<br><br> go func() {<br>  if err = server.Serve(); err != nil {<br>   panic(err)<br>  }<br> }()<br><br> defer func(server *socketio.Server) {<br>  if err = server.Close(); err != nil {<br>   logger.Exception(ctx, &quot;Socket close error&quot;, err)<br>  }<br> }(server)<br><br> http.Handle(&quot;/socket.io/&quot;, server)<br> http.Handle(&quot;/&quot;, http.FileServer(http.Dir(&quot;./asset&quot;)))<br><br> var broadcastConsumer = orderstatusbroadcast.NewOrderStatusBroadcast(configuration, messageBus, logger, server)<br> broadcastConsumer.Construct()<br><br> go func() {<br>  if err = messageBus.RunConsumers(); err != nil {<br>   panic(err)<br>  }<br> }()<br><br> return http.ListenAndServe(&quot;:5000&quot;, nil)<br>}<br><br><br>func runOrderStatusSocket(ctx context.Context, server *socketio.Server, logger log.Logger) {<br> server.OnConnect(orderstatusbroadcast.ORDER_STATUS_NAMESPACE, func(connection socketio.Conn) error {<br>  connection.SetContext(&quot;&quot;)<br>  connection.Join(orderstatusbroadcast.ORDER_STATUS_ROOM)<br>  logger.Info(ctx, fmt.Sprintf(&quot;Live location connection established ConnectionId : %s&quot;, connection.ID()))<br>  return nil<br> })<br>}<br><br>func handleOrderStatusSocketDisconnect(ctx context.Context, server *socketio.Server, logger log.Logger) {<br> server.OnDisconnect(&quot;/&quot;, func(s socketio.Conn, reason string) {<br>  s.LeaveAll()<br>  logger.Info(ctx, fmt.Sprintf(&quot;Socket connection closed Reason : %s&quot;, reason))<br><br> })<br>}<br><br>func handleOrderStatusSocketError(ctx context.Context, server *socketio.Server, logger log.Logger) {<br> server.OnError(&quot;/&quot;, func(s socketio.Conn, err error) {<br>  s.LeaveAll()<br>  logger.Exception(ctx, &quot;Error on socket connection&quot;, err)<br> })<br>}</pre><p>Let’s launch our consumer that will listen to OrderStatusChangedNotificationEvents. The task of this consumer is to broadcast the message to the socket.</p><pre>func (self *OrderStatusBroadcast) Construct() {<br><br> self.messageBus.AddConsumer(&quot;Out.Socket.BroadcastOrderStatus&quot;).<br>  SubscriberExchange(&quot;*&quot;, rabbitmq.Topic, &quot;Events.V1:OrderStatusChangedNotificationEvent&quot;).<br>  HandleConsumer(self.broadcastOrderStatusConsume())<br><br>}</pre><pre>func (self *OrderStatusBroadcast) broadcastOrderStatusConsume() func(message rabbitmq.Message) error {<br><br> return func(message rabbitmq.Message) error {<br><br>  var (<br>   eventMessage event.OrderStatusChangedNotificationEvent<br>   err          error<br>  )<br><br>  ctx := self.logger.WithCorrelationId(context.Background(), uuid.NewV4().String())<br><br>  if err = json.Unmarshal(message.Payload, &amp;eventMessage); err != nil {<br>   return err<br>  }<br><br>  self.logger.Info(ctx, fmt.Sprintf(&quot;%s order status updated. Status : %s&quot;, eventMessage.OrderNumber, eventMessage.Status))<br><br>  self.socket.BroadcastToRoom(ORDER_STATUS_NAMESPACE, ORDER_STATUS_ROOM, ORDER_STATUS_ROOM, eventMessage)<br><br>  return nil<br> }<br>}</pre><p>In the Rabbit management UI, we can observe that messages are smoothly flowing into the queue and being processed by the consumers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*wzSeZIQ_5khfvGexoqg8gw.png" /></figure><p>We have confirmed the processing of messages through the consumer logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d_q_CN-gWEoLnl1H" /></figure><p>For our local development testing, we can use a simple HTML page as shown below.</p><pre>&lt;!doctype html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;socket-io test&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;script src=&quot;https://cdn.socket.io/socket.io-1.2.0.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;https://code.jquery.com/jquery-1.11.1.js&quot;&gt;&lt;/script&gt;<br>&lt;script&gt;<br>    var socket = io(&quot;http://localhost:5000/orderstatus&quot;, {<br>        jsonp: false,<br>        reconnection: true,<br>        reconnectionDelay: 100,<br>        reconnectionAttempts: 100000,<br>        transports: [&quot;websocket&quot;],<br>    });<br><br>    socket.on(&quot;update_order_status&quot;, function (data) {<br>        console.log(data);<br>    });<br>&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kcGzJyxWeSsKAN94OVopaQ.png" /></figure><p>I am grateful to Akın Işık 👑 for sharing his domain know-how with me and for providing support during our pair programming sessions.</p><p>Building the socket architecture in this development has been an enjoyable experience for me. I hope you have also found it enjoyable, and thank you for your time. I look forward to meeting with you again for future challenges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*ugShH3rslIihdWJ5ymR1vw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4340495619a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Motivation For Clean Code]]></title>
            <link>https://medium.com/hepsiburadatech/motivation-for-clean-code-dd4a642984b8?source=rss-815d08a6d42c------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd4a642984b8</guid>
            <category><![CDATA[code-maintainability]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Okan YÜKSEL]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 12:02:14 GMT</pubDate>
            <atom:updated>2023-03-13T12:02:14.037Z</atom:updated>
            <content:encoded><![CDATA[<p>Regardless of the scale of the software project, we need to be part of any team, large or small. Therefore, it is very important that: the code, written by us, should be readable and developable by other developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*eiotgPYVX6MJ_evHOZCFmQ.jpeg" /><figcaption><a href="http://geek-and-poke.com/geekandpoke/2008/2/4/the-art-of-programing.html">The art of programming by Geek &amp; Poke</a> is licensed under <a href="https://creativecommons.org/licenses/by/3.0/">CC BY 3.0</a></figcaption></figure><p><strong>“Big” Dave Thomas</strong>, (founder of OTI, the godfather of the Eclipse strategy) defines clean code with these sentences:</p><p><em>Clean code </em><strong><em>can be read, and enhanced by a developer other than its original author</em></strong><em>. It has unit and acceptance tests. It has meaningful names. It provides </em><strong><em>one way rather than many</em></strong><em> ways for doing one thing. It has </em><strong><em>minimal</em></strong><em> dependencies, which are explicitly defined, and provides a clear and minimal API.</em></p><p>On the other hand, even if we are going to maintain the project alone, we may need to make additional developments for any module of the project months or years later. It is necessary to be able to understand, at a glance, what task the code written years ago fulfills, which modules of the project they serve, to protect the mental health of the developer, and to make sure that other modules are not affected by the new development.</p><p><em>Any fool can write code that a computer can understand. Good programmers write code that humans can understand.</em> <strong>Martin Fowler</strong></p><p><strong>Why Clean Code Is Needed?</strong></p><p>It’s not hard to predict what’s going to happen when developing with unclean code. I want to talk about some of the problems we will face.</p><p>If the code is not cleanly;</p><ul><li>Generates technical debt (If you want to take a look: “<a href="https://en.wikipedia.org/wiki/Technical_debt">https://en.wikipedia.org/wiki/Technical_debt</a>”). We can talk about managing technical debts under another heading, but there can be many reasons for technical debt. The first igniter of this wick is also non-cleanly code.</li><li>We encounter code blocks that become unmaintainable, over time the project may also become unmaintainable.</li><li>Would be costly to development. The development cost would be higher than it should be. If the dev team can’t foresee the cost, that’s a clear indication that we have a project that wasn’t cleanly developed.</li><li>Confusion grows. With each added feature, each code block developed, the confusion will grow. This means that the project dies over time. You may have heard a lot: “Let’s rewrite this.”</li></ul><p><strong>How To Get Clean Code?</strong></p><p>First of all, we need the awareness of all members of the team and the institution that owns the project. Because achieving clean code will cost time. (money cost naturally, time = money)</p><p>We need to have the motivation to pair programming and refactoring with other members of the team.</p><p>We need to communicate further with the technical and commercial teams to make sure that we can simply explain and discuss the module or code block.</p><p><em>Clean coding is not a skill that can be acquired overnight. It is a habit that needs to be developed by keeping these principles in mind and applying them whenever you write code. </em><strong>Yiğit Kemal Erinç</strong></p><p><strong>Clean Code Frame</strong></p><p>Simple, focused, completeness, correctness.</p><p>In order for us to accept that the clean code principles are followed;</p><ul><li>The code should be <strong>simple</strong> and understandable.</li><li>Functions, classes and variables should be <strong>focused</strong>. They should be single responsible and not have side effects.</li><li>It should be able to <strong>respond to all needs</strong>, should cover possible cases, should allow the development and prevent situations that should be avoided.</li><li>We have to make sure it works <strong>correctly</strong>. This is only possible with unit and acceptance tests. Integration tests are required to test integrations.</li></ul><p><strong>Meaningful Names</strong></p><p><em>The name of a variable, function, or class, should answer all the big questions. It should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent. </em><strong>Robert C. Martin</strong></p><pre>public List&lt;string&gt; GetTags(int[] a)<br>{<br>  var list = new List&lt;string&gt;();<br>  <br>  for (var b = 0; b &lt; theList.Count; b++)<br>  {<br>    if (theList[b].CityCodes.Intersect(a).Any())<br>    {<br>      list.Add(theList[b].TagName);<br>     }<br>   }<br><br>   return list;<br>}</pre><p>Which tags will be returned from the GetTags() method? What is “a” parameter? What is “theList” variable? There are many uncertainties.</p><p>Without a comment or a deep dive of the code, it is impossible for me to understand what purpose this method and parameters serve. At this point, if I edit the naming on the condition that it makes sense in the context in which I am developing, I approach cleaner code. Let ‘s do it.</p><pre>public List&lt;string&gt; GetTagNamesThatMatchedCityCodes(int[] cityCodes)<br>{<br>  var tagNamesThatMatchedCityCodes = new List&lt;string&gt;();<br>  foreach (var tag in locationTags)<br>  {<br>    if (tag.CityCodes.Intersect(cityCodes).Any())<br>    {<br>      tagNamesThatMatchedCityCodes.Add(tag.TagName);<br>     }<br>   }<br><br>    return tagNamesThatMatchedCityCodes;<br> }</pre><p>Now, the mission of this method can be understood at a glance. It’s easier to discuss in code review sessions because it has meaningful naming.</p><p>If we want to optimize performance especially for large datasets, we can also prefer the use of “yield return”, but this may reduce the readability of the code. In such quandaries, we may need to decide whether the readability or the performance of the program is important to us. For example, if I’m developing a compression algorithm, I want it to work efficiently. But if I’m developing a program for business and it won’t create too much system load, I can accept to lose some performance to have a readable and maintainable code.</p><pre>public IEnumerable&lt;string&gt; GetTagNamesThatMatchedCityCodes(int[] cityCodes)<br>{<br>  foreach (var tag in tags)<br>  {<br>    if (tag.CityCodes.Intersect(cityCodes).Any())<br>    {<br>      yield return tag.TagName;<br>     }<br>   }<br>}</pre><p>Meaningful naming of variables, methods, and classes in the domain. This is another important point to strengthen communication within the team.</p><p>Developer, business analyst, product owner, etc. Names should be clear and understandable to every member of the team. Eric Evans defines the concept of “<strong>ubiquitous language</strong>” in his book “Domain-Driven Design: Tackling Complexity in the Heart of Software”, which is another book I would recommend to read if you get the chance.</p><p>The ubiquitous language is one of the key elements of dealing with complexity. This awareness will also prevent work accidents.</p><p><strong>Short And Focused Functions</strong></p><p>We should develop the functions as short and focused as possible. They should have only one mission (single responsibility) and they should do this mission to the best of their ability. This awareness will also prevent code duplication.</p><p>Methods with many lines of code increase complexity. Especially if we have an if statement or a code block containing loops, we can shorten the code block by making use of new methods to keep the code more understandable. This is an important topic in code review sessions to avoid increased complexity.</p><pre>private void CreatePluralDependentMessageParts(int orderCount) <br>{<br>  if (orderCount == 0) {<br>    FormatMessageForCustomerWithNoOrder();<br>   } else if (orderCount == 1) {<br>     FormatMessageForCustomerWithSingleOrder();<br>   } else {<br>     FormatMessageForCustomerWithManyOrders(orderCount);<br>   }<br> }</pre><p><strong>Data Transfer Objects</strong></p><p>Data transfer objects are a clean way to transfer data between application layers or functions.</p><p>I can talk about a scenario that will probably happen to you if you don’t use data transfer objects. As in the example below, the same type of method parameters come back to back, the developer trying to reach the deadline may confuse the string email and string appKey parameters. It won’t be long before you realize that your mail notification service has failed.</p><pre>public Customer(string name, string surname, string email, <br>string appKey, int age, bool isPremium)<br>{<br>      Name = name;<br>      Surname = surname;<br>      Email = email;<br>      AppKey = appKey;<br>      Age = age;<br>      IsPremium = isPremium;<br>}</pre><p>If the method has more than a few parameters, it is time to combine these parameters into the data transfer object.</p><pre> public Customer(CustomerDto customerDto)<br> {<br>      Name = customerDto.Name;<br>      Surname = customerDto.Surname;<br>      Email = customerDto.Email;<br>      AppKey = customerDto.AppKey;<br>      Age = customerDto.Age;<br>      IsPremium = customerDto.IsPremium;<br> }</pre><p><strong>Comments</strong></p><p>We should avoid writing comments. At first glance, we should be able to understand what purpose the code block serves. Correct naming and being focused are very important for clarity.</p><p>If the code is not clear, we should prefer code refactoring rather than commenting. However, comments can be made for situations that need to be explained.</p><pre>// Check to see if the order is eligible for shipping<br>if (order.Payment.IsCompleted &amp;&amp; order.Delivery.Slot.IsAvailable)</pre><p>It should be better like this;</p><pre>if (order.IsEligibleForShipping())</pre><p><strong>Use Searchable Names</strong></p><p>Avoid using magic numbers in your code. Using searchable constants helps you approach cleaner code. Also, when you want to make changes in your business logic, you will be able to edit it effortlessly without having to scan the entire code.</p><pre>if (password.Length &gt; 10)<br>{<br>   throw new ValidationException($&quot;Must be at least 10 characters&quot;);<br>}</pre><pre>if (password.Length &gt; MAX_PASSWORD_LENGTH)<br>{<br>    throw new ValidationException($&quot;Must be at least {MAX_PASSWORD_LENGTH} characters&quot;);<br>}</pre><p><strong>Error &amp; Validation Handling</strong></p><p>Sometimes we can find that the blocks of code written to process validation results or handle the error increase too much and make the code difficult to read. There should be a standard approach to error and validation handling throughout the application. And we have to make sure we don’t pollute the code base. To achieve this, we may prefer to throw an exception rather than carry error codes or flags. We can develop error handling middleware to log the exceptions and format our response.</p><pre> public bool IsValidPassword(string password)<br> {<br>   if (string.IsNullOrEmpty(password))<br>     throw new ValidationException(&quot;Cannot be null or empty&quot;);<br>   if (password.Any(char.IsLetterOrDigit))<br>     throw new ValidationException(&quot;Must contain at least one special character&quot;);<br>   if (password.Length &gt; MAX_PASSWORD_LENGTH)<br>     throw new ValidationException($&quot;Must be at least {MAX_PASSWORD_LENGTH} characters&quot;);<br><br>    return true;<br>  }</pre><p>Finally, I would like to end with the following advice;</p><p>For the mental health of ourselves and our team, we should try to make our code better by avoiding irregular developments. Dirty code will cause more time wasted in the future and worse, very difficult problems to solve. As you stick to the clean code principles, you will realize that you develop better quality code, and the outputs of your developments will give you more happiness.</p><p>Thanks for your time.</p><p>Okan Yüksel, Software Engineer</p><p><strong>References</strong></p><ul><li>Robert C. Martin, ‘Clean Code: A Handbook of Agile Software Craftsmanship’</li><li>Akın Kaldıroğlu, Clean Code</li><li>Yiğit Kemal Erinç, <a href="https://www.freecodecamp.org/news/clean-coding-for-beginners/">https://www.freecodecamp.org/news/clean-coding-for-beginners/</a></li><li>Sunny Sultan, <a href="https://sunnysultan1640.medium.com/what-is-bad-code-how-to-write-clean-code-a9b7b539ad8">https://sunnysultan1640.medium.com/what-is-bad-code-how-to-write-clean-code-a9b7b539ad8</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*b88hNn9FtEwMlYr3AZIMFg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd4a642984b8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hepsiburadatech/motivation-for-clean-code-dd4a642984b8">Motivation For Clean Code</a> was originally published in <a href="https://medium.com/hepsiburadatech">hepsiburadatech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>