Category Archives: CS-343

What’s the difference between JavaScript and Java?

 What is Javascript?

It’s a scripting language that runs in a browser, and Javascript can do almost anything on a Web page:

HTML can be manipulated, providing a tool to change HTML at runtime. Events can be attached and executed, in line with the idea of event-oriented programming. The data verification function verifies the validity of the form of data when submitting the form. The operation of the client’s browser: forward, backward, refresh, jump, open a new window, print, etc. Cookies can be created and used.

What is Java?

Java is a programming language introduced by Sun. It is an interpreted language with syntax rules similar to C++. Java is also a cross-platform programming language. The program written in Java language is called “Applet” (small application program). After compiling it into class files by the compiler, it is stored in the WWW page and marked on the HTML file accordingly. As long as the client software of Java is installed, the client can run the “Applet” directly on the network. Java is well suited to enterprise networks and Internet environments and is now one of the most popular and influential programming languages on the Internet. Java has many remarkable advantages, such as simplicity, object-oriented, distributed, interpretability, reliability, security, structural neutrality, portability, high performance, multithreading, and dynamism. Java dispenses with C++ features that do more harm than good and many that are rarely used. Java can run on any microprocessor, and programs developed in Java can be transmitted over the network and run on any client.

Different data types

Java has eight data types: byte, short, int, long, float, double, char, and Boolean, while JavaScript has three data types: number, String, and Boolean.

In addition, there are differences in Java and Javascript variables.

They are positioned differently

Unlike Java, which is a completely object-oriented programming language that requires you to design objects before you can write in Java, JavaScript is an object-oriented scripting language that provides developers with built-in objects, making it easier and less time-consuming.

Link in different ways

Unlike Java, which USES static linking, where object references must be made at compile time and the compiler needs to implement strong type checking, JavaScript USES dynamic linking, where object references can be checked at run time.

Different USES

The most essential difference between them is their usage. At present, Java is widely used in PC terminal, mobile terminal, Internet, data center, and so on, while JavaScript is mainly used to embed text into HTML pages, read and write HTML elements, control cookies, and so on.

Java and JavaScript have different strengths and different specialties. The Java arena is programming, while JavaScript’s heart is in Web pages, where it can do almost anything.

Sourses:

https://www.upwork.com/resources/java-vs-javascript-what-is-the-difference?gclid=Cj0KCQiAwMP9BRCzARIsAPWTJ_G1ymcXEZzbxXRSv4C38P8hTynhLvbfWVea1UEjHNZfbiRwSMScx9kaAgftEALw_wcB

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

Uses, Drawbacks, and Additions to JavaScript in 2020

Photo by cottonbro on Pexels.com

In web development, the development of web applications (software accessed through a web browser) and even game development, JavaScript is used to add interactivity and function to what would otherwise be static webpages, and to create software which runs entirely within users’ web browsers. And while JavaScript is undoubtedly useful in the contexts of web and software development, there are some aspects of the language which I feel are somewhat lacking compared to other programming languages.

For one, compared to its namesake Java, JavaScript is somewhat lacking in terms of its ability to create objects. While objects are a part of JavaScript, creating classes is very nonspecific compared to Java. For example, say I want to create an apple class in Java and in JavaScript, for Java, I would need to create a separate class file:

public class Apple {
   String color;
   public Apple()
      {
       color = "red";
       System.out.println("I am a " + color + " apple!");
      }
}

Whereas with JavaScript, it would look something like this:

class Apple {
  constructor() {
   this.color = "red";
   console.log("I am a " + color + " apple!");
  }
}

While not being strongly typed does have advantages (flexibility of variables, ability to write code which returns a different type depending on context/necessity) I prefer the strong typing of languages such as Java and C#. Strong typing helps to make code more readable, without specifying the type of a variable before using it (ie: var fruit = “apple”;), it can be unclear what a variable is intended for at first glance (especially if there are many similar variables storing similar values). With strong typing, you are always clear on what type of data is meant to be stored inside of a particular variable, (int studentID is clearly only meant to store integer values, while String studentName is only meant to store String values).

JavaScript continues to grow and develop as a language, and new features are constantly being implemented. When reading about some of these new features being added to JavaScript this year, I found a blog post discussing some of the more interesting features which were implemented in 2020. The post served as a good introduction, and offered clear information about each of the new additions discussed.

Private & Static Fields

Something which was absent from JavaScript was the ability to use access modifiers for fields. This year, the ability to use private, or static fields was added to JavaScript; private fields will allow for greater security and the ability to ‘wall off’ access to certain fields, while static fields will allow for the creation of ‘class-scope’ attributes.

BigInt

Another complaint which I have had about JavaScript is the fact that JavaScript only has one number type. While the introduction of the BigInt type does not solve this issue, it does allow for larger numbers to be represented in JavaScript. It functions similarly to the Java ‘Long’ datatype, in that it can store very long number values.

While JavaScript is still missing some features which I enjoy from other languages, these recent additions make it more versatile than ever, and JavaScript continues to be the de-facto language for developing anything interactive on the internet.

Site Referenced: https://www.telerik.com/blogs/latest-features-javascript-ecmascript-2020

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

How does Docker Assist Big Data analyst

 As we dive deeper into the semester we start to learn more tools that will assistance us with open source networks. For this pertrucalr week I looked into how docker will assistance someone in a bigdata constintration like myself. While doing my research I found out that docker allows us to put data or large files into containers. Which will allow us to deliver and respond much quicker to the customer with the use of docker. This is enabled not only the customer but the data scientist to have a more organized platform for information to be transferred. This is valuable because instead of  having to go through multiple platforms to transfer information instead with the use of docker you are able to use one platform to put the infromation into a container which will then transfer it to the client. With the power of docker it allows big data scientist to be self-sufficient and build effectce models which can be tested and modified on multiple occasions with out having to change the main structure of the data. With the use of docker it allows us to have the developer systems and product environment to be constant and be monitored under the same platforms, while prior to docker we where unable to do such a thing because the environments would always switch up and not be uniform. Finaly more systems should incorporate docker into there platforms because it allows us to package the information as applications, dependencies to be deployed as one single package. 

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

Refactoring

https://www.agilealliance.org/glossary/refactoring/#q=~(infinite~false~filters~(postType~(~’page~’post~’aa_book~’aa_event_session~’aa_experience_report~’aa_glossary~’aa_research_paper~’aa_video)~tags~(~’refactoring))~searchTerm~’~sort~false~sortDirection~’asc~page~1)

This week we’ll be covering refactoring which is a very simple but also very important concept to software design similar to models, the topic I covered last week. The reason why I’ve chosen to talk about refactoring is because while it’s a topic that hasn’t been specifically covered in class; I have had experience learning about a form of refactoring in this software process management class I’ve been taking. According to the link above, refactoring is the process of improving the overall structure of a program’s source code. However, this does not mean that the functions of the program are altered in any way. For example, the interface is not improved on, bugs are not fixed, and code isn’t outright rewritten to change the behavior of the program. Refactoring instead cleans up and organizes the source code in order to be more easily readable and understood. An example of this would be simplifying the two lines “answer = 2 * 5;” and “answer = answer * 8;” into the line “answer = 2 * 5 *8”. This change simplifies the code and makes it easier to understand at a brief glance. On a smaller scale, refactoring can be used to remedy code smells and remove duplication. But on a larger scale, refactoring can alter large bodies of code towards different design styles such as object oriented or functional.

The benefits to refactoring do not end at organization and raising code readability. Refactoring also encourages the use of reusable design elements and code modules. These reusable elements and modules highlight the structural similarities and differences in each code module. Refactoring also improves attributes of code that cause easier maintenance like length, duplication, coupling, cohesion, and cyclomatic complexity. Since refactoring often simplifies source code, the length and complexity are also often times lowered which again makes code easier to read. In order to efficiently refactor code, the dependencies (cohesion) and independencies (coupling) of each module will have to be highlighted in the overall structure of the code. And in the case of duplication, it has already been stated that refactoring can remove it from source code. All of these benefits return back to the intended purpose of refactoring, improving the overall structure of a program’s source code by cleaning and organizing it. It’s a form of proofreading and revising code but also comes at the risk of accidentally changing the behavior of a program. So individuals using refactoring should have a good grasp on which part of their code does what in order to avoid that issue.

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

Don’t be Overwhelmed by Refactoring

As I’ve mentioned previously, I taught myself how to code a few years ago. I’ve learned a lot more since then, but I’m always learning. The other day, I had an assignment for another course that involved going back and refactoring old code. Since it was so bad, I’d like to discuss it.

Concept

The code itself is a terminal based Java calculator. I imagine it was really tricky for me at the time considering the way in which I implemented it. I didn’t know about the static keyword nor about how to use methods. This serves as a great example of what not to do:

The Original Code

Now, the code itself is so horrendously bad that I have to get creative to even display it. So here’s a few entertaining lines. Keep in mind the entire program is within the main method:

int load;
double num1, num2, ans;
boolean on, autoclose, autocontinue, loading, numchecking, divide, multiply, add, subtract, other, help;
String in, in2, in3, in4, in5, operation, fa, status1, status2, status3;
char op;

Now, a sane person might ask “Why are there so many variables and why are many of them named so badly?” Well the reason is because I didn’t use methods. I used variables to separate control flow. I also find it funny that I had a String for every user input rather than just reusing one, as well as the fact that I declared all variables at the top for no reason. Here’s an example of that horrible control flow in action:

in = input.next();

if (in.equals("/")) {
	divide = true;
	numchecking = true;
	operation = "divide";
	fa = "by";
	op = '/';
}

else if (in.equals("*")) {
	multiply = true;
	numchecking = true;
	operation = "multiply";
	fa = "by";
	op = '*';
}

I would ask for input, set these variables, and then later on:

if (numchecking) {
	Thread.sleep(1000);
	System.out.println("Enter your first number.");
	num1 = input.nextDouble();
	System.out.println("Enter another number to " + operation + "  " + fa + " " + num1);
	num2 = input.nextDouble();

	if (divide) {
		ans = num1 / num2;
	}
	if (multiply) {
		ans = num1 * num2;
	}
	if (add) {
		ans = num1 + num2;
	}
	if (subtract) {
		ans = num1 - num2;
	}

	Thread.sleep(3000);
	System.out.println("Calculating...");
	Thread.sleep(1000);
	System.out.println(num1 + " " + op + " " + num2 + " = " + ans);

I have no idea why I used if else previously but not here. I can understand I didn’t know how to use a switch statement yet I guess. Anyway, I used Thread.sleep() to add artificial delay for some reason in the program. This code I’ve shown is pretty tame honestly. Notice the line counts. I recommend taking a look at the original source code so you can really appreciate how horrible it is. Unfortunately, I had to convert the .java file to a .docx file to upload it to WordPress:

The Refactoring Process

I find myself fall into the same hole: When I realize I can do something in a better way but it’s large and intimidating, I prefer to start from the beginning rather than modifying the current product. Sometimes, that is extremely useful and you just need a solid clean start. However, often that’s overkill and wastes time. I tend to do that even in video games.

As an example, one of my all time favorite games is Factorio which is an indie game about building factories and trying to automate everything. The goal of the game is to get the game to play itself. Anyway, I have over 500 hours in this game and I haven’t actually reached the end goal of launching a rocket. It’s not because I don’t know how to do it or I die too quickly. It’s because I’m never satisfied with my factory layout or my world generation settings. When it comes to world generation, I do actually have to start over. When it comes to factory layout, I could take the time to manually replace the entire layout and keep my current research. Despite that, I almost always start over.

The saving grace with code is that, when its scale is manageable, it can be incredibly fun and relaxing to refactor. Sometimes it’s tough to get started but once you do, it’s a really fun time. I honestly had less trouble refactoring as I did with the assignment itself. The assignment wanted me to make a change based on a guide. Make the change, write it down, and continue. However, I fell into refactoring and made change after change extremely quickly. With code this bad, it was really easy to just aim at one thing and make 40 changes that all fit into unique categories. So I prioritized refactoring the code well over documenting it well.

Virtually all of those variables I had before are gone. Here is the refactored beginning of the code:

private static final String[] OPERATORS = {"+", "-", "*", "/"};
private static Scanner scanner;
private static boolean autoContinue;
private static boolean autoClose;
private static boolean continueOnce;

public static void main(String[] args) {
    boolean programIsOn = true;

You’ll notice I made use of static variables. I only have one variable in the main method and it controls the loop of the program. Other variables are now in methods or simply don’t exist. I even created an array of operators to allow for easier expansion of functionality later on, despite the fact that I’ll almost certainly never come back to this project. I also have 3 booleans on 3 separate lines. This is my personal preference, but with only 3, I would understand simply writing: private static boolean autoContinue, autoClose, continueOnce; I just tend to lean on keeping things on separate lines. Although now that I’ve written that, I kind-of do prefer that. Although it would mess up the width aesthetic going on because it’s such a wide line.

Before, I showed part of how I took in user input and managed arithmetic operations. I set a bunch of variables and handled it later. Here’s how I manage it now:

private static void handleOperations() {
    String operation = scanner.next();
    System.out.println();

    if(isArithmeticOperator(operation)) {
        arithmeticOperation(operation);
        return;
    }

    switch(operation) {
        case "help":
            help();
            continueOnce = true;
            break;
        case "exit":
            autoClose = true;
            break;
        default:
            System.out.println("Sorry, I don't understand that operation. Try again.");
            continueOnce = true;
    }
}

I created a method to handle it that is called in the main loop. It has good variable names, uses a switch statement, and calls methods that have descriptive names. It could be better but it is leagues better than what it was before. Originally in the refactoring process, I had:

private static boolean doUserRequestedMethod() {
    switch(scanner.next()) {
        case "/":
            divide();
            break;
        case "*":
            multiply();
            break;
        case "+":
            add();
            break;
        case "-":
            subtract();
            break;
        case "help":
            help();
            return true;
        case "exit":
            autoClose = true;
            break;
        default:
            System.out.println("Sorry, I don't understand. Try again.");
            return true;
    }

    return false;
}

It returned a boolean value to allow the loop to continue if it needed to, such as if the user entered an unknown command. I replaced that with global (static) variables to control that. I renamed the method for clarity, and I created a single arithemticOperation() method to avoid code repetition. However, that function itself needed a switch statement, so rather than check the operation twice, I split off the arithmetic operations from the original switch statement in a way that allowed me to add more arithmetic operations in the future. I’m pretty happy with that solution.

Lastly, since I showed how the numbers are calculated originally, I should show that in the refactored version. First I have to check if the input was for an arithmetic operation:

private static boolean isArithmeticOperator(String potentialOperator) {
    for(String operator : OPERATORS) {
        if(potentialOperator.equals(operator))
            return true;
    }

    return false;
}

This was part of why I created the OPERATORS array, so that I could avoid a long boolean of &&s. Then for the actual calculation:

private static void arithmeticOperation(String operator) {
    System.out.println("Enter a number: ");
    double leftOperand = scanner.nextDouble();

    String partialEquation = leftOperand + " " + operator + " ";
    System.out.print(partialEquation);

    double rightOperand = scanner.nextDouble();
    double result = leftOperand;

    switch(operator) {
        case "/":
            result /= rightOperand;
            break;
        case "*":
            result *= rightOperand;
            break;
        case "-":
            result -= rightOperand;
            break;
        case "+":
            result += rightOperand;
            break;
    }

    System.out.println(partialEquation + rightOperand + " = " + result);
}

Again, you’ll find decent variable names and a more clear control flow. Obviously this code isn’t flawless but that’s not the real goal in refactoring. The point of refactoring is to create an improvement. You’ll never have perfect code, but you can always improve your code. This is pretty analogous to life itself. Recognize the value and functionality currently there, recognize that you will never be perfect, but always aim to be better.

Here is the current state of the refactored code. It’s honestly amazing how much better it is:

Conclusion

Refactoring is not something to be feared; it should be enjoyed. There is something very relaxing about it if you enter it with the right mentality. Focus on small things you can easily tackle that would make a big improvement and do that. As you slowly cross off changes you need to make, it’ll become more manageable and more readable. In that program above, I cut the number of lines in half after refactoring. I can actually read it and understand what it’s doing. It should be satisfying to go through and make progress towards simplicity and organization. You just have to want it.

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.

SOLID

A topic that is related to my CS-343 class, is the SOLID principles. SOLID principles are important in the design of object oriented software. They are also similar to the code smells that we have discussed in class as a detection of a code smell could mean one of the SOLID principles are broken and thus could lead to inefficiencies in one’s code; whereas fixing the code smell or SOLID principle with a design pattern/technique can make code more understandable, flexible, and maintainable. For this topic, my source of information comes from the Data Science Blog article, “The SOLID principles: a Guide for Object-Oriented Design”, which will be linked below this post. The post summarizes and explains each individual principle of SOLID, and it provides an example as well as advantages of implementing the principle and also the author’s advice on implementing the said principle.

The reason why I chose this topic was to learn more about common concepts that other programmers followed and are familiar with. Along with trying to familiarize myself with some well-known concepts in the programming world, I also chose to learn more about SOLID principles because it is a topic that I remember being brought up in a previous course that I had taken, which was aimed towards designing cleaner code. Because of this, I became curious and wanted to learn more about SOLID principles as well. From the blog post on SOLID principles, along with learning about each individual principle and implementation from the principles, I had also enjoyed learning a new tool of modeling code, which was the sequence diagram; which the author had to used to model the code example for the Single-Responsibility Principle.

While following the blog post, I also found that the article was a good refresher in tying/connecting to similar material that we have went over in my Software Design and Architecture course. One of the principles, ‘the open-closed principle’, was similar to the simple factory pattern, in that both designs had the pattern of ‘encapsulating what varies’. And the implementation of this principle reminded me of a code smell because the author provides a note to not cover this principle for all of an applications code, but to rather only apply the open-closed principle where it is deemed appropriate; otherwise it would create unnecessary abstraction; this ‘unnecessary abstraction’ segments relates to the code smell, needless complexity. And the fix for this code smell was implementing a decorator pattern fix, which is another subject that has been covered in my Software Design and Architecture course. Overall, I found the article to be a good read to learn more about SOLID principles as well as tying the principles to other programming topics covered in a design pattern course.

Link of source below.

https://www.datascienceblog.net/post/programming/object-oriented-design-solid-principles/

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

The Insatiable Quest for Prime Numbers

I have been coding at least since 2013. I started off self taught and now I’m majoring in CS, while still constantly learning outside of classes. I went from language to language, but something that almost always followed me was the idea of a prime number generator.

I must’ve tried this in almost every language I’ve used. It’s a very simple idea: create a console based program that can both check if an integer is prime, and print out a list of primes in order as quickly as possible. Usually, I don’t get too far for reasons I’ll get into. Although, I did succeed mostly with C++. I had an incredibly quick program (once I realized how terribly slow it was to print out the results to the screen) that ran on multiple threads and could fill up a file with prime numbers. I had two main problems: the file it filled up became so big that notepad wouldn’t be able to open it and the max size of an unsigned long.

Looking back at that code, it was a horrible mess and I’ve come a long way in both C++ and general code design. However, ever since then my quest began to create a data structure from scratch that could allow me to handle enormous primes. I managed to create a class that used strings to hold values. I defined all necessary arithmetic operations and it worked. Incredibly slowly. I should also mention that while I’m constantly coming back to this idea, my attention wanes as I run out of time between vacations.

Using strings was a horrible idea. Not only are they really slow when you try to treat them like numbers, but they are a huge waste of memory. Each character is 1 byte and in base 10 I would only be using 10 values per character. Even using base Z (where I use 0-9 and then a-z and finally A-Z), it would be a very stupid waste of space. So I started thinking about how I could store numbers more efficiently. In C++, it really isn’t that hard.

The solution I came up with involved std::size_t’s (size_t). It’s just a compiler name for the largest possible unsigned integer. Since I have a decent background in number bases (see my blog post on Duodecimal and why we should all switch to it), I was inspired. My design was a linked list structure of size_t’s. I used a linked list rather than an array because I wanted “small” numbers to not take up a lot of space, I wanted to avoid reallocation, and I also wanted to prevent an upper limit for the size. In theory, this object can be as large as memory allows. If I used something like a std::vector, it’s size itself is stored as a size_t.

Each size_t is the largest possible integer in C++. And each node in the linked list acts like a digit of a base. Let n be the largest size_t number. Suppose you have n + 1. That number would basically just be 1<—>0 in this form. Then you keep ticking up the 1’s digit, etc. This means that the numbers are stored incredibly densely. We’re dealing with base (n+1). In my case, I think n is 64 bits. So n=264 – 1. Anyway, to store n2 , you would need 2 nodes. To store nk you only need 64*k bits.

This is insanely better than using strings. Since they’re integers already as well, I get to avoid conversion. My problem recently has been finding the time and motivation to work on this. I try to create unit tests so I can guarantee it’s working as expected and I get bored. I also need to find efficient algorithms for arithmetic operations.

Despite my inability to complete this project, it does a good job of showing the benefits of Object Oriented Programming. I can take all of this complexity and shove it into a class. Once that class is done, I can create the functions to simply calculate primes the normal way.

Checking Primality

The most basic way to check if an integer is prime is to check if any positive integers less than it (other than 1) divide it. From there, you might realize that you can skip all of the even numbers after 2 because if 2 doesn’t divide it, then neither will any of the evens. Then you can also skip all integers larger than it’s square root as factors come in pairs. A few proofs would easily show these results to be true. Then you can continue to progress downwards. However, I’ve come up with a method as well.

How come after you check 2 you can skip all of the even numbers? Okay I suppose I should do one simple proof here:

In fact, let me do this in general:

I enjoy a nice simple proof every now and then, even though I could’ve just cited transitivity of divides. Anyway, what this is telling us is that this applies for any factors. Any time an integer does not divide our potential prime, we can ignore all multiples.

What I’m getting at is that the hypothetically most efficient method for verifying primality is to check all primes up to it’s square root. Since every number is either prime or the multiple of primes, checking a prime also checks every single multiple of that prime. The problem is that you need a list of primes to check. Hence, my program would store primes and use them to verify if a number is a prime.

You may be thinking that if I have a list of primes, why bother at all with arithmetic. And thinking about it, having an “exhaustive” list of primes (an exhaustive infinite list…) and simply checking that list could be very efficient to verify a number is prime. However it would be pretty inefficient to verify that the average number is not prime. The reason I’m not using that method is because my list of primes is small and slowly grows. I only need to store primes up to the square root recall. That means to check 100, I’ll only have 2,3,5, and 7 stored. To check 10,000, I’ll only have all 2 digit primes.

So as I verify primes the list would grow and add more factors in order. You would also want to check the smaller primes first. While you can’t exactly say that more integers are even than are multiples of 5 due to the set being infinite, any complete finite subset of consecutive integers has this property. Multiples of 2 will make up half of the elements, multiples of 3 one third, etc. So you’ll want to start with the smaller primes first.

How to determine divisibility is also up to you. For instance, in base 10 we can rule out any integer who’s first digit is a 0 or 5 (except the number 5 itself) since that rules out multiples of 5 and 10. However, when working with duodecimal, I realized different number bases have different properties for divisibility. For example, in base 12 every multiple of 4 and 8 ends in 0,4, or 8. Every multiple of 3 and 9 ends in 0,3,6, or 9. Every multiple of 6 ends in 0 or 6. Every multiple of 12 ends in 0.

You could potentially have an algorithm to convert the integer to a different number base that is more efficient than performing an arithmetic calculation. Especially considering that for these tricks, you only need to convert the first few digits of the number. I think it’s a really interesting idea, however you risk circumventing the benefits of the machine code. Often times you try to make something more efficient, and then it’s either unnecessary or makes performance worse because the compiler was able to do a better job “fixing” your code. I think either way I’ll have to experiment with these idea in the future. Thinking about it, you only need to convert the number to the base of the prime and then check if the 1s digit is 0. You can then modify how many digits you actually convert based on how many digits the base-prime number will be. For larger numbers this might have potential.

Conclusion

While this project may not be the best example, I think it’s very useful for programmers to have a “go to” project for practicing an unfamiliar language. Something simple enough to allow you to write it from memory, while complex enough to give you a good grasp of the language. In this primes project, I have to handle the terminal, arithmetic, functions, objects, files, threads, etc. If I simplified it down and ignored my ambitions, it would server as a very functional example to allow you to learn the syntax and libraries of a new language. Ideally, you wouldn’t even have the original code to look at. You would just program the functionality from memory using your IDE and Google to figure out syntax. The best way to learn a language is to use it. If you have something familiar in your mind, then you have a great example project to work on already. I find struggling to implement functionality and spending a lot of time searching for a solution has taught me an invaluable amount about the languages I use.

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.

What is a REST API?

This week we began to discuss REST APIs. While it was explained in class, the concept kind of went over my head so I wanted to look more into what they are. While looking around I found a helpful article from sitepoint.com

The author explains it with an analogy. A REST API is a way for two systems to communicate over HTTP. This is like when you get car insurance. The insurance agency must get data from the government, credit agencies, banks and other systems.

He goes on to give an example of a REST API that just shows a bad joke.

He also talks about the other data communication standards like CORPA and SOAP. They are much stricter than REST which is not a standard but a set of constraints that must be satisfied for an API to be RESTful.

The next section discussed was something we covered in class, requests and responses. He also includes an example for the reader to try at home.

REST APIs also have some challenges associated with them. One is that there are multiple endpoints that can be used to fetch the same data like:

  • /user/123
  • /user/id/123
  • /user/?id=123

This can make is hard to be consistent on a large project with many developers.

It is also important to keep your application secure and a REST API provides another level that needs to be secured.

The author ends with additional articles and links to learn more about REST APIs.

A lot of what this article covered was also covered in class, specifically the part about requests and responses. I feel like what we discussed in class was clearer and more made more sense. This is probably because we were talking about it and could ask questions if necessary.

What was useful from this article was the REST API example. I did try the example myself and it worked with no issues, though this is to be expected as it was just copying and pasting the code. I would have liked if there were more explanation, but this was a simple example so not much more could be said.

The author here assumes that the reader is familiar with JavaScript. I am new to JavaScript, but this example was simple enough that I could understand what was going on. I don’t anticipate us doing an example this simple in class, but it was helpful, nonetheless.

https://www.sitepoint.com/developers-rest-api/

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

JavaScript/Node.js

This week on my CS Journey, I want to look more into JavaScript and how it is used in docker. Although we did a few activities on JavaScript, I was still confused so I decided to read and research more into it. JavaScript is a text-based programming language used both on the client-side and server-side which is mainly for the web. Many of the websites use JavaScript on all browsers making JavaScript the most-deployed programming language in history. The name JavaScript is quote misleading due to the resemblance of java programming language however, JavaScript is completely different from the Java programming language. Both Java and JavaScript are written, assembled and executed differently, and each has dramatic differences when it comes to what it can do. JavaScript is mainly used for: Adding interactive behavior to web pages like Change the color of a button when the mouse hovers over it, displaying animations, creating web and mobile apps, Game development, and  building web servers.

Now let’s get into Node.js which is what is used in docker. Over the decade Node.js has enabled JavaScript programming outside of web browsers, which has a dramatic success of Node means that JavaScript is now also the most-used programming language among software developers. Node.js is an open-source, cross-platform runtime environment for developing server-side and networking applications. Node.js applications are written in JavaScript and can be run within the Node.js runtime or any other operating systems. some of the features I learned from the blog is that, Node.js  can be  Asynchronous and Event-Driven meaning that All APIs of the Node.js library are asynchronous, it essentially means a Node.js based server never waits for an API to return data. It can be very fast since it is being built on the Google Chrome’s V8 JavaScript Engine, Node.js library is very fast in code execution, and lastly, No Buffering- Node.js applications never buffer any data. These applications simply output the data in chunks. 

The diagram below also helped to understand the concept well.

I highly recommend that everyone read the assigned book on JavaScript because it is very helpful in terms of understanding the concepts and the book covers a wide variety of interesting topics. Also, I suggest that everyone follow this tutorial it is an example that shows how to get a Node.js application into a Docker container. The guide also helps to understand basics of how a Node.js application is structured.

Here is the tutorial: https://www.digitalocean.com/community/tutorials/how-to-build-a-node-js-application-with-docker-quickstart

Sources : https://learning.oreilly.com/library/view/javascript-the-definitive/9781491952016/ch16.html

https://www.tutorialspoint.com/nodejs/nodejs_introduction.htm

From the blog Derin&#039;s CS Journey by and used with permission of the author. All other rights reserved by the author.

RESTful API Basics

            As we start our learning for our final project in our class, we have started to learn about and work with RESTful API architecture style (REST API), so I have started some research and done further learning myself. I found a great article from by Margaret Rouse with an wide view of the application program interface, called RESTful API. She breaks down what it is, how it works, its uses, its constraints, challenges, and some background information. REST uses the HTTP requests of GET, PUT, POST, and DELETE for data use and access. This API is based on representational state transfer, which is what the acronym stands for. It works by, “[Breaking] down a transaction to create a series of small modules. Each module addresses an underlying part of the transaction.” Commands are used to obtain resources, and resource’s states is called a resource representation. As previously mentioned, the commands are: GET to retrieve a resource, PUT to modify/updated a resource, POST to create a resource, and DELETE to remove a resource. The idea is for users to access networked components with stateless calls, no information being retained by the REST services. This statelessness makes REST “useful in cloud applications.” They are scalable and can be “redeployed if something fails.” It is very useful for efficient internet usage and is very compatible for distributed environments, and is used by the likes of Amazon, Google, LinkedIn, and Twitter. With cloud and microservices growing in popularity and usage, REST is sure to grow alongside. REST adheres strictly to 6 key concepts. There must be a uniform interface under a single URL. It must be client-server based, dividing request-gathering concerns on the client and data access, workload management, and security on the server. There must be stateless operations, as mentioned previously. Any state information must be managed on the client. Caching is essential for resources unless “explicitly indicated that caching is not possible. It must be a layered system, like a hierarchy to the architecture. There must be code on demand, meaning that “a server will send back static representations of resources,” or “when necessary, servers can send executable code to the client.” Sticking to these requirements can be difficult, which presents the challenges of endpoint consistency, response time and data size, defining paths and locations, security, authentication, request scope, testing, and error handling. Since REST is useful for the aforementioned reasons, this is worthwhile and understandable though. I expect to use this information in my final project, which should be dealing in a REST API, so this will be very useful to me in the near future. It is very interesting and exciting, and is growing to the top of the computer science world.

Source: https://searchapparchitecture.techtarget.com/definition/RESTful-API

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