Monthly Archives: October 2020

What’s that smell?

In computer programming, a code smell is any characteristic in the source code of a program that possibly indicates a deeper problem.[1][2] Determining what is and is not a code smell is subjective, and varies by language, developer, and development methodology.
The term was popularized by Kent Beck on WardsWiki in the late 1990s.[3] Usage of the term increased after it was featured in the 1999 book Refactoring: Improving the Design of Existing Code by Martin Fowler.[4] It is also a term used by agile programmers.[5]
(From Wikipedia, the free encyclopedia)

During her presentation at RailsConf in 2016 called Get a Whiff of This, Sandi Metz talks in depth about code smells, the practical effect of recognizing them and doing refactoring. My reason for choosing this particular source of information was because she gave real life examples and comparisons that helped me to better understand problems within codes that were humorous and I found her explanation of the types of code smells and how to fix them entertaining, easy to understand and very useful. Sandi presented examples of code she herself had written and demonstrated through diagrams and easy to follow steps how to refactor the code to make it neater. At the end of her presentation Sandi gives reference to a static analysis tool called Reek that you can run on your code and it will tell you what to go look at, so you don’t even need to go figure it out yourself.
This presentation really boosted my confidence as a programming student and gave me higher hopes as a future programmer. While watching this presentation video, I learned that most code is a mess, even the best coders can have messy code, and when given difficult or complex code, it can be broken down and easily fixed even if I am not able to understand everything within the given code. Going forward, I will definitely be referring back to this video to help me spot and correct any imperfections within my own code or any code I am given.

The 5 different categories of code smells are:

  1. The Bloaters – these make code bigger than they should or need to be.
  2. The Object Orientation Abusers/Tool Abusers – these are ideas that are available that you can misuse.
  3. The Change Preventers – these make change hard.
  4. The Dispensables – these represent something unnecessary that should be removed from the source code.
  5. The Couplers – these come as a bundle, they represent the attraction behavior of two classes which could be called excessive.

    (https://youtu.be/D4auWwMsEnY)

From the blog cs@worcester – Coding_Kitchen by jsimolaris and used with permission of the author. All other rights reserved by the author.

Factory Design Pattern

In keeping with my recent learning with java design patterns, I have been learning about the Factory Design Pattern. It is defined as a creational pattern by the Gang of Four and is very widely used because of the plethora of applications that it has. This seemed to be one of the best design patterns to learn as I saw a great many recommendations to do so in my research on design patterns. In the Factory Method Pattern article from Java T Point, the design pattern is made by, “[defining] an interface or abstract class for creating an object but [letting] the subclasses decide which class to instantiate.” In other words, if the client requires multiple similar behaviors, the Factory Design Pattern is used to choose the required subclass instance to complete the required behavior. The article outlines the key advantages to this design pattern, including the promotion of “loose-coupling” because of the lack of application specific classes into the code. It then gives a couple of examples for usage including a class not knowing what subclasses will be required. There is then a simple UML diagram which shows a small example of how an electricity bill may be calculated using the Factory Design Pattern. This example is then expanded upon. First, an abstract Plan class is created. It contains an abstract getRate method and a concrete calculateBill method. The subclasses show the real usefulness of the design pattern. There are 3 subclasses: DomesticPlan (with a rate of 3.50), CommercialPlan (with a rate of 7.50), and InstitutionalPlan (with a rate of 5.50). Each class implements the getRate method, which sets the Plan class’s rate variable to their respective rates. From here, a GetPlanFactory class is created which uses the Plan class and its subclasses to return a Plan object. The one method here is getPlan, which takes a string variable and has a set of if statements, each of which returns a different Plan subclass object depending on the string. Finally, the GenerateBill class is the one which the client interacts with. It asks the client the name of the plan needed, which the PlanFactory class uses to return an object of the one of the Plan subclasses. Then, units of electricity are taken from the client. The Plan subclass object then calls getRate to get the rate associated with the plan, and then calculateBill to tell the client the total charge for electricity usage. Although the explanation seems complicated, it is quite simple and clean in implementation, and extremely useful when one does not know which of a given set of behaviors will be required. I expect I can use this design pattern quite frequently in my personal, school-related, and professional coding. 

From the blog CS@Worcester – Marcos Felipe's CS Blog by mfelipe98 and used with permission of the author. All other rights reserved by the author.

Best Practices for Using Docker

For the past few weeks, we have been working a lot with Docker and how to use it. Coincidentally, I came across an article describing some best practices when using Docker. Some of the things in the article were even things we used in class.

Many things were given to keep in mind. There is size. Images should not waste space, especially as it could be a security concern. Using Alpine Linux is a great way to save space though it may not always be appropriate. It is also important to keep your Dockerfile current. Using the latest tag is one way but the author also says to check regularly to make sure you really are building from the latest version. The author also mentions a new tool called docker scan to find known vulnerabilities in your Docker images. There is a lot of emphasis on Docker containers being simple and easy to create and take down. The system should be designed to do so without adversely affecting your app as that is the whole point of Docker. At the end of the article there are additional links to more articles about Docker by the same author.

I selected this article because it is relevant to the current course material. We have been using Docker in all our classes for the last few weeks. As I was reading the article I recognized where the author says use “Use Alpine Builds” because we do use those in class. The article even explains to use “FROM alpine”, something we start our Dockerfiles with in class.

Because the tips in the article were kept very general, I was able to understand most of it. For more technical articles I often get confused or lost, especially since I have no experience working in the software development industry. Reading this article made me realize how far I have come since I started the CS major. Going in I had no programming experience and little to no aptitude when it came to computers. Seeing the things we learn in class actually be relevant in the real world is a very validating thing. It proves to me that I am actually learning, something that is only more difficult with remote learning.  

I hope to be able to use this article going through the course and on the final project. These tips should help me get the most out of Docker.

From the blog CS@Worcester – Half-Cooked Coding by alexmle1999 and used with permission of the author. All other rights reserved by the author.

Law of Demeter

Todays blog is about the Law of Demeter a.k.a the Principle of Least Knowledge. This information is based off of the article, “Object Oriented Tricks: #2 Law of Demeter”, by Arun Sasidharan on the website “Hackernoon”. The law uses the Tell Don’t Ask principle which states that we may call methods of objects that are: passed as arguments, created locally, instance variables, and globals. In other words, saying that “each unit should only have limited knowledge about other units”, that are closely related to the current unit. Basically the Law of Demeter (LoD) says that it is a bad idea for single functions to know the entire navigation structure of the system, or to have a chain of functions, also known as a “Train Wreck”. The article states, “We want to tell our neighboring objects what we need to have done and depend on them to propagate that message outwards to the appropriate destination”, and that is what we need to do to solve this problem of “Train Wrecks”.

I chose this article because it was one of the first to come up when searching “Law of Demeter”. When I looked into the article it seemed like a reliable source. I also looked up reviews on the website before diving too far into the article. Many people suggested the website in their reviews so I concluded that it was a trustworthy source. The article has paragraphs discussing the law/principle, code snippets to show the before and afters of using the Law of Demeter, and then a final summary at the end to give an overview of everything talked about. I have found that articles with the same elements/structure help me a lot with understanding a new subject.

While reading about the Law of Demeter, it brought me back to a few times where I personally broke the law on projects. There has also been a few times where I have seen people break the Law of Demeter in tutorials, such as the one I watched for the Decorator Pattern. With this article, I learned how to write reliable, clean functions and to use them in a reliable manner. I also learned that it is very difficult to accomplish. As the article states, it is more of a suggestion than a law for that exact reason. Unlike some of the other principles, this is something that we cannot be proficient in in a single day. It is something to set as a longer term goal to improve on. I hope, through practice, to be able to utilize this principle in an efficient manner on future projects.

Source: https://hackernoon.com/object-oriented-tricks-2-law-of-demeter-4ecc9becad85

From the blog CS@Worcester – Austins CS Site by Austin Engel and used with permission of the author. All other rights reserved by the author.

Don’t Spend So Much Time Coding Cleanly!

There comes a point in every developer’s career where they transition from “make it work” to “oh my God I need to make this look decent”. Initially, our goal is to create a functional Hello World program. However, as we develop, we slowly begin to learn proper code styles and naming conventions. After reading enough Stack Overflow Forums, we start to become self aware of how our code looks and we begin to focus on code aesthetics. While there’s merit in that, we often focus on the wrong things.

This video does a great job of explaining just that: there isn’t really any such thing as clean code. Now, that isn’t to say that there aren’t wrong ways to code. I’m sure we can all name plenty. That being said, the main point is that we shouldn’t spend our time trying to code perfectly the first time.

The best way to code is to do so as well as we can without spending too much time overly focused on getting everything right the first time. If you know you have the opportunity to do something right or cut corners, do it right. However, if you’ve spent 10 minutes trying to name a variable, give it some placeholder name and worry about it later. The first priority is functionality. Later on, you can review and refactor your code.

The main goal of refactoring is readability. In a compiled language especially, there is only so much efficiency the programmer can add. Compilers do a remarkable job of optimizing code by themselves, so your main goal should be readability. Make sure that other developers, as well as your future self, can read and understand your code. Add comments where necessary, but aim for self-commenting code. If your code is its own comment, that helps save space.

In conclusion, focus on simple and readable code. Don’t waste your time doing something that can simply refactored later, within reason. With that being said, try to do things right the first time if it’s obvious how to do it right.

From the blog CS@Worcester – The Introspective Thinker by David MacDonald and used with permission of the author. All other rights reserved by the author.

TECHNICAL DEBT

As I was preparing for my exams, I came across the term/topic technical debt as one of the topics under the review topics and this term was seen in one of the class activities. I decided to research on the topic, write a blog post to broaden my understanding for the exams. I came across this blog post that talks about technical debt and chose this blog because the concept has been broken down into topics explaining the term in-depth.

The term technical debt has been described in this blog as well as the good and bad reasons for technical debt. It also explains and gives examples on the various types of technical debt such as Planned Technical debt, unintentional technical debt, unavoidable technical debt, software entropy. It also explains some identifications of technical debt in a project and various ways on how technical debt can be avoided and managed. A youtube video is provided explaining the term as well.

In this blog I learned that although the term may sound like a financial term, it is defined as the deviation of an application from any nonfunctional requirements. Simply, it is a code you have to work on tomorrow because you took a shortcut to deliver it/software today. Technical debt just like in financial terms can have interests which is the difficulty to implement changes and thus needs to be addressed in order to prevent software entropy and risks that may relate to the source code. Teams may delay better coding and certain pieces which are understood by them to impede future development, however, interests may cumulate if these pieces, mediocre codes and known bugs that were left are not resolved.

Technical debts can be identified when code smells are too subtle than logic errors and when there are higher levels of complexities with technologies overlapping each other. Other warnings signs include product bugs that will cause an entire system crash and issues with coding styles.

I learned in Planned technical debt that organizations make an informed decision to generate technical debt knowing and understanding the risks and cost while Unintentional technical debt occurs as a result of poor practices, inexperience with new coding techniques and rollout issues. Unavoidable technical debt is created due to changes in the business and technology that present better solutions hence, making old code obsolete.

One way of managing technical debt is to assess debts and to acknowledge that technical debts exists and share discovery with stakeholders, explaining the importance of paying off technical debt earlier. Technical debt can also be managed by using Agile methodologies that can ensure that teams are working on technical debt.

I hope others find this blog educative as well.

https://www.bmc.com/blogs/technical-debt-explained-the-complete-guide-to-understanding-and-dealing-with-technical-debt/

From the blog CS@Worcester – GreenApple by afua3254 and used with permission of the author. All other rights reserved by the author.

RESTful API from another Perspective

A topic that I chose to learn more about for this week is ‘REST API Design’ as listed in our course syllabus. The source that I had used to supplement my learning was a conference talk on REST API called Never RESTing – RESTful API Best Practices using ASP.NET Web API – Spencer Schneidenbach. This source will be linked at the bottom of this post; however, I would like to mention that I enjoyed this conference talk as I found it both informative and insightful.

In the talk, Schneidenbach goes over his experiences and gives insight into building and designing RESTful API’s. He breaks down building/designing restful api into four activities, design, implementation, document, and maintenance; although he mentions that practically all four of these activities or a culmination of the two activities would be performed at once when working on api, he tries to separate the four activities in his talk. Throughout the talk he also brings up other topics such as explaining what REST and api’s are; however, I would rather discuss segments what I found informative or insightful from his talk.

One of the things he brings up when designing api is that ‘restful api != good api’; and this claim that an api that solely follows the constraints imposed for REST API does not solely make that api good; rather he argues that when building api we should be doing what makes sense and ‘throw out the rest’. I really resonated from this statement, as it made the designing process more practical in that when building api we must be flexible and logical with our decisions; and that theoretical rigid constraints are not what always works in real environments.

In conjunction to this statement, he also mentioned two prime rules he kept in mind which were, KISS and be consistent. KISS meant to keep things simple, but an element of KISS that I found insightful, was asking who we are keeping things simple for. He argues that when designing we should always keep in mind the user experience or the consumer who will be using the api. I thought this was interesting perspective to think of how to keep things simple for a consumer to use the api when designing it; in addition to this rule, he also added to not be creative and just provide enough that is necessary and no more or less, which I agreed with. For the consistency principle, it was straightforward strategy to keep things consistent with accepted best practices; however, I also enjoyed his second comment ‘be consistent, but be flexible when it makes sense’. This comment reiterated a theme in design that there is no silver bullet in designing api, and that although there are solid principles that we should follow, we need to be have some sense to find a balance with what our consumers require and want.

From the blog CS@Worcester – Will K Chan by celticcelery and used with permission of the author. All other rights reserved by the author.

Let’s talk about adapters

This week I will be touching base on a structural design pattern called the adapter pattern. This pattern has two different versions, the class adapter – which implements the adapter using inheritance and can only be used in C++, and the object adapter – which uses composition to reference an instance of the wrapped class within the adapter. For the purpose of this blog post, I will be speaking only of the object adapter pattern.

Structural design patters are supposed to simplify your design, the adapter pattern in particular makes doing so easy as pie. The adapter pattern reuses old interfaces and provides different interfaces to its subject in order to make things work after they’ve been designed, even if the previous interfaces were incompatible. So what can this pattern do? Let’s break it down a bit:

– Change the interface of an existing object.
– Provide a different interface to its subject.
– Make things work after they’ve been designed.
– Reuse old interfaces.

The adapter pattern addresses incompatible interfaces and lets classes work together that previously could not due to incompatibility by converting the interface of a class into another interface that the clients expect. This conversion process allows software to exchange and make use of information. When you are dealing with different interfaces with similar behaviors, it is best to use this design pattern to help develop a clearer, more easily understandable code. A brief list of some of the benefits of using adapter patterns are:

– It is a low-cost solution.
– It is easy to understand.
– Incompatible code can communicate with each other.
– It makes things work after they’re designed.
– Helps to reuse existing code.

Information gathered for this blog post:
https://stacktraceguru.com/adapter-design-pattern
https://www.geeksforgeeks.org/adapter-pattern/
https://www.java2novice.com/java-design-patterns/adapter-pattern/
https://sourcemaking.com/design_patterns/adapter

From the blog cs@worcester – Coding_Kitchen by jsimolaris and used with permission of the author. All other rights reserved by the author.

Facade Design Pattern

This week we practice docker a lot bout docker Activity, but we havent learn all about patterns so I choose to write one more Main Design Pattern call Facade Design Pattern. in my homework 3 I picked Decorated design pattern but I have’t learn more about Facade Design Design Pattern. This is really help full in programing becuse it have high level interface that make subsystem easier to use.

Facade design pattern provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.Facade pattern is one of structural design pattern among other Gang of Four design pattern. The facade pattern is appropriate when we have a complex system that we want to expose to clients in a simplified way. Its purpose is to hide internal complexity behind a single interface that appears simple from the outside. Facade also decouples the code that uses the system from the details of the subsystems, making it easier to modify the system later.

To understand the facade, let’s take a very simple example of a desktop computer machine. When we have to start a computer, all we have to do is press the start button. We really do not care what all things go inside the computer hardware and software. It is an example of Facade pattern.

In Java programming, we must have connected to a database to fetch some data. We simply call the method dataSource.getConnection() to get the connection but internally a lot of things happen such as loading the driver, creating connection or fetching connection from pool, update stats and then return the connection reference to caller method. It is another example of Facade pattern in the programming world. Similarly, we can find a lot of more examples which hide lots of internal complexities and provide simple to use interface to the programmer to work with the system. All such are facade examples.

Remember facade does not reduce the complexity. It only hides it from external systems and clients. So the primary beneficiary of facade patterns are client applications and other systems only. It provides a simple interface to clients i.e. instead of presenting complex subsystems, we present one simplified interface to clients. It can also help us to reduce the number of objects that a client needs to deal with.

When you call a shop to place a phone order, an operator is your facade to all services and departments of the shop. The operator provides you with a simple voice interface to the ordering system, payment gateways, and various delivery services.

Source:

https://refactoring.guru/design-patterns/facade

https://www.tutorialspoint.com/design_pattern/facade_pattern.htm

From the blog CS@Worcester – </electrons> by 3electrones and used with permission of the author. All other rights reserved by the author.

Adapter Design Pattern

 

    This week On my Blog, I want to talk about a design pattern. The One I want to focus on is Adapter Design Pattern. Adapter design pattern Convert an interface of a class into another interface clients expect. The adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. The adapter design pattern is a structural design pattern that allows two unrelated/uncommon interfaces to work together. In other words, the adapter pattern makes two incompatible interfaces compatible without changing their existing code. Now Let’s take a look at an example that shows how the design works. From the blog, I used it provided a diagram that I think is helpful to understand the design pattern. In this diagram, Socket wrenches provide an example of the Adapter. A socket attaches to a ratchet, provided that the size of the drive is the same. Here a Ratchet is ½ in size and the socket is ¼ without using an adapter you cannot connect the ratchet and socket together. 



    Now let us take a look at the benefits and liabilities of using the adapter design pattern. The first benefit is that you can let any two unrelated classes run together. Second, Improved the reuse of classes, it Increased the transparency of classes and it has Good flexibility. Now for the Liabilities, the Adapter design pattern takes Too much use of adapters will make the system very messy and difficult to master as a whole. For example, if an interface A and B are implemented and interface B is adapted internally. If too many tasks are running in A system, it will be A disaster. So, if it’s not necessary, you can simply refactor the system without using an adapter. Also, in object-oriented programming especially in JAVA it inherits at most one class, it can only adapt to one adapter class at most, and the target class must be an abstract class.

    A real-life example that I found was about the card reader ACTS as an adapter between the memory card and the laptop. You insert the memory card into the card reader and insert the card reader into the portable computer. The memory card can be read from the portable computer.

    This source is helpful to understand the design pattern even more. I would suggest you take a look at the website because it goes into further detail about the Adapter design pattern, including various examples using diagrams and JAVA codes. 

 

Source: https://sourcemaking.com/design_patterns/adapter#:~:text=Intent,class%20with%20a%20new%20interface

From the blog haorusong by and used with permission of the author. All other rights reserved by the author.