Category Archives: CS-343

The Principle of Least Knowledge

As I was reading about coupling and cohesion, I also came across the Principle of Least Knowledge, which just so happened to be on our list of topics in the syllabus.

The Principle of Least Knowledge (or Law of Demeter) was first discussed in 1987 at Northeastern University. It states that an object should never now the internal details of other objects, which makes sense given the name. It is used to promote loose coupling in software designs.

The article also gives an example using 3 classes – A, B, and C. Each class has objects objA, objB, and objC. objA is dependent on objB, which in turn composes objC. In this scenerio, objA can invoke methods and properties of objB but not objC. Say C has a method M. If you make a objC called O, the Principle of Least Knowledge says O can access

  • The same object, i.e., the object “O” itself
  • Objects that have been passed as an argument to the method “M”
  • Local objects, i.e., objects that have been created inside the method “M”
  • Global objects that are accessible by the object “O”
  • Direct component objects of the object “O”

A code example is also given to illustrate the concept.

public class LawOfDemeterExample

    {

        //This is an instance in the class scope

        //and hence this instance can be accessed by any members of this class

        AnotherClass instance = new AnotherClass();

       public void SampleMethodFollowingLoD(Test obj)

        {         

            DoNothing(); //This is a valid call as you are calling a method of the same class

             object data = obj.GetData(); //This is also valid since you are calling a method

            //on an instance that has been passed as a parameter           

             int result = instance.GetResult();  //This is also a valid call as you are calling

            //a method on an instance locally created

        }

        private void DoNothing()

        {

            // Write some code here

        }

    }

After, an second example is given to illustrate what not to do.

var data = new A().GetObjectB().GetObjectC().GetData();\

In this example the client depends on all three classes A, B, and C. If any of the three change you will run into issues.

This principle will definitely be important as I continue my career in software development. As the ode I write gets more complex, I have to be wary of violating principles like this to maintain low coupling. The author also mentions testability being improved with this principle and the loosely coupled code it encourages. Next semester I am taking the software testing course; right now I have next to no knowledge about software testing. I only know how to just test units made for me in java. Hopefully I will see how loosely coupled code compared to tightly coupled code in testability.

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

Coupling and Cohesion

This week I wanted to learn more about coupling. The article I found happened to be about both coupling and cohesion.

Coupling and cohesion are both terms that refer to the modularity in a system. They help measure how complex the design of an object-oriented system is. Good knowledge of both is needed to build scalable systems that can be extended and maintained over time.

Coupling is how interdependent software modules are. With high coupling, software modules are very independent, and they need each other to run. There are several types of coupling:

  • Content coupling — this is a type of coupling in which a module can access or modify the content of any other module. When a component passes parameters to control the activity of some other component, there is a control coupling amongst the two components.
  • Common coupling — this is a type of coupling in which you have multiple modules having access to a shared global data
  • Stamp coupling — this is a type of coupling in which data structure is used to pass information from one component in the system to another
  • Control coupling — this is a type of coupling in which one module can change the flow of execution of another module
  • Data coupling — in this type of coupling, two modules interact by exchanging or passing data as a parameter

Cohesion is how intra-dependent a software module is. High cohesion is a software module that forms its own meaningful unit. There are also different types of cohesion:

  • Co-incidental cohesion — this is an unplanned random cohesion that might be a result of breaking a module into smaller modules.
  • Logical cohesion — this is a type of cohesion in which multiple logically related functions or data elements are placed in the same component
  • Temporal cohesion — this is a type of cohesion in which elements of a module are grouped in a manner in which they are processed at the same point of time. An example could be a component that is used to initialize a set of objects.
  • Procedural cohesion — this is a type of cohesion in which the functions in a component are grouped in a way to enable them to be executed sequentially and make them procedurally cohesive
  • Communicational cohesion — in this type of cohesion the elements of a module are logically grouped together in a way that they execute sequentially and they work on the same data
  • Sequential cohesion — in this type of cohesion the elements of a module are grouped in such a manner that the output of one of them becomes the input of the next — they all execute sequentially. In essence, if the output of one part of a component is the input of another, we say that the component has sequential cohesion.
  • Functional cohesion — this is the best and the most preferred type of cohesion in which the degree of cohesion is the highest. In this type of cohesion, the elements of a module are functionally grouped into a logical unit and they work together as a logical unit — this also promotes flexibility and reusability.

Tight coupling makes maintenance difficult as all the components depend on each other.

This article was helpful in explaining these two concepts. As we develop increasingly complicated software in our courses and careers it is important to learn more abstract concepts. These were things I have never really thought about before. Usually I write code just so that it works. If I am going a step further I might try to make it “look good” and be neatly indented with as few lines as possible. Especially going into the capstone course, I will have to evaluate my code for things like low coupling and high cohesion.

https://www.infoworld.com/article/2949579/design-for-change-coupling-and-cohesion-in-object-oriented-systems.html

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

MongoDB and NoSQL Databases

            In our practice with REST API backends, multiple times we ran into MongoDB usage, as the database we were using for the API was MongoDB. My only previous experience had been SQL/SQLite, so I wanted to know what the difference was. I came to find out there is a world of difference, in fact MongoDB is a NoSQL database (NoSQL meaning… well exactly what you would expect it to mean). I found an article – part of a MongoDB tutorial – from Guru99 called Types of NoSQL Databases, What is & Example which dove into the differences and usefulness of MongoDB and other NoSQL databases. Chiefly, NoSQL DB’s do not require fixed schemas, avoid joins, and are easy to scale, which is perfect for distributed data storage and “scaling out”, which is becoming increasingly essential in the CS world. The lack of schema is convenient too, as it allows for “heterogeneous structures of data in the same domain,” providing for great versatility. The other essential parts of NoSQL include it being non-relational and having a relatively simple API. The four kinds are Key-value pair based, column-oriented graph, graph based, and document oriented. Key-value pair based means data is stored in pairs (with a key and a value), which is optimal for large datasets and heavy loads. Column-based means that work is done on separated columns with values in single columns being stored contiguously, performing well with aggregation queries. Document-oriented DB’s (MongoDB is one) also function as a key/value pair, but in this, a value is stored as a document, which is stored in JSON or XML. It is not optimal for high performance or aggregate structures, like Key Value or Column Based. Graph based stores entities and relationships between them. Each entity is a node and each relationships is an edge, defining the relationship. This is different from relational DB’s inn that Graph DB’s are “multi-relational.” NoSQL DB’s commonly query with a key and a GET request. The CAP theorem is also important to NoSQL because it guarantees at most two out of the following three: consistency, availability, and partition tolerance. This is a key limitation of NoSQL DB’s. The last key to NoSQL falls on the concept of eventual consistency, meaning that changes to data on one machine must be reflected on other replicas eventually. Where the standard for RDBMS is ACID, NoSQL is BASE: Basically Available, Soft state, Eventual consistency. The article goes on the list advantages, disadvantages, and summarize itself before coming to a close. I thought this was very interesting to learn, as I can see how different DB styles can reflect the needs of a project or client story. I wasn’t sure why we were using MongoDB; I kind of took it as a given. But this reading broadened knowledge, so now, if I am able to build a REST API of my own over the upcoming break, perhaps I can find the optimal DB for my needs, or help me better understand future projects once I join the workforce.

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.

Code Smells

https://blog.codinghorror.com/code-smells/

This blog post will center on code smells which was a topic covered in class fairly early on. The reason why I’m going back to it is mainly to refamiliarize myself with the subject since it wasn’t a major topic in class. Code smells are defined by the blog post linked above as general warning signs in code, hence the name. There are different types of code smells that signify different coding problems. For example, long comments, long methods, overly large classes, duplicate code, dead code, inconsistent naming, uncommunicative naming, et cetera. Keep in mind that these issues won’t necessarily stop a program from running, rather they negatively effect on the performance and design levels. Also, all of these different types of code smells share the common trait of not quite looking right when looking at a larger scale. So at first glance the code might seem fine, but given a closer look the flaws whether it be dead code, inconsistent naming, or whatever become readily apparent.

A code smell isn’t something concrete like a detailed recipe, it’s more abstract than that. It similar to a suggestion or a tip and can lead to improving code both on a functional level and a design level. Take for example, noticing the code smells of long comments and dead code which suggest removing the useless code and either simplifying or outright deleting the comments. This will make the code more readable which also improves it on a design level. On the other hand, noticing the code smells of duplicate code and long methods and correcting each issue accordingly will improve the code on a performance level top of the possible design improvements. All of the types of code smells that I listed earlier still hold true but they act as more of a general guideline. There are some scenarios in which some smell types blend together such as long methods and overly large classes to name one. Detecting code smells isn’t going to always be the same in that what someone is looking for will differ every time and the outcome will also differ every time. This process is kind of like trying to find freshly spoiled food; sometimes it looks fine and sometimes you won’t know what exactly you’re looking for. But what you do know is that something smells off and you probably don’t want to risk the chance of getting sick.

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

REST API Design Practices

What is REST API? - Seobility Wiki

For many assignments in a recent class, I had the opportunity to use and learn about REST (Representational State Transfer) API in relation to simple web applications. In working with REST, I was unsure about some of the syntax and conventions used with the API, namely the difference between different response types (JSON vs String response for instance).

I looked into finding some more information on good practices for REST API projects, and according to a helpful blog post I found on Stack Overflow (https://stackoverflow.blog/2020/03/02/best-practices-for-rest-api-design/), REST APIs should generally both request and send responses with JSON (JavaScript Object Notation). I had a number of issues with sending and receiving data which was not in this format (needed to send/receive strings in POST methods within an endpoint). This was causing problems such as information not being sent and received properly (name field of an item not being sent or received in the right places) as well as issues with the functioning of the web application itself (endpoints belonging to unrelated services would cease to function properly if the requests and responses were not JSON.

Furthermore, according to the author, JavaScript has baked-in methods to handle interacting with JSON entities, which makes it easier to use overall especially if there are other JavaScript based technologies being used within the structure of the project, so it makes sense to use JSON within requests/responses. So in future projects involving REST, I will attempt to primarily use JSON objects for responses and requests to ensure compatibility and easy access through JavaScript.

Another point which was discussed was the importance of using nouns in naming conventions, rather than verbs (specifically nouns which are highly representative of the destination or object being affected) when naming endpoint paths. IE: instead of POST: /orderPizza/, use POST /order/ when trying to create a new order. This makes sense, as the HTTP methods typically describe the action or verb being enacted on an object, so you needn’t describe that within the endpoint path.

Finally, I want to discuss the topic of HTTP status codes; the author of this article describes the meaning of many common error codes and why you might return them as a response. This was especially helpful for me as I had been using these codes within a REST project, but had no idea what the majority of them actually meant. According to the article, a code of 400 indicates a client-side validation error, 401 represents an authorization or permissions error, and 404 represents an inability to find a particular resource. Out of all of these errors, 404 is definitely the most common from my experience. I have frequently seen this while using the internet whenever a page would couldn’t be found on a website/web application, it was pretty neat to learn more about.

What is a 404 Page? - Learn to code in 30 Days
Example of a common 404 not found error page

Overall, after reading this article I feel more informed about the way REST API services work, and will be more prepared for the next project I work which makes use of the framework.

Post Referenced: https://stackoverflow.blog/2020/03/02/best-practices-for-rest-api-design/

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

AngularJS

This post today is about AngularJS based off of the article AngularJS-Overview by TutorialPoint. AngularJS is a structural framework for dynamic web applications that was developed in 2009 by Misko Hevery and Adam Abrons. Its latest version 1.2.21 is now maintained by Google. AngularJS lets you use HTML as a template language and then allows you extend the the syntax to express application components. It is a framework used to build large scale and high performing applications that are easy to maintain. General features include that it is open source and licensed under Apache license version 2.0, it is an efficient framework able to create Rich Internet Applications (Web apps that are able to perform the normal features and functions of normal applications), provides an option to write client side applications using Javascript under an efficient Model View Controller method, and AngularJS is cross-browser compliant so that it automatically handles JavaScript for each browser. The advantages of AngularJS are that it has the ability to make single page applications in a clean way, provides data binding capabilities to HTML giving it a responsive experience, it is unit testable, uses dependency injection, gives the ability to provide more functionality with less code, and it can run on all major browsers and smartphones. The disadvantages are that it is not secure and not degradable. Since it is a framework that is JavaScript only, it is not safe so server side authentication is a must. Also since it is all JavaScript, if the user disables it, the webpage would show nothing but the basic page.

This relates to class because we were looking at the process and components that go into web applications. I selected TutorialsPoint because I have used it before for overviews, tutorials, and references. It has proven to be a reliable source to me so I do not have to worry about getting the wrong information. Their reviews online are typically very well rated with key words such as reliable, useful and helpful. I have found those three keywords to be true with this article. I had learned many things since I did not know much about AngularJS prior to reading the article. Some of these things include that it is very useful for single page applications and that it is not very secure. This is very useful for me to learn about because I am currently planning a single page web application project so it is an option for me to utilize.

Source: https://www.tutorialspoint.com/angularjs/angularjs_overview.htm

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.

Maven Overview

Today I will be writing about Maven using information from the article Maven-Overview by TutorialsPoint. Maven is a project management tool giving a complete build process framework. Mavens objective is to provide a comprehensive, reusable and maintainable model for projects and to provide plugins and tools to interact with this model. Since Maven uses a standard directory layout and default build lifecycle, development teams can quickly set up their project builds. When you have multiple development teams Maven can create a standard build structure for all teams to use. This promotes consistency across the project while developers create reports, builds and testing automation setups. Maven gives a way for developers to manage builds, documentation, reporting, dependencies, SCMs, releases, distribution and mailing lists. Mavens project structure is declared in in the pom.xml file. POM stands for Project Object Model and contains the fundamentals of the entire Maven system. This pom.xml file is similar to the build.gradle file we have seen/used in class. Some features of Maven include its ability to generate a website or PDF including complete documentation, backwards compatibility, automatic parent versioning so that there is no need to specify in the sub module, parallel builds achieving performance improvements of up to 50%, and improved error reporting.

This topic relates to class because it is a software project management tool, which can be very useful to developers. We often used Gradle in class which is a similar concept. I selected this article from TutorialsPoint because it is a useful website for quick references, overviews and tutorials. It is similar to w3schools which is another website I use often for quick tutorials, references, etc.. I would say that the information is reliable, just more shallow as it does not dive deep into topics. I would not use it as the only source when trying to learn a certain subject in depth as you will not get a deep understanding of the material. As an overview though, I would say it is perfect. I personally had an okay understanding of Maven as I had used it a couple of times but never knew the finer details as to how it is different from other project management tools. Some things I had learned from this article are its many features including its use for reporting and documentation. I plan to use project management tools for future projects, so it is good to know the differences and know which one is the right one to use.

Source: https://www.tutorialspoint.com/maven/maven_overview.htm

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.

What is AngularJS?

In the Software Constr. class, I was presented for the first time with the angularjs front-end web framework. AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML’s syntax to express your application’s components clearly and succinctly. AngularJS’s data binding and dependency injection eliminate much of the code you would otherwise have to write. And it all happens within the browser, making it an ideal partner with any server technology.

I had the chance to work a little with this framework and I understand some part of it how it works. Angular has the following key features which makes it one of the powerful frameworks in the market.

 MVC – The framework is built on the famous concept of MVC (Model-View-Controller). This pattern is based on splitting the business logic layer, the data layer, and presentation layer into separate sections. The division into different sections is done so that each one could be managed more easily.

Data Model Binding – You do not need to write special code to bind data to the HTML controls. This can be done by Angular by just adding a few snippets of code.

Writing less code – When carrying out DOM manipulation a lot of JavaScript was required to be written to design any application. But with Angular, you will be amazed with the lesser amount of code you need to write for DOM manipulation.

Unit Testing ready – The designers at Google not only developed Angular but also developed a testing framework called “Karma” which helps in designing unit tests for AngularJS applications.

There are some advantages for this framework.

Since it is an open-source framework, you can expect the number of errors or issues to be minimal.

Two-way binding – Angular.js keeps the data and presentation layer in sync. You do not need to write additional JavaScript code to keep the data in your HTML code and your data later in sync. Angular.js will automatically do this for you.

Angular can take care of routing which means moving from one view to another. This is the key fundamental of single page applications; wherein you can move to different functionalities in your web application based on user interaction but still stay on the same page.

It extends HTML by providing its own elements called directives.  So why Angular? While AngularJS does not suit every project idea, it builds amazing apps. The most valuable reasons of AngularJS usefulness lie in their concepts and benefits that they provide. Nowadays with all marketing strategies and technologies to find a worth product has become a real challenge. Besides, it is easy to lose yourselves among all those benefits that are listed by every product. And it is even harder to find those ones you really need and that really suits your idea.

From the blog CS@Worcester – Tech, Guaranteed by mshkurti and used with permission of the author. All other rights reserved by the author.

What is the difference between a software framework and a software architecture?

Software frameworks are reusable “semi-finished” software for domains (such as ERP, computing, etc.) that implement common parts of the domain and provide well-defined points of variability to ensure flexibility and extensibility. In other words, the software framework is the softwarenation of the results of domain analysis and the template for the final application in the domain.

With the expansion of software scale, wide application and the development of software reuse technology, the software reuse based on subroutine and class has a lot of shortcomings:

(1) The library of the subroutine is becoming more and more huge, which makes it difficult for its users to master

(2) Most classes are too small to do all the useful work by themselves

It is for these reasons that a set of classes (modules) are considered as a whole in reuse, resulting in a software framework. The software framework contains at least the following components:

(1) A series of modules to complete the calculation become components

(2) The relationship between components and the interaction mechanism

(3) A series of variable points (hot spots, or adjustment points)

(4) Behavior adjustment mechanism of variable point

Developers through the software framework behavior adjustment mechanism, peculiar to the general application domain software module bound to the variable point of a software framework, and got the final application system, this process is called software example of a software framework, the existence of software framework allows developers will be the main energy on the development system of the module, so as to improve software productivity and quality.

The behavior adjustment mechanism of the software framework refers to how to adjust the variable part of the framework for the specific application and how to add the method and rules of the specific application module at the variable point.

Ii. Software architecture

Software architecture is a sketch of a system. The objects described by software architecture are abstract components that directly constitute the system. The wires between the components describe the communication between the components explicitly and in relative detail.

Software architecture, by definition, is divided into two camps of ‘constituent’ and ‘decision-maker’, which are described as follows:

The componentized view of software architecture is that the system is described as computing components and their interactions. It has two very obvious characteristics:

Focus on the object of architectural practice — software, with the software itself as the object of description.

This paper analyzes the composition of the software, and shows that the software is not a whole in the sense of “atom”, but a whole composed of different parts connected through a specific interface, which is very important for software development.

Decision-makers believe that software architecture involves a series of decisions, mainly including:

Organization of software systems

Choose the structural elements that make up the system, the interfaces between them, and the behavior that these elements exhibit when they cooperate with each other

How do you combine these elements so that they gradually synthesize into larger subsystems?

The architectural style used to guide the organization of the system: these elements and their interfaces, collaborations, and combinations

Software architecture is concerned not only with the structure and behavior of the software itself, but also with other features: usage, functionality, performance, elasticity, reuse, understandability, economy, and technical constraints and trade-offs.

Personal understanding: When software engineering has a certain scale, software development does not exist in the form of data structure + algorithm, but “divide and conquer” software based on many factors such as technical choices and user needs. The main task of the architect is to divide the software into different modules and define the interfaces between modules.

Sources:

https://softwareengineering.stackexchange.com/questions/229415/difference-between-an-architecture-and-a-framework#:~:text=An%20architecture%20is%20the%20the,that’s%20designed%20to%20be%20extended.&text=Frameworks%20are%20specifically%20designed%20to%20be%20built%20on%20or%20extended.

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

DRY (Don’t Repeat Yourself)

https://thevaluable.dev/dry-principle-cost-benefit-example/

I’ve chosen to talk about a very simple design principle this week called “Don’t Repeat Yourself”, DRY for short. It’s a topic that is covered in this class according to the syllabus and I chose it since its similar to another topic I covered YAGNI in that they’re easy to understand design principles. The meaning is quite self-explanatory, don’t repeat code since if you need to change the behavior of a certain project, you’d have to rewrite numerous lines of code if DRY wasn’t applied. However, applying this principle to everything isn’t efficient either. Trying to apply DRY everywhere causes unnecessary coupling and complexity which also leads to more difficulty changing behavior. According to the link above, using DRY means emphasizes knowledge above all else. What it means by that is that when designing and constructing software, one should have the knowledge of when to apply DRY and when not to for the sake of the readability and efficiency of the code.

In that context, DRY reminds me of the importance of resources in a computer when running something. If you want something run faster, you’ll have to sacrifice more memory. And when you want something to have more memory, you’ll have to sacrifice more speed. Both are valid choices; it really depends on the needs of the software and the user. Say for example, I want to create a program that lists all numbers from one to 100 which I do by writing out a thousand lines of code in which each prints a number. However, if I implement DRY, then I could create an integer variable r and a loop which prints the value of that variable and increments it by one until r equals 100. But the case where I want to alter the behavior to list every odd number between one and 100 is where thing get a bit interesting. In the DRYless scenario, I can simply delete the lines of code that print even numbers. Yet in the scenario with DRY, I’d have to add a condition that skips printing variable r for that iteration of the loop. You have to sacrifice complexity for readability and vice versa. Though the choice is ultimately up to what works best in the current situation. Like in my example, the added complexity from DRY doesn’t really harm the readability, in fact it improves it in some ways, at least in my opinion.

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