Author Archives: jsimolaris

C o d e C o v e r a g e T e s t i n g

Cover your tests

Welcome back, I am going to explain why you should be running most of your tests with some sort of code coverage. Code coverage is a software testing metric that analyzes how effective your tests are when ran with your code. Code coverage enables you to see the degree to which your code has been implemented. It also helps you to determine how successful unit tests are by checking the degree to which your code is covered by them. Code coverage percent is calculated by items tested by dividing elements tested by elements by elements found.

Code coverage enables you to improve the efficacy of your code by having a statistical analysis of code coverage. The test cases your currently running without code coverage may be less effective than you realize. Running with code coverage allows you to identify parts of your software that have not been examined by your test cases. This not only makes better code but it saves time because it gives you a clearer picture of where you need to refactor.

Code coverage enables you to identify parts of the software that are not implemented by a set of test cases.

How is code coverage calculated?

Well, that depends on what tools you’re using. However the common tools combine some of the following types:

  • Line coverage: percent of lines tested
  • Functions coverage: percent of functions called
  • Conditions coverage: percent of boolean expressions covered
  • Branch coverage: percent of branches executed

Are all code coverage types created equal?

When I first learned about code coverage, I assumed that line coverage must be superior, because hitting every line must be most important and probably will include most methods. While this is important it will miss out on a few things. Consider the following code from a stackoverflow answer:

public int getNameLength(boolean isCoolUser) {
    User user = null;
    if (isCoolUser) {
        user = new John(); 
    }
    return user.getName().length(); 
}

When you call this method with the boolean variable isCoolUser set to true, you will have your line coverage come back 100%. However, this method has two paths;

  1. boolean is true
  2. boolean is false.

If the boolean is true, all lines are executed, and code coverage will return 100%. What we don’t see with line coverage is that if you call this method with the boolean set to false, you will get a null pointer. Line coverage wouldn’t show you this bug, whilst branch coverage would. For these reasons, best practice is to use a coverage tool that examines multiple types of code coverage

You’ve convinced me, so how do I start?

Code coverage comes built into most IDE’s. In intellij, when you open the run drop-down menu, its two buttons below, “Run with Coverage”. I have found this tool incredibly useful/invaluable in my coding. Since learning of it, I have not run tests without using coverage. There have been a few instances where I created test classes that passed but I wasn’t aware just how terrible they could be. Using code coverage has made me learn more and see my mistakes much more easily. Lines I thought were testing the code, I could comment out and see if it reduces code coverage and learn from that. In Intelli-j’s code coverage, lines that have been executed are green while lines that aren’t are red.

Other code coverage tools are listed below:

SonarQube

JaCoCo

Clover

Selenium

Carina

Cucumber

Good coverage can’t fix bad test writing practices.

If your tests aren’t comprehensive, covering multiple possibilities, coverage won’t save you.

Thanks for taking the time to stop by and read my blog.

I learned quite a bit of information from the following links:

https://ardalis.com/which-is-more-important-line-coverage-or-branch-coverage/

https://stackoverflow.com/questions/8229236/differences-between-line-and-branch-coverage/8229711#8229711

https://www.softwaretestinghelp.com/code-coverage-tutorial/#Methodologies

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

Don’t Talk to Strangers

The Law of Demeter was proposed by Ian Holland in 1987. During the development of a system called Demeter using oriented object programming, Holland and his colleagues realized that the code that fulfilled a series of rules was less coupled. Although it is called The Law of Demeter, it is not really a law, but more of a guideline to help reduce coupling between components. When applying LoD to object orientated design, there is a set of four rules that formalizes the “Tell Don’t Ask” principle;

You may call methods of objects that are:
1. Passed as arguments
2. Created locally
3. Instance variables
4. Globals

A great example of this is:

    class User {
        Account account;
        ...
        double discountedPlanPrice(String discountCode) {
            Coupon coupon = Coupon.create(discountCode);
            return coupon.discount(account.getPlan().getPrice());
        }
   }
   class Account {
       Plan plan;
       ...
   }

Here account.getPlan( ).getPrice( ) violated the LoD. The most obvious fix is to delegate/tell:

    class User {
        Account account;
        ...
        double discountedPlanPrice(String discountCode) {
            // delegate
            return account.discountedPlanPrice(discountCode);
         }
     }
     class Account {
         Plan plan;
         ...
         double discountedPlanPrice(String discountCode) {
             Coupon coupon = Coupon.create(discountCode);
             return coupon.discount(plan.getPrice());
         }
      }

Each function should have a limited amount of knowledge as opposed to knowing about the whole object map so our neighboring objects need to know what we have done in order to depend on them to propagate that message to the correct location. Following this rule is hard, which is why it is called the “Suggestion of Demeter” by many because it is so easy to violate. Following this rule, though, is extremely beneficial because any function that “tells” instead of “asks” is decoupled from the rest of the code around it.

The blog I retrieved this information from was https://hackernoon.com/object-oriented-tricks-2-law-of-demeter-4ecc9becad85. The information was extremely easy to follow and understand. The coding examples given to show the difference between following the LoD and not following it were simple and clear. I also found the explanation of LoD given to be simple and to the point. Going forward with coding, although understanding that following LoD can be hard, I plan to utilize this guideline in order to enhance and simplify all of my future codes.

By following the LoD in future coding endeavors, my code will be easier to test, I can reuse classes more easily, the amount of coupling and dependencies between classes will be reduced, my code will more flexible when I make changes to it and it will be more maintainable.

Information gathered for this blog:
https://medium.com/better-programming/demeters-law-don-t-talk-to-strangers-87bb4af11694
https://hackernoon.com/object-oriented-tricks-2-law-of-demeter-4ecc9becad85
https://en.wikipedia.org/wiki/Law_of_Demeter

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

“Encapsulate what varies”

When asked the question “Which object-oriented design principle do you think is most important?” a Software Architect named Nicholas Cloud answered, “Encapsulate what varies”. I must say, I couldn’t agree more. In his blog, DeveolpIntelligence, Nicholas writes about his desire to constantly look for ways to utilize this principle to make writing expressive and maintainable code easier. He gives a lot of great examples and breaks them down, explaining each way they can be changed and why that change makes the code better.

Encapsulation means to bundle data with methods that operate on that data, or to restrict the direct access to some of an objects components. There has been some debate between programming language researches on which meaning they prefer to use. The Gang of Four suggests that we consider what should be variable in our designs. This approach is the opposite of focusing on the cause of redesign. Many design patterns use encapsulation to create layers between objects, making it easy to change things on different sides of the layers without negatively affecting the other side. There are so many advantages of encapsulation, from data hiding, to reusability, to making testing your code easier.

As one of the fundamentals of OOP, it is arguably one of the most important due to the number of advantages it brings. I found all the information I obtained from a few different blog posts and articles, all of which had almost the exact same information. Having read just the definition, understanding the true essence of encapsulation was difficult, but the code examples I found were extremely helpful and made things clearer. I thought the manner in which the information was presented was easy to follow and the use of real-life examples and comparisons kept me interested enough to stay focused on the subject. Below is an example I found easy to understand;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Person {
String name;
int age;

 void talk() {
}
 
void think() {
}
 
void work() {
}
 
void play() {
}
}

The common characteristics and behaviors of a person are packaged into a single unit: the Personclass. The Person class is an encapsulation unit and the Person object exposes its attributes and behaviors to the outside world:
1
2
3
Person you = new Person();
you.name = "John";
you.work();
Here, encapsulation hides implementation details of the Person class from other objects. Likewise, creating an interface is also the process of encapsulation:
1
2
3
4
5
interface Human {
void eat();
void talk();
void think();
}
This interface groups the essential behaviors of human-being in a single unit.

The rest of the examples can be found at https://www.codejava.net/java-core/the-java-language/what-is-encapsulation-in-java-the-what-why-and-how.

I enjoyed learning about this principle and I feel more confident going forth in this field knowing yet another way to make writing code neater, more maintainable, flexible and easier to read.

Knowledge obtained for this blog post:
https://www.informit.com/articles/article.aspx?p=167890&seqNum=4
https://www.developintelligence.com/blog/2013/04/encapsulate-what-varies/
https://levelup.gitconnected.com/object-oriented-design-principles-bb6daf98b185
https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)
https://www.geeksforgeeks.org/encapsulation-in-java/

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

Anti-Patterns

Anti-patterns are patterns in software development that are considered bad programming practices. The exact definition is “An Anti-pattern is a literary form that describes a commonly occurring solution to a problem that generates decidedly negative consequences.” More understandably put, an anti-pattern is a way of not solving a problem. Anti-Patterns are said to be the opposite of Design Patterns, for instance, with Design Patterns, users usually start with a well-defined problem and identify the best path to take to the solution, whereas with Anti-Patterns, they begin with a failed solution, which can be challenging and usually further complicate matters.
(http://antipatterns.com/EdJs_Paper/Antipatterns.html)

I found a video online that I found easy to follow along to by Andy Sterkowitz on 5 programming anti-patterns that was specifically geared towards beginners. The first anti-pattern he spoke about was ambiguous naming; ambiguous naming of variables, functions and classes. He explains that when you’re writing code, your variables should be well named, to make your ( or another’s) comprehension of your code easy. He suggests really thinking about what you’re planning on naming things within your code to simplify things. The second anti-pattern he spoke about was magic strings and numbers.
Example:

if (age > 21) {
// do something
}
By the context of this, obviously you’d be checking for the legal age.. but you can’t assume that this information is known.

The third anti-pattern is called lava flow. He compared this anti-pattern to how lava flows continuously and hardens along the way, saying that as a programmer early on, you think you’re just creating all these small little apps you might need but you’re actually making parts of your application warped or hard to develop. He suggests to use Git to modify and make changes to your code instead of building a whole bunch of different sections. The fourth anti-pattern he talked about was cut and paste. What that means, he says, is when you see a code and there are ten or so different functions that all just say the same thing basically. He suggests to instead make one function that does everything or even one class. Doing this will save you time from having to go back through each and every function and modify one thing. The fifth anti-pattern he talked about is called the poltergeist pattern. Andy explained that this is basically just code that doesn’t serve a true purpose, like a class that just calls upon another class.

Through this video, I learned that the best way to write code is to not have a lot of code and to really make sure you have strict guidelines about when it is appropriate to make a new class, method or function. Andy gave a lot of useful and helpful tips on how to improve my coding skills and what common mistakes I should avoid doing in the future. He used easy to grasp and very relatable metaphors and comparisons to real life that made understanding his explanations of the patterns easy and interesting. While watching this video I had quite a few “wow, that’s really helpful.” moments and I realized there are a few things I should and will be changing from here on out to tidy up my code.

Video used for this entry:
https://www.youtube.com/watch?v=lQ_rGCL17EE

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

What’s that smell?

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

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

The 5 different categories of code smells are:

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

    (https://youtu.be/D4auWwMsEnY)

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

Let’s talk about adapters

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

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

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

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

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

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

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

YAGNI

Welcome back!

This week in Coding Kitchen, we explore one of the key principles of Extreme Programming, YAGNI (You Ain’t Gonna Need It). This principle states that some capability we think our software will need in the future should not be built now because “you aren’t gonna need it“, or as XP co-founder Ron Jeffries put it, “Always implement things when you actually need them, never when you just foresee that you need them.

The YAGNI principle is to be used in conjunction with other practices, such as continuous integration, continuous refactoring and continuous automated unit testing. Without the additional use of any of these other practices, your code could go into Technical Debt, which means it could become disorganized and need to be reworked. Using the YAGNI principle saves you time by helping you to avoid writing code that you do not end up needing and by making your code better because you did not have to fill it with guesses that turned out to be wrong.

In an article posted by Martin Fowler, he uses an example about selling insurance for the shipping business. His example states that an insurance company’s software system is broken into two components, pricing and sales and that the dependencies cannot usefully build sales software until the relevant pricing software is completed. His example also states that while the company works on updating the pricing component to add support for risks from storms, they consider working on a feature they will not need for another six months for piracy pricing. By adding on this additional feature now, Fowler declares that doing so would incur three classes of presumptive features, and four kinds of costs that occur by neglecting YAGNI for them.

1) Wrong feature — Cost of building, cost of carry + cost of delay
2) Right feature, built wrong — Cost of repair, cost of carry + cost of delay
3) Right feature, built right — Cost of carry + cost of delay

I chose this article because this particular example given by Fowler highlights the benefits of using YAGNI and why neglecting to do so would inherently cause many issues and become costly. As a future software engineer, I would prefer having to write less code that is easier to understand rather than have lines of useless, possibly obsolete code. I found Fowlers explanation of YAGNI and his further explanation of the many ways applying this principle could cause problems in comparison to the very few ways it could be of benefit easy to understand and useful. Having knowledge of this principle as a programmer will make writing and editing code in my future professional endeavors much more time and cost effective.

Inspiration and information gathered for this blog post :

https://dzone.com/articles/martin-fowlerbliki-yagni-youre-not-gonna-need-it

https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it

http://c2.com/xp/YouArentGonnaNeedIt.html

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

SOLID Design Principles

Hello everyone and welcome back.

 This week I will be exploring three of the five design principles of OOP; Single Responsibility Principle (SRP), Open-Closed Principle (OCP), Liskov’ Substituion Principle (LSP), Interface Segregation Principle (ISP), and Dependency Inversion Principle (DIP).

My first introduction to these principles was in reading “Clean Code: A Handbook of Agile Software Craftsmanship” by Robert C. Martin. Prior to learning these concepts, my code was messy and not easily modified. I used to put way too many methods in classes, and my child classes were not fully compatible with the parent classes. I chose this topic because we all benefit when our code is adaptable, clear-cut and easy to maintain. I chose this blog because the author presents the information in a very direct format with great examples.

The purpose of these design principles is to make our code easier to maintain, change and understand. As software engineers, a lot of the code most of us will be working on will be code that others have written. There will be others who will be maintaining our code when we are no longer working on it. When we follow these design principles, not only do we improve our coding skills, but we help those who maintain the code we have written.

Single Responsibility Principle (SRP) means that a class should have only one purpose/task that it is responsible for. This makes code more maintainable by making software more comprehensible for future changes to be made. If a single class has multiple responsibilities, editing in the future will be more complicated because we will have to make additional changes to the classes that are dependent on it. You will have to update and recompile dependent classes that are not directly related to the change you needed to make.

Open-Closed Principle (OCP) means functions, classes and modules should be written such that others can add to them but not change the core elements. When we use this principle our code, our software will give less errors when requirements change. This makes our code more robust and reusable.

Liskov’s Substitution Principle states that every dependent class should be substitutable for their parent class without breaking functionality. Our validation rules on input parameters in subclasses should not be stricter than the input parameters on the parent. Using this principle increases maintainability of our software by making our class hierarchies easier to understand.

Through utilizing these design principles, I will be a better software engineer. I am more aware of ways to improve the legibility, and modifiability of my code. These design principles will help me stay away from poor coding practice.

Blog of Inspiration:

https://android.jlelse.eu/solid-principles-the-definitive-guide-75e30a284dea#.xq7a6fvtk

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

Hello fellow CS enthusiasts and beginner programmers!

  In this week’s blog post, I plan to go over Object Oriented Programming. I found an excellent blog that explains the four principles of OOP; encapsulation, abstraction, inheritance and polymorphism. The author hilariously titled the blog “How to explain object-oriented programming concepts to a 6-year-old”. As a father of two 6 year old boys, I don’t see many 6 year old’s understanding it but it did however clarify Object Oriented Programming for me. I chose this specific blog because I found it comprehensible and uncomplicated. It was written and formatted in a way that made it very enjoyable to read. I have read many examples in textbooks but none of them were as easy to understand as these for me.

I enjoyed the simple example the blogger used to explain encapsulation. Encapsulation happens when the object keeps its state private inside a class, but other objects can’t directly access it. Other objects they can only use public methods. The object maintains its own state, and unless explicitly stated other classes can’t change it. We are made aware of a developing sim game involving a cat class which has private variables as the “state” of the cat such as mood, hungerLevel, energyLevel. The cat in the example also has a private meow() method, and public methods sleep(), play() and feed(). Each of the public methods modifies the state of the cat class and has the possibility of invoking the private meow() method.

To explain abstraction, the blogger used an example of a cellphone. When using your cellphone, you only need to use a few buttons because implementation details are hidden. We don’t need to be aware of all the intricate processes that occur when we press buttons on our cellphones, we just need them to behave accordingly as expected.

Inheritance is the concept of code being reused to create more specific types of an object. is fairly easy to understand due to classes being referred to as parent and child classes. The child receives all the fields and methods of the parent class but can also have its own unique methods and fields.

When explaining polymorphism, the author uses the example of a parent “shape” class with the children triangle, circle, and rectangle. In the shape class we have methods CalculateSurfaceArea(), and CalculatePerimeter(). The children classes utilize polymorphism when calling the abstract classes of the parent because they each have their own formulas for surface area and perimeter.

Since discovering this blog post, I am more confident in my understanding of OOP. I can visualize the 4 principles better and will be able to utilize them in my coding much more efficiently now. I hope you enjoyed this blog post, attached below is the blog which inspired my post.

https://www.freecodecamp.org/news/object-oriented-programming-concepts-21bb035f7260/

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

Introduction

Hello, my name is John Simolaris and I’m currently a student at Worcester State University. Throughout my blog I will share various tools, tips and information I gain along the way to becoming a Software Engineer. In my personal life, I enjoy fixing up old power wheels, strength training, and researching various topics such as neurochemistry, philosphy, poetry, art, pure mathematics, childhood development, etc. Professionally, I am interested in learning software design and penetration testing. From now until the end of 2020, I will be posting about my findings in:

  • Design Principles
    • Object Oriented Programming
      • Abstraction
      • Encapsulation
      • Polymorphism
      • Inheritance
  • SOLID
    • Single Responsibility Principle (SRP)
    • Open-Closed Principle (OCP)
    • Liskov Substitution Principle (LSP)
    • Interface Segregation Principle (ISP)
    • Dependency Inversion Principle (DIP)
  • DRY (Don’t Repeat Yourself)
  • YAGNI (You Ain’t Gonna Need It)
  • GRASP (General Responsibility Assignment Software Patterns)
    • Controller
    • Creator
    • High Cohesion
    • Indirection
    • Information Expert
    • Low Coupling
    • Polymorphism
    • Protected Variations
    • Pure Fabrication
  • “Encapsulate what varies.”
  • “Program to an interface, not an implementation.”
  • “Favor composition over inheritance.”
  • “Strive for loosely coupled designs between objects that interact”
  • Principle of Least Knowledge (AKA Law of Demeter)
  • Inversion of Control
  • Design Patterns
    • Creational
    • Structural
    • Behavioral
    • Concurrency
  • Refactoring
  • Smells
    • Code Smells
    • Design Smells
  • Software Architectures
    • Architectural Patterns
    • Architectural Styles
  • REST API Design
  • Software Frameworks
  • Documentation
  • Modeling
    • Unified Modeling Language (UML)
    • C4 Model
  • Anti-Patterns
  • Implementation of Web Systems
    • Front end
    • Back end
    • Data persistence layer

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