Java Singleton Design Pattern Best Practices with Examples

This week blog post is about Java Singleton design pattern. The reasons for Singleton pattern are to restricts the instantiation of a class and ensures that only one instance of the class exists. This article explains and show examples of the many different approaches of Singleton pattern implementation, the problems with the approach.

The approaches of Singleton pattern implementation:

  1. Eager initialization – pros: easiest way to create a singleton class | cons: instance variable is created even though it might not be used.
  2. Static block initialization – Similar to eager initialization but provides option for exception handling.
  3. Lazy initialization – This is the approach that was we used in class and it’s a completely fine for a single threaded environment, but potential can cause problems for a multi-threaded environment.
  4. Thread Safe Singleton – resolutions for Lazy initialization but reduces performance. Requires synchronization.
  5. Bill Pugh Singleton implementation – Best method for singleton implementation. Contains a inner static helper class by doing so the instance is not created unless someone calls on the getInstance() method. Doesn’t require synchronization.
  6. Using Reflection to destroy Singleton Pattern – This approach destroyed the singleton pattern.
  7. Enum Singleton – resolution for reflection method. Not flexible. Any enum value is instantiated only once.
  8. Serialization and Singleton – Use to store it in file system to retrieve it later. Cons: when deserialize it creates a new instance of the class.

I found this article very helpful with understanding Singleton design. This article explains to me when to use and the consequences that comes with each different implementation. The content of this blog was the best. The example code of this article was very clear and made easier to understand the materials. This change my way of using this method because I now know which method to choose in certain situation. The lazy initialization will be used more while I’m in school, but I think Bill Pugh method will be used more in the future because it’s very popular and it’s easy to understand. I agree with all the contents, but I read the comments of the other readers and they had some issue with some of the content which I have to read more about the subject to find out what’s right and wrong.

https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples

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

What is Behavior-Driven Development?

This week’s topic has to do with behavior-driven development, which a strategy of software development that focuses on the communicating narrative between developers so as to ensure that all members understand the specifications and other requirements of a program. I found an insightful article at the following website: https://airbrake.io/blog/software-design/behavior-driven-development. This blog post is one of a few in a series explaining different development techniques that work together as part of the software development life cycle.

As explained in the article, behavior-driven development, or BDD, works hand-in-hand with other strategies, such as test-driven development, which entails the execution of a failing test and then subsequently writing a minimum amount of code in order to pass the test. The BDD of tests becomes different from this technique when it relies more on the desired behavior of the program, rather than simply writing initially failing tests for all parts of the program, as utilized with test-driven development. BDD defines behavior specifications with user stories that outline various scenarios for the program to be executed or tested. These stories take on a narrative tone that states who and what are involved in each scenario, as well as the conditions that must be met in order for the scenarios to be successfully implemented. By using a common language understood and easily communicated by everyone on a development team, members can easily collaborate to define these specifications and perform tests based on the definitions given with the user stories.

This topic stuck out to me because it somewhat combined what I have been learning in both my Software Design and Software Testing courses this semester. This post discusses different methods of designing programs and their tests, and I thought that BDD clearly incorporated both, with the description of designing the behavior specifications to be met, as well as the concept of testing these specifications. We’ve somewhat been starting to take on both of these roles in the classroom by determining the purpose and desired functions of our programs, and then performing tests to ensure that the functions are working successfully. While we haven’t written out user stories to more specifically outline the behaviors, I think that this process is more implicit for us at this point.

From the blog CS@Worcester – Hi, I'm Kat. by Kat Law and used with permission of the author. All other rights reserved by the author.

Test Automation

https://abstracta.us/blog/software-testing/test-automation-patterns-and-good-practices/

This blog post discusses good practices to use with test automation. Automating tests can save time and decrease the amount of work that has to be done. Following these practices will help ensure that you get the most value out of automation.

Test Code Review

  • All levels of testing should be reviewed to examine their quality. This will help the tester discover bad practices or mismatches in the tests.

Apply Assertions

  • Assertions should be used to identify problems.
  • An assertion that’s too generic can create false negatives and false positives, so pay special attention in the definition of assertions.

Behavior-Driven Development (BDD)

  • A common language should be created for the business and engineers to be used as a starting point for development and testing.
  • User stories are defined and used as input for test cases.
  • BDD gives developers clear specifications and brings testability to a system.

Page Object Pattern for UI Testing

  • The use of design patterns increases scalability and maintainability
  • The page object pattern allows you to reuse knowledge of the structure of an application while having a minimal impact on tests.
  • This pattern strengthens tests by decoupling the structure of the user interface from the test code

Data-Driven Testing

  • With data-driven testing, automated tests are parameterized so that the same steps can be carried out with diverse amounts of test data
  • Adding data to the file creates new test cases

Parallel Execution of Tests

  • Using parallel execution options like Selenium will reduce testing time by running several tests at the same time.

I thought this blog was very interesting. While I have learned a little about test automation I haven’t used it enough to learn the best practices for it. It is important to learn these practices because the whole point of automation is to save time, and if you don’t do it correctly you will end up spending more time trying to fix your errors.

I thought the most interesting part of this post was the section on the page object pattern. This is a design pattern that I’ve never heard of. It seems to be very useful because it helps prevent you from breaking your tests when you change your code. This is a topic that I would like to learn more about and will keep in mind when I work with automated testing. Overall I thought this was a useful and well-written blog post.

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

Machine-learning system tackles speech and object recognition, all at once

http://news.mit.edu/machine-learning-image-object-recognition-0918

Speech recognition systems usually require hundreds of thousands of transcripts in order to work properly. This new model of machine learning learns through audio visual associations similar to how a child would learn, where they correlate speech with related images. The researchers then modified the model to associate specific words with specific pixels. It works by dividing the image into a grid of cells consisting of patches of pixels while dividing the audio portion into segments of the spectrogram. It then compares each image cell to each audio segment and produces a similarity score for each individual one. The researches call this comparison method a “matchmap”. One good use of this is learning translations between all of the languages on the planet. There are an estimated total of 7,000 languages spoken wordwide and only about 100 have trascription data for speech recognition. With this model, two different language speakers can describe the same image and the machine can learn the speech signals of the two languages and match the words, making them translations of one another. This is interesting because that means the model does not require actual text to learn to translate. In languages where things are not commonly written down, the machine can translate meanings where other methods that are common today cannot.

This method is important to note because machine learning is a growing topic in the world of computer science and this could open up all kinds of possibilities. It is a new and innovative way to try to solve a problem and might become something needed for future jobs or projects in life. With this matchmap system, speech recognition no longer needs to be manually taught hundreds of thousands of transcriptions and examples of those transcriptions in order to function properly. This is increasingly important since new words enter our dictionary and become common for people over time. Currently, the machine can only recognize a few hundred words but in the future it could help advance the machine learning field while also improving the speech recognition software that exists such as siri.

 

From the blog CS-443 – Timothy Montague Blog by Timothy Montague and used with permission of the author. All other rights reserved by the author.

Post #4: Testing Documentation and Formatting

Hello and welcome back to Benderson’s blog! This week’s blog will focus on the documentation and formatting you would use for testing software. I found a blog that talked about the right format for documentation and formatting by Chris Kenst. At the beginning of his blog, he talks about how you know what is the appropriate documentation for a test and says it will depend on the degree on the test technique and approach you use. He talks about a couple different techniques in a short sentence but in the end says cramming all of them into one system isn’t really a good idea. The next paragraph talks about how much you need for documentation which he sums up with a small amount because you need to focus more on the project itself than the documentation that you put in there. The time it would take to make all the documentation for the test, you would run out of time for the test and documentation it self. The next and final paragraph focuses on stay agile, “Focusing on the appropriate documentation for your tests and then creating the smallest amount you need to do your job well also allows you to have agility”, this sentence from the blog sums up the whole paragraph really well.

This blog was very informational on the topic of test documentation and formatting and how much you should focus on it. I haven’t really been big on documentation in my four years in college as I always find it as an additional thing that I really don’t have to do but over the years, I’ve began to realize how important it is to have in your code. My reasoning usually is that I know what each of those methods do so it doesn’t need to be documented and formatted but I realized that in the actual work world I will have other people reading my blogs and they won’t know exactly what each method does unless I document it. So going back to this blog, getting all the information I need to know how much I should document and how I should format is very helpful for not only me but my future colleagues who will have to read my code. Knowing exactly what you’re testing is probably a pretty good thing to know. Also, knowing some tidbits such as focus more on the testing than the actual documentation and write a small amount so you have time, will help me make sure I get the tests done and have a good amount of documentation.

Link: https://www.kenst.com/2018/09/appropriate-test-documentation-formatting/

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

Software Quality

The podcast that I listened to this week is of course again by Test Talks which is hosted by Joe Colantonio. This podcast is a more recent one that talks about software quality and the state of it in 2018. As software is getting more and more powerful and popular, it is important to try to make it the best quality software it can be so it does not ruin your project or even worse, a business. Joe talks to Shailesh Rao, who is the the current COO of BrowserStick. The first thing Rao notes as importance is comparing your software toa stress free life. It is the ultimate goal, but it is always worked on. Having a bug-free software takes time and you might always be working on it, but it’s the always working on it that is of key. Trying to make it work to your utmost ability is a great goal to have in mind and will help you in the long run. He also stresses the importance of quality itself, not just in coding, but the quality behind hiring someone, and the culture you create. He then goes on to talk about automated testing becoming more and more crucial and seeing it as a means to an end. Only about 20-30 percent of companies are using it, and while many do not use it, there is no lack of intent there and the numbers are growing. The last thing he mentions is a piece of advice which is that discipline is key. Everyone is going through the same struggle and its important to know that. Apply that discipline and don’t give it.
What I really liked about this podcast was that it talked about something that is going on now and what is important right now. It’s really cool to know how popular software quality and automated testing is becoming. It helps me know what companies will want you to know and what you should be good at. After I graduate, of course it will be important for me to know the basis of coding, and to know the most popular languages like java and c, but technology is always changing and I need to be right there soaking everything in, so I can be at my utmost prepared self.

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

Testing Efficacy and Machine Learning

As stated in the title of this post, this week’s Software Testing topic of discussion relates to the hand-in-hand incorporation of software testing and machine learning, found at the following blog post: https://testing.googleblog.com/2018/09/efficacy-presubmit.html. Google has been taking on automated testing of their code before permanently committing to their huge repository. By doing so, they have examined “Efficacy Presubmit,” which uses the idea of automatically predicting which tests would be best appropriate to run, as well as learning about which tests are more useful or valuable than others in terms of discovering critical issues in code. Tests that are more guaranteed to pass every time are less meaningful than those that come up with failures. This process of discovering the more valuable tests would certainly assist with optimizing time and resources spent to run tests. To do this, Google applied a machine learning concept, binary classification, to “learn” whether a test would or would not pass (a binary outcome), using the numerical data given from running software tests, such as pass/failure history and runtime for tests. By predicting the outcomes ahead of time, testers can understand which tests are more likely to keep passing every time or produce more failures.

I was really interested in learning more about the software development process at Google. Many of my CS friends discuss how awesome it would be to work at Google, Microsoft, or Facebook, among other giant companies dominating the field of software development. Reading more about how developers at Google undergo the cycle of writing and testing their code (with multiple iterations before and after committing, as to be expected) increased my confidence that even within the first few weeks of my software testing course, our course content lines up with what Google (and other companies I’m sure) is doing. I also enjoyed learning about how machine learning can be applied to software testing. I had only thought of the two concepts in a mutually exclusive fashion, but the description of the data used for the classification of the tests (like the runtimes for tests) gave me perspective of how various concepts in computer science can work together to solve problems.

From the blog CS@Worcester – Hi, I'm Kat. by Kat Law and used with permission of the author. All other rights reserved by the author.

Given-When-Then

GivenWhenThen

Blogger Martin Fowler in his self titled blog describes a template for organizing unit tests, called “Given, When, Then”. This concept is perhaps a rephrasing of what we discussed in class, the four phase test, or “Setup, Exercise, Verify, (teardown)”. The idea is to structure our test cases in a logical, easy to understand process.

Fowler describes the idea as “essential to breaking down writing a scenario (or test) into three sections”. Given a specification, any situation we need to test for can be broken down into these three steps. The first section is “given”, or the “setup”. During this phase of the test, we would create variables and set up the preconditions to a test. Fowler uses a scenario of trading stock to illustrate his point. “Given” a certain amount of stock to invest (precondition) move on to the next phase.

The next step in the model is the “when” phase. During this phase of testing, we are choosing the behavior of a function to be tested. In Fowler’s stock trading example, this translates to “Given: x amount of stock to sell- When: I want to sell y stock”.  This phase essentially defines the behavior of the test we are writing.

Last but not least, the “then” phase is all about putting the first two cases together and verifying them. Following Fowler’s stock example, the “then” phase is represented as “Given: x amount of stock to sell – When: I want to sell y stock – Then: I should have x-y stock”. This phase is where you verify the expected behavior to the actual behavior of the program.

Personally I find this model particularly helpful, in the sense that it provides a useful narrative for breaking down testing situations. To me the “given-when-then” model seems more intuitive than “arrange, act, assert” or “Setup, exercise, verify”. While all three models definitely describe the same process, I think that this model is the most clear. In any case, breaking down test scenarios into discrete parts like this is integral to creating clear, easy to understand tests.

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

Mutation Testing

Greetings reader!

The nature of this blog is to give a short summary over a topic that is essential in the Computer Science field: Mutation Testing. This blog will share my analysis of Tutorial’sPoint’s: Simply Easy Learning- Mutation Testing Tutorial.  I will be expressing my reaction to the content by sharing what I find useful and interesting and displaying if I have any concerns or disagreements. Without any further introduction, let’s begin.

First, let’s start with defining what mutation testing is. Mutation testing is a testing technique that uses the structure of the code to conduct the testing process. It is simply the rewriting of code in small ways in order to take out the excessiveness in the code. This wordiness may cause failures in the software if it is not altered. It is very sneaky because it can pass through the testing process’ unnoticed.

There are three types of mutation testing: value, decision, and statement mutations. Value mutations are efforts to change the values to display errors in the programs. The change of the value is usually to either a very large value or a very small value. It is found that the most common strategy to combat this is to change the constants. Decision mutations are when the code is changed to check for errors in the design. Ways to fix these errors are by changing the arithmetic operators to find the failures or by altering the relational and logical operators. Statement mutations are when changes are done to the statements by deleting or rewriting the line.

Mutation testing is based on two theorems. The first is the competent programmer theorem. This theorem explains that most software errors made by experienced programmers are due to small syntax errors. The second theory is called the coupling effect. The coupling effect says that simple errors can couple to form other faults.

All in all, mutation testing is a fairly simple technique that is used when testing code. Sometimes errors or faults can be hidden when making tests that will cause the source code to fail. Mutation testing is the process of altering these subtle errors in efforts to run the code.  This topic is extremely important to this field because it gives us a deeper understanding of our errors, which helps greatly when correcting “bad” code.

Source: Tutorial’sPoint’s: Simply Easy Learning- Mutation Testing Tutorial

 

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

The Simple Factory – Easy as Cake?

Using the Simple Factory design pattern is a lot like making cheesecake

Software developer Sihui Huang, writing for the blog freeCodeCamp, explains the simple factory design pattern in terms that most people can appreciate – cheesecake.

Huang walks us through the basic steps in a simple factory for creating cheesecake. Starting with a number of his favorite types, he creates a makeCheeseCake() method which calls cheesecake.makeCrust, cheesecake.AddLayers, etc. The makeCheeseCake() method uses the type of cheesecake as a parameter, and calls the the steps to creating a cheesecake that all different types have in common. No matter what kind of cheesecake you are making, you still need to make the crust. So the makeCheeseCake() method is only concerned about the steps required in making any kind of cheesecake, it doesn’t care about what flavor the particular instance is. Huang describes this concept, as we have in class, as encapsulating what varies.

So Huang goes on to create a cheesecake factory class that handles all the different classes of cheesecake we can possibly create, and returns the appropriate cheesecake type by a createCheeseCake() method inside the factory class. The trick is that when you call the makeCheeseCake(), a new cheeseCakeFactory object is created, and uses the createCheeseCake method to determine what type the cheesecake is. So now the MakeCheeseCake() method does not need to know at all about what kind of cheesecake it is creating.

By separating the parts of a program that stay the same from those that vary, we can simplify adding and modifying different types of an object (in this case cheesecake) by adding a new class and adding to the cheeseCakeFactory class. No code has to be rewritten to accommodate for changes and removals of types of cheesecake.

Personally I enjoy Huang’s analogy to elaborate on the simple factory design pattern. Being able to separate varying parts of a program from parts that never change makes our code more understandable, coherent, and easy to modify. And the idea that a “factory” can handle the details of initializing different types of objects instead of having separate implementations for every object type is good design, and I think the cheesecake factory example is a good metaphor for encapsulation

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