Understanding Angular with Tetris

For this week’s post I read through Michael Karén’s article, “Game Development: Tetris in Angular.” As the name suggests, this article demonstrates how to make a Tetris game in Angular. This is a great example project that shows many of Angular’s functionalities without being too complex. It covers topics introduced in CS 343: components and templates, and other topics like styles and event listeners. The author’s project code can be viewed on GitHub for further examination.

The project contains three components (with @Component
decorator): app, board, and piece. The app component is the main component that
uses the board component as a template. The board component handles the board
UI and injects the game logic from GameService. And lastly, the piece component
handles the UI and properties of the Tetris pieces.

Templates are used in two ways in Karén’s game. The app-root
which uses another component as its template by using the custom tag
<game-board></game-board>. The game-board uses a URL as a template,
which is defined in the board component’s HTML file. This HTML file defines how
both game-board and, by extension, app-root are rendered on the page.

The injectable class (with @Injectable decorator)
game.service contains much of the game logic. As an injectable, game.service’s
methods are accessible to board.component when game.service is injected in
board.component, located at the example code’s line 72 with “constructor(private
service: GameService) {}.” This is useful as it is cleaner to separate the responsibility
of the game logic and the UI logic from each other.

The styles are defined in a Cascading Style Sheet or CSS file.
The CSS file is used to define how some of the HTML elements are designed. CSS makes
HTML design simpler with its more intuitive interface.

I learned a new decorator from this article, @HostListener.
This decorator can be used to define the program’s response to user
interaction. In this article’s project uses @HostListener to define how the game
board responds to the specified keystrokes.

The JSON methods stringify and parse were also new to me. JSON.stringify will convert an object into a string. JSON.parse on the other hand, converts a string into a JSON object.

Reading through this article and examining the project’s
code has helped my understanding of Angular and HTML tremendously. I recommend Michael
Karén’s article, “Game Development: Tetris in Angular,” to those who are
looking for a fun example of an Angular program.  Being able to see all the parts of the
program and how they work together has made Angular more accessible for me and
has provided an excellent resource for possible projects in the future.

Article referenced:
https://blog.angularindepth.com/game-development-tetris-in-angular-64ef96ce56f7

From the blog CS@Worcester – D’s Comp Sci Blog by dlivengood and used with permission of the author. All other rights reserved by the author.

Angular Components

This past week, I began to work with REST API frontend code
using the Angular framework in CS-343. The introductory class activity taught
the basics about setting up and working with an Angular project as well as some
useful properties of Angular (such as *ngIf) that I definitely see myself using
in the future. However, the activity did not go into much detail about how to
create and manipulate Angular components to create more interesting UIs. While
researching Angular on my own, I came across a blog post from Angular
University titled “Angular Components – The Fundamentals.”

The blog can be found here:

https://blog.angular-university.io/introduction-to-angular-2-fundamentals-of-components-events-properties-and-actions/

As someone who has enjoyed creating UIs in Java using Swing
components, this blog immediately caught my attention. I expected it to help me
create UIs for server-based applications that would be more interesting than
the basic layout I worked with in class. However, while this blog did not go
into too much detail on the creation of UIs, it has certainly helped me to
better understand the fundamental properties of Angular components. The information
I learned from this blog will undoubtedly be useful as I begin to work more
in-depth with Angular components in my final project for CS-343. I decided to
share this blog because I think that others who are new to Angular will also find
it to be a useful introduction to Angular components.

The blog starts by providing a basic introduction to Angular components, as well as browser components in general, using short example code. It then discusses in detail the two main aspects of an angular component, properties and events, and explains when to use them and when to avoid using them. I think the blog did a great job explaining properties and events in simple terms and clearly stating when not to use them. I especially liked how the blog links properties and events to input and output, respectively. This association helped me understand when to make use of properties and events in Angular projects, since I already have experience working with input and output of components in Java. I also think the example code in this blog is simple enough that it can easily be referenced while working on other projects. I certainly see myself referring back to these examples as I start working with Angular components on my own to help myself understand the correct syntax for implementing properties and events. Finally, this blog has demonstrated to me how to create familiar components, such as a scrollable list, and it has taught me how to change aspects of components, such as their color. The information in this blog has helped me understand the fundamentals of Angular components and how to work with them in applications. I will certainly be referring back to this post as I begin to work on my final project this week, as it is a great resource to help new Angular developers to understand Angular components.

From the blog CS@Worcester – Computer Science with Kyle Q by kylequad and used with permission of the author. All other rights reserved by the author.

Testing Doubles

When testing a system, known as the System Under Test or SUT,
the system needs to have access to its dependencies but often the access given
is just clever mimicry. Testing doubles are used to replace a system’s dependencies
with varied functionality. The article “Test Doubles — Fakes, Mocks and Stubs,”
by Michal Lipski, explains three out of five of the types of testing doubles defined
by Gerard Meszaros, fakes, stubs, and mocks. The author provides diagrams and
code examples with explanations for the testing doubles.

The first testing double described in the article are fakes.
The article provides the example of a SUT that depends on a Data Access Object
or DAO. In this case, a fake is used to replace the DAO so that the SUT can be
tested without the need of using a real database.

Stubs are the next testing double type discussed in the
article. Stubs are the simplest testing double type as they only provide canned
responses. These responses are predetermined and are used in place of actual
data.

The last type in the article are mocks. Mocks are used for Behavioral
Testing. Mocks allow for testers to be able to verify the system is behaving
correctly, correct methods called at correct times. A simple case for a mock is
when a SUT depends on a method that does not return anything that can be
verified. The mock object will record when its methods are used, so that the
behavior can be checked.

I found the example diagrams in “Test Doubles — Fakes, Mocks
and Stubs,” by Michal Lipski, very helpful in understanding the differences of
the testing doubles. While this article does not go over two types of testing
doubles, dummies and spies, the three types that are discussed are described well.
Ultimately, when testing a system, it is imperative that the system can test
all its behaviors without relying on actual data.

From the blog CS@Worcester – D’s Comp Sci Blog by dlivengood and used with permission of the author. All other rights reserved by the author.

FPL&S 1: Getting to Know Angular

For my final project in my software construction and architecture class, I will be writing a 5-post series for Final Project Learning and Status (FPL&S). This project will be using Angular, Typescript, and Node Package Manager (npm). I am not familiar with these tools, but I have learned my lesson before that one should fully understand the technologies they’re using before they start a project. I have spent about 10 hours this week tinkering with Angular, reading blogs, watching tutorials, and of course referencing Angular documentation, with the goal of understanding the architecture as a whole.

My first question: why did I have to download Node.js? The answer boils down to requiring npm, which is packaged with Node.js. Npm allows users to share packages, and Angular requires quite a few packages to run. Npm takes care of this. Of course, it also installed Angular itself.

I was also confused about which files were doing what in a pre-configured project, but after playing with the code and making modifications, this started becoming second-nature, so I won’t go into detail on that. However, learning the concepts behind each file was much more important.

Traversy Media released an Angular Crash Course video which I found to be quite comprehensive and helpful in understanding the framework as a whole. Many of these concepts were learned in practice, but it is nice to be explicitly told some things to remove doubt. The video described how UI “Components” are used and built. Particularly useful were the descriptions of using a constructor to import services that will be used, and that selector was defining the tag to be used in HTML.

Modules, called NgModules, are another important concept, central to Angular. In a single-page web app you might only have a single NgModule, but in larger systems they help improve the modularity of an application, just as modules in Java or other languages. A single NgModule, however, can have many Components. Components can also be reused and nested, but should be considered a view, the goal of which is to create a user experience.

My final project will tie in with my independent study Android app next semester. My first idea was to implement audio recording that will also be necessary for my mobile app, but this turned into a much bigger challenge than expected. Due to the nature of my mobile app, I feel it will be better to start with a web front-end that can pull from data already stored in a cloud database, in order to display metrics, charts and a summary of results. Learning about Angular Observables will likely help to perform asynchronous uploading.

I’ve learned much more than what I’ve written up here, but this blog post addresses what I feel was most relevant to my project and learning Angular. Since this blog is documenting learning experiences, I welcome comments, corrections, and suggestions if anyone thinks it will help.

From the blog CS@Worcester – Inquiries and Queries by ausausdauer and used with permission of the author. All other rights reserved by the author.

Part 2: Setting up your first Angular 8 project

Did you do that Angular tut I provided in my last post? Pretty easy to get up and running. I did the whole Tour of Heroes tutorial over the summer so I could have a solid understanding of where I was at with it. It’s flexible and somewhat intuitive. Ready to kick your Angular skills up a notch? Let’s create a component that does an API call that returns a list of all employee’s. We’ll code this against a working online example that’s hosted at dummy.restapiexample.com I’m making a couple of assumptions here. First that you actually did the earlier tutorial and second that you understand how API’s work and lastly that you have an Angular site you are currently working on. If you’re not sure about Rest API’s read this article on Sitepoint then jump back in. Ok if you’re working with a very basic Angular site let’s open it in your favorite IDE. I like using Webstorm as it has some neat built ins. In Webstorm I’ll click in the lower toolbar and launch a terminal session in the root of my project folder. To create the new component I’ll type in: ng g component getAllEmployees Since you’re here go ahead and create an employee class: ng g class employee This will create a new Angular component named get-all-employees and will also create an employee class file in the root of your project. If you check out your projects file structure you’ll see a new folder named get-all-employees in the app folder. Browse that new folder and you’ll see that Angular created the .css .html .spce.ts and component.ts for your new component. Now let’s get to the fun part, the coding. Open the employee.ts in the root folder and modify it like this: export class Employee { id: number; employee_name: string; employee_salary: number; employee_age: number; constructor(id: number, employee_name: string, employee_salary: number, employee_age: number) { this.id = id; this.employee_name = employee_name; this.employee_salary = employee_salary; this.employee_age = employee_age; } } Ignore my formatting please as my blog interface makes it wonky. By using an Employee class we can import the JSON response objects into an array of employee objects. Save the employee.ts and open up the get-all-employees.component.ts we’ll modify this to use the employee.ts and create the methods to pass the GET request to pull in all the employees: import { Component, OnInit } from ‘@angular/core’; import {Employee} from ‘../employee’; import {HttpClient, HttpErrorResponse} from ‘@angular/common/http’; @Component({ selector: ‘app-get-all-employees’, templateUrl: ‘./get-all-employees.component.html’, styleUrls: [‘./get-all-employees.component.css’] }) export class GetAllEmployeesComponent implements OnInit { employees: Employee[] = [Object]; error: HttpErrorResponse = null; constructor(private http: HttpClient) { } ngOnInit() { } getAllEmployees(): void { this.error = null; this.http.get(‘http://dummy.restapiexample.com/api/v1/employees’ ) .subscribe(response => { this.employees = response; console.log(response); }); } } Let’s break down what we are doing here. The imports should be self-explanatory but just in case… The (Component, OnInit) are Angular core components technically since we aren’t using the ngOnInit method we really don’t need it and could remove it from this component. We import Employee so we can create an array of Employee objects. The HttpClient and HttpErrorResponse are imported because we are going to be making an http call and may have to handle an error response. The @Component section defines the get-all-employees component. Now lets look at the class, we create the empty employees array of object type Employee. We set a HttpErrorResponse named error to null and we call our constructor to create a private http client. The getAllEmployees method is the where the magic happens. It takes the JSON response and maps each entry as an Employee object in the employees array. Ok next week we will finish this up by modifying app.modules.ts, get-all-customers.component.html, app.component.html and app.component.ts Until then – Happy Coding! #CS@Worcester #CS343

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

Part 2: Setting up your first Angular 8 project

Did you do that Angular tut I provided in my last post? Pretty easy to get up and running. I did the whole Tour of Heroes tutorial over the summer so I could have a solid understanding of where I was at with it. It’s flexible and somewhat intuitive. Ready to kick your Angular skills up a notch? Let’s create a component that does an API call that returns a list of all employee’s. We’ll code this against a working online example that’s hosted at dummy.restapiexample.com I’m making a couple of assumptions here. First that you actually did the earlier tutorial and second that you understand how API’s work and lastly that you have an Angular site you are currently working on. If you’re not sure about Rest API’s read this article on Sitepoint then jump back in. Ok if you’re working with a very basic Angular site let’s open it in your favorite IDE. I like using Webstorm as it has some neat built ins. In Webstorm I’ll click in the lower toolbar and launch a terminal session in the root of my project folder. To create the new component I’ll type in: ng g component getAllEmployees Since you’re here go ahead and create an employee class: ng g class employee This will create a new Angular component named get-all-employees and will also create an employee class file in the root of your project. If you check out your projects file structure you’ll see a new folder named get-all-employees in the app folder. Browse that new folder and you’ll see that Angular created the .css .html .spce.ts and component.ts for your new component. Now let’s get to the fun part, the coding. Open the employee.ts in the root folder and modify it like this: export class Employee { id: number; employee_name: string; employee_salary: number; employee_age: number; constructor(id: number, employee_name: string, employee_salary: number, employee_age: number) { this.id = id; this.employee_name = employee_name; this.employee_salary = employee_salary; this.employee_age = employee_age; } } Ignore my formatting please as my blog interface makes it wonky. By using an Employee class we can import the JSON response objects into an array of employee objects. Save the employee.ts and open up the get-all-employees.component.ts we’ll modify this to use the employee.ts and create the methods to pass the GET request to pull in all the employees: import { Component, OnInit } from ‘@angular/core’; import {Employee} from ‘../employee’; import {HttpClient, HttpErrorResponse} from ‘@angular/common/http’; @Component({ selector: ‘app-get-all-employees’, templateUrl: ‘./get-all-employees.component.html’, styleUrls: [‘./get-all-employees.component.css’] }) export class GetAllEmployeesComponent implements OnInit { employees: Employee[] = [Object]; error: HttpErrorResponse = null; constructor(private http: HttpClient) { } ngOnInit() { } getAllEmployees(): void { this.error = null; this.http.get(‘http://dummy.restapiexample.com/api/v1/employees’ ) .subscribe(response => { this.employees = response; console.log(response); }); } } Let’s break down what we are doing here. The imports should be self-explanatory but just in case… The (Component, OnInit) are Angular core components technically since we aren’t using the ngOnInit method we really don’t need it and could remove it from this component. We import Employee so we can create an array of Employee objects. The HttpClient and HttpErrorResponse are imported because we are going to be making an http call and may have to handle an error response. The @Component section defines the get-all-employees component. Now lets look at the class, we create the empty employees array of object type Employee. We set a HttpErrorResponse named error to null and we call our constructor to create a private http client. The getAllEmployees method is the where the magic happens. It takes the JSON response and maps each entry as an Employee object in the employees array. Ok next week we will finish this up by modifying app.modules.ts, get-all-customers.component.html, app.component.html and app.component.ts Until then – Happy Coding! #CS@Worcester #CS343

From the blog Home | Michael Duquette by Michael Duquette and used with permission of the author. All other rights reserved by the author.

Mockito: Complicated at First Glance, Simple in Concept

Mockito is a mocking framework. In his article Mocks aren’t Stubs, Martin Fowler mentions that Mocks allow for behavior verification, rather than state verification, which verifies values after method calls to confirm the proper behavior occurred. Behavior verification instead makes sure the proper behavior happened, by confirming the proper methods themselves were called.

So mocking is a means of setting expectations of method calls on a mock object, and then verifying that those method calls actually happen. But how does this apply to Mockito?

Mockito is a bit more comprehensive. It has mocks, stubs and spies. It has a lot of methods, and a few different philosophies on how it should be used. Should everything be mocked except the system under test? Should you mock types that you didn’t create? When is partial mocking ok? These are questions that are not simply answered and will likely have answers that evolve over time. But the takeaway is that there is a lot to Mockito.

The best way to learn how Mockito can be used is to look at examples. Mockito’s documentation is a good resource and describes many of the concepts. However, the examples are a bit simple and isolated. A Vogella tutorial on Mockito has many better examples that shows how you can use Mockito in actual production code.

Complicated behavior is where mocking comes in handy. Stubs are great for making sure simple methods are called within objects. But in complicated systems, there is a lot more going on that may affect the behavior of the object under test. A mock object can trick external classes into believing that the Mock object is doing real work, by providing expected return values when a method is called. Furthermore, you cannot always check the state of an object without modifying the class itself, making behavior verification the only means of testing.

Mockito is commonly used in Android mobile app testing, especially when Android was officially using Java. In a mobile environment, you are building an app on top of a complicated framework, and as such you may encounter problems, or at least complications, when trying to test. A common example is the Context object in Android. It provides necessary information about the environment in which code is being run. Android Fragments and Activities might need this context internally, but the behavior of the Fragments and Activities should not depend on the actual Context object. Another issue arises: how do you set up application context in a test environment? With Mockito, these complications are resolved by simply creating a Mock Context object in the test cases. If you rely on return values within a mock object, you can even tell Mockito what it needs to return when methods are called.

Mockito can be used in combination with other test methods, using as many or as few of its features as desired. Mocking is quite possibly a necessity when testing complicated systems, and at the very least powerful and convenient.

From the blog CS@Worcester – Inquiries and Queries by ausausdauer and used with permission of the author. All other rights reserved by the author.

A Different Type of Angles

I decided to learn more about angular since it peaked my interest in class and in general. in my search for more information on Angular, I found “Introduction to AngularJS” by GeeksForGeeks. This post explains the strengths and important things to know about Angular and some of the key features of Angular. some key points from the post are that its easy to use and requires little understanding of different coding languages like HTML, JavaScript, and CSS. Angular saves time as well and avoids unnecessary code. Angular is a powerful framework that allows the developer more control over their applications and web resources. Angular is also unit test ready which helps the developer even more in there processes of creating applications and resources. Angular has Data Binding which means that the developer does not need to continuously update the HTML file or create a special code to bind the data. This keeps data consistent and updated with the most recent version of an application or resource that the developer provides.
Angular seems to make web development easier than ever and gives people the templates and tools needed to create powerful and intuitive applications to suit their own needs. From my short experience with angular, i felt confident and powerful while using the framework and wasted less time than expected had i tried to create a web application without it. I felt in control and could see the real time changes that were occurring in my local website due to the changes I was making. Angular has been for sometime one of the three major frameworks for web developers and the other two are React and Vue. I’m unsure about the other too languages are better or worse or have advantages over Angular, but at this point in time Angular seems like a strong and good choice for my future with any type of web development. the one thing that i think makes angular so appealing to me and others is that the data is bonded and you don’t need to constantly change things to reflect one change in a web application or resource. This framework is something i could see myself using in the future or something like it for web development because it simplifies a larger more difficult job and allows people with enough information to traverse its power and harness that power to create powerful applications. I can’t wait to learn even more about Angular and how to use it effectively.
link to article referenced: https://www.geeksforgeeks.org/introduction-to-angularjs/

From the blog CS@Worcester – Tyler Quist’s CS Blog by Tyler Quist and used with permission of the author. All other rights reserved by the author.

Seeing Doubles

In Computer testing there exist many ways to automate test and create ways to use objects that behave in a similar way to what they are supposed to be. In the blog post by Michal Lipski titled “Test Doubles — Fakes, Mocks and Stubs.”, he goes through the different doubles testing forms and explains their strengths and weaknesses and even shows diagrams and examples of code to help people better understand what each one of them is. Fakes being a working implementation that takes shortcuts and are different from the actual version. Stubs hold data given to the object via the tester to check if that data is being returned at the right time and calls. Mocks just write down the calls they receive and allow the tester to know that the actions were completed, but not if they were completed correctly. these forms of testing allow the tester to create version that satisfy conditions that they wish to check and understand.
I personally really enjoy the simplicity of these testing methods and how they don’t require much time or effort to be completed. while stubs are one of the simplest, in my opinion, they take a good amount of time and are thrown away later which makes them a hassle and a waste. Fakes seem to be a great choice for prototyping different things and allowing the tester to do as they please without any fear of damaging or changing any actual data. all together these testing methods are useful and will help me in my future in the computer science field.
link to the article referenced: https://blog.pragmatists.com/test-doubles-fakes-mocks-and-stubs-1a7491dfa3da

From the blog CS@Worcester – Tyler Quist’s CS Blog by Tyler Quist and used with permission of the author. All other rights reserved by the author.

The Single Responsibility Principle

Several weeks ago, we briefly discussed the SOLID design
principles in CS-343. This discussion was supposed to lead into a homework
assignment where we would research a couple of principles, but since this never
happened I decided to research a SOLID principle for a blog post instead. In
this post, I will be focusing on the Single Responsibility Principle, or SRP
(the ‘S’ in SOLID). This principle declares that a class should have only one
reason to change, or in other words, a single responsibility. It sounds like a
simple concept, but actually implementing it can be challenging. My research
into the SRP helped me come across a blog post by Patrick Smacchia titled “SOLID
Design: The Single Responsibility Principle (SRP),” which defines guidelines
that may help make the principle easier to follow.

The blog can be found here:

In the blog, Smacchia explains that the SRP is not as simple
to follow as it sounds, because different programmers may define a responsibility
or a reason to change in different ways. For this reason, he approaches
the principle based on its fundamental purpose of determining which logic
should be in which class. From this approach, he explains several aspects of
the SRP using example code, and he provides a set of concrete guidelines that
can help enforce the principle. I chose to share this post because Smacchia’s
approach to explaining the SRP has helped me understand it better by getting me
to think about it from a more fundamental perspective. I also think his
guidelines would be useful to any programmers, myself included, who intend on
following this principle in their projects.

I certainly intend on referring back to the guidelines
included in this blog to ensure that my future projects follow the SRP. Although
there are a couple I don’t fully understand, such as the one on POCO classes, I
think the others will greatly help me adhere to the SRP. His suggestion to keep
logic related to different functions separated into different classes makes
sense thanks to his Employee example, which I will refer back to when deciding
which functions should be separated into different classes. I found Smaccia’s
discussion on cohesion especially interesting because it exposed me to the Lack
of Cohesion Of Methods metric, or LCOM, which is used to actually quantify how
cohesive a class is. It surprised me that a more complex class can have a lower
LCOM score than a simpler one, and that a class’ simplicity does not represent
its adherence to the SRP. I will definitely refer back to this blog to help me
ensure that my own classes keep a low LCOM score even as they grown more
complex as a way to follow the SRP. I have certainly had issues with classes
getting too large and doing too many things in the past, and I think learning
more about the SRP from this blog will help me avoid this problem in the future.

From the blog CS@Worcester – Computer Science with Kyle Q by kylequad and used with permission of the author. All other rights reserved by the author.