Builder Pattern

http://marxsoftware.blogspot.com/2013/10/too-many-parameters-in-java-3-builder-pattern.html

This blog post details a way to reduce the number of parameters required for a constructor: the builder design pattern. In this pattern an object called a builder receives each parameter step by step and returns the resulting constructed object at once. This blog post explains the pattern by using detailed code examples. First a Person class is shown without the builder pattern to demonstrate how too many parameters in a constructor can become a problem. Then a PersonBuilder class is shown which conveys the idea behind a builder class. Each variable is set in a setter method, then a createPerson method returns a new Person with the values from the setter methods as parameters. With this implementation, the values of a Person are set with methods as opposed to the parameters of the Person constructor. There is a lot more code, but it is much more readable than having a very large parameter list. The next few code examples show how a builder class can be nested and enhanced with the use of custom types and parameter objects.

The biggest advantages of the builder pattern are usability and readability.  Parameters are reduced and are provided in easy to read method calls. This approach also lets you acquire an object in a single statement and state. Also, it is even easier to apply an IDE’s code completion feature. The biggest drawback is that the number of lines of code are essentially doubled. Despite the fact that it is easier to read, the code is much more verbose. The author included examples of client code instantiating a Person with and without builders, which I thought was a good way to highlight the difference using a builder makes.

Instantiating with builders:

final Person person1 = new Person.PersonBuilder(
   new FullName.FullNameBuilder(
      new Name("Dynamite"), new Name("Napoleon")).createFullName(),
   new Address.AddressBuilder(
      new City("Preston"), State.ID).createAddress()).createPerson();

Without:

final person = new Person("Coltrane", "Rosco", "Purvis", null, "Hazzard", "Georgia", false, true, true);

As you can see, the builder implementation is extremely verbose but it is easier to read and harder to make a mistake. The more parameters there are, the more true this is.

I selected this blog after looking up design patterns in the gang of four book that we haven’t covered in class. I thought this blog did a good job explaining why this pattern would be used and the benefits and drawbacks of using it. I chose this topic because design patterns are one of the most useful things to learn as a software developer and if we end up covering this one in class I will be well prepared. I will definitely be applying what I’ve learned from this blog, as I’m sure every programmer knows how frustrating long parameter lists can be. I’m glad that now I know a design pattern that alleviates this problem.

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

Builder Pattern

http://marxsoftware.blogspot.com/2013/10/too-many-parameters-in-java-3-builder-pattern.html

This blog post details a way to reduce the number of parameters required for a constructor: the builder design pattern. In this pattern an object called a builder receives each parameter step by step and returns the resulting constructed object at once. This blog post explains the pattern by using detailed code examples. First a Person class is shown without the builder pattern to demonstrate how too many parameters in a constructor can become a problem. Then a PersonBuilder class is shown which conveys the idea behind a builder class. Each variable is set in a setter method, then a createPerson method returns a new Person with the values from the setter methods as parameters. With this implementation, the values of a Person are set with methods as opposed to the parameters of the Person constructor. There is a lot more code, but it is much more readable than having a very large parameter list. The next few code examples show how a builder class can be nested and enhanced with the use of custom types and parameter objects.

The biggest advantages of the builder pattern are usability and readability.  Parameters are reduced and are provided in easy to read method calls. This approach also lets you acquire an object in a single statement and state. Also, it is even easier to apply an IDE’s code completion feature. The biggest drawback is that the number of lines of code are essentially doubled. Despite the fact that it is easier to read, the code is much more verbose. The author included examples of client code instantiating a Person with and without builders, which I thought was a good way to highlight the difference using a builder makes.

Instantiating with builders:

final Person person1 = new Person.PersonBuilder(
   new FullName.FullNameBuilder(
      new Name("Dynamite"), new Name("Napoleon")).createFullName(),
   new Address.AddressBuilder(
      new City("Preston"), State.ID).createAddress()).createPerson();

Without:

final person = new Person("Coltrane", "Rosco", "Purvis", null, "Hazzard", "Georgia", false, true, true);

As you can see, the builder implementation is extremely verbose but it is easier to read and harder to make a mistake. The more parameters there are, the more true this is.

I selected this blog after looking up design patterns in the gang of four book that we haven’t covered in class. I thought this blog did a good job explaining why this pattern would be used and the benefits and drawbacks of using it. I chose this topic because design patterns are one of the most useful things to learn as a software developer and if we end up covering this one in class I will be well prepared. I will definitely be applying what I’ve learned from this blog, as I’m sure every programmer knows how frustrating long parameter lists can be. I’m glad that now I know a design pattern that alleviates this problem.

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

Anti-Patterns Part 2

So this week I have decided to pick up where I left off two week ago and discuss some more anti-patterns I have found. I find them to be quite useful as they are often easy to pick out/recognize, thus they are easy to avoid. This blog by Sahand Saba discusses several of them, but once again I will pick and choose a few as space is limited.

Have you ever been looking through some code and seen random, ambiguous numbers everywhere? I’m sure you have, so I am sure you know how annoying it is. These “magic numbers” make code hard to understand and can cause problems when trying to modify it later down the line. Always try to associate numbers with a variable or at the very least some sort of description to go along with it. It will prevent headaches and problems in the future. These “magic numbers” have always been a pet peeve of mine, so this just drives the point home further for me.

The next one I’ll admit I have a tendency to do, but after reading what Saba had to say about it, I am going to try and avoid doing it in the future. This anti-pattern is being afraid to add too many classes. The story goes, sometimes developers are afraid to add more classes and they think it will increase the complexity. However, in reality, it is just the opposite. Saba likens it to a tangled ball or yarns vs single strands of yards. Which is easier to work with? I think you know the answer. That example really made it clear to me that smaller, simpler classes really do make it easier and less complex.

Over analyzing is the last one I wanted to mention. This is basically thinking and discussing about a problem so much, that no work actually ever gets done on it. To avoid this, it is suggested that you break apart the problem into smaller pieces/iterations (a.k.a. Agile Software Development) and address them one step at a time. This way the overall problem is far less overwhelming and easier to deal with. I feel that this a very important skill to have and makes life a lot easier when dealing a massive, overwhelming issue. I always try to take this approach, although sometimes it can be easier said than done.

There are several other anti-patterns discussed including dealing with team meetings, management, etc., but since I am running out of space, I will leave them for another time. However, I wanted to reiterate that I feel anti-patterns are a great way to learn good coding practices. It is basically learning from other people’s mistakes and experiences, so hopefully their mistakes will allow you save some time and headaches in the future.

Link:

http://sahandsaba.com/nine-anti-patterns-every-programmer-should-be-aware-of-with-examples.html#magic-numbers-and-strings

 

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

Excuses Can Be the Death of a Product

As we find ourselves really getting into the thick of the semester, I still find myself going back to the same site to find stuff to write about for this class. I’ve found softwaretestinghelp.com to really useful and has provided me with some valuable advice. Now, about this week topic, which is “5 Excuses Every Software Tester Must Stop Giving”…

Excuses are wonderful thing when testing software as it often provides an out for when tests fail or don’t go quite as expected. It often takes a realist to get to the truth of the matter when it comes to finding the true bugs within a piece of software. This article discussed five in total, but there are two that stood out to me and since space is limited, I will focus on those.

The first one discussed is not having full control over a test environment. This allows one to blame the environment when a test doesn’t go as planned (i.e. claiming it wasn’t configured correctly). Although this can be frustrating, it can be beneficial as it gets your product out of the ideal, perfect scenario sandbox it has been developed it. It allows both the testers and developers to see how it can handle an environment closer to what it may actually be in when the product is released. Yes, technically it may not be configured correctly, but guess what, it probably won’t be in the real world either so it is important to see how it handles these situations. The article also mentions that if you really need control over the environment, you should work closely with whoever owns it. Either way, saying you don’t have control is really a poor excuse and I know personally, I will be sure to try and not use this as an excuse.

The other “excuse” that stood out to me is about not having the ability to do anything other than manual testing. In other words, you only have time to/are only allowed to do basic, by the book testing. The tester cannot collect metrics, run stress tests, etc. I agree that this often the case, but the article points out some good ways around this that I know I will take into account in the future. The main point of the work-arounds is that a lot of this “non-functional” testing may be able to be done while you are doing to regular testing. Instead of just running through the procedure, watch performance metrics at the same time for example. Maybe grab someone else to help with this rather than asking them after or doing it yourself. In other words, kill two birds with one stone. In may be a bit more challenging, but it can save time and allow for the testing to collect the information they need.

This blog provided some good detail on how to stop making excuses while testing. Excuses can kill a product as often time they are used in a way to avoid the truth. You may be able to push the truth off further down the road, but eventually it is going to come out, and one can only hope there will still be time to address the real problem.

Link:

http://www.softwaretestinghelp.com/5-excuses-every-software-tester-must-stop-giving/

 

 

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

Simple and Static Factories

http://coding-geek.com/design-pattern-factory-patterns/

 

This week’s blog, as with the last, will be about a topic directly covered in class.  And, more importantly, it’ll be necessary knowledge for the first assignment of my class making it a good choice to review.  The above linked article is about factory design patterns.  In class, we only covered the use of simple factories whereas this article covers factory method pattern, abstract factory pattern, and static factory methods as well.  Since I have a length limit, I’ll cover the most pertinent material first while focusing on things I learned outside of the classroom about their use.

Starting with the Simple Factory first.  The author informs us that a simple factory isn’t considered a pattern technically but notes that it’s prevalence requires covering.  They describe it as a tool that can be “to create/instantiate objects,” but it’s one that is rarely used.  More commonly a static factory would be used in java.  If the developer’s “factory method needs some instances to work” or “they need to instantiate the factory in order to use it,” then the simple factory works fine but a lazy static factory is still advised.

Since Static Factories are more resourceful it seems, lets discuss them in more detail.  The first use he notes is the static factory’s ability to replace a constructor to “create an instance. The first advantage I see from this is the fact that factories have names.  Any unique constructor name can only be used once in a class.  Any time a class would need multiple constructors with the same name, static factories can be used with more descriptive names to help anyone reading/working with the code.   Another convenience of static factories, as opposed to constructors, is that it doesn’t have to create an object when invoked.  This helps reduce creating duplicate or unnecessary objects.  One last noticeable boon is its ability to have stricter control over what instances exist.  Relating to the previous blog, this helps guarantee that a class is a singleton.

Although this concept was already covered in class, its importance requires mentioning.  A factory can return any subtype of its return type.  This, overall, adds great flexibility to the programmer.

The author does advise that factories (and most patterns) should only be used when necessary as they can make the code more difficult to understand.  Small personal projects most likely don’t require them but, they find good use when working in large projects.

This information, complimented with examples, was instrumental to my understanding of factory use and implementation.  Using factories seems like a great practice, when done appropriately.  It also is obvious that this is a core tool that I’ll need to have as a developer.  I know that this will be applicable to my immediate work.  But, beyond that, I’ll probably be using it on any project that requires me to create multiple instances of an object.  Especially when that allows me to avoid having to write nearly identical constructors repeatedly.  (Factories seem awesomely useful and a huge time saver.)

From the blog CS@Worcester – W.I.P. (Something catchy) by aguillardcsblog and used with permission of the author. All other rights reserved by the author.

Singleton has a Pattern of Landing Jobs

The Singleton pattern is a great topic choice for me this week. I sought to find a blog to strengthen my understanding of the Singleton pattern. But at the same time, I hoped it would offer insight as to what “Singleton related” questions may be asked in future job interviews. It turns out that such a blog does indeed exist, covering both of these inquiries!

Core Java Interview Questions: The Singleton Design Pattern by Sam

Sam begins by explaining the fundamentals behind design patterns. For nearly all programming languages across the board, design patterns are the conceptual structure and layout of our code, which establish themselves over time for being “tested and well-proven.” Not only are design patterns consistently brought up during job interviews, they are an intricate part of both object-oriented programming, and software development in general. This is important to me because I am always looking for ways to further my programming experience, for both myself and my future career.

So what is a prime example of a “conceptually tested and well-proven” design structure? According to Sam, knowledge of the Singleton design pattern is one of the primary requisites that employers tend to look for when interviewing potential candidates.

Most importantly, the job interviewer is likely to ensure whether or not the candidate knows what a Singleton is, and when/why we would want to use it. We can apply the Singleton pattern when we want to limit the creation of an object to a single instance. For an example of why this may be useful, Sam explains that it can make logical sense for the developer to have “a single go-to place in your application to get data on something.” I believe another reason why the Singleton pattern is useful is that it seems to make the layout of our code look elegant in a neatly structured way. I also feel that if we can limit the creation of needless objects, especially in large projects, this can free up a lot of memory that would otherwise be wasted.

Sam also notes that job interviewers may go a step further and ask the candidate how we create a Singleton pattern, perhaps in Java for example. Objects are created using constructors. Since the goal of a Singleton is to eliminate this ability, this can be achieved by creating a private constructor for the Singleton class. We can then provide a getInstance() method to make the Singleton object available.

I strongly suggest checking out Sam’s blog regarding the Singleton design pattern. I gave a basic summary on the subject, but Sam goes into further details regarding how to instantiate a Singleton pattern, as well as the strengths and weakness of this particular design. My main takeaways from this blog are the concise explanations and insights regarding the Singleton design pattern. Since it seems to be widely considered during interviews, hopefully my further solidified knowledge regarding this topic (due to Sam’s blog) will help me land a good job in the future!

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

Levels of Testing

Source: https://blog.testlodge.com/levels-of-testing/

Another week into my blog for CS 443 this week I decided to look up blogs about levels of testing. While I was searching the web, I found a blog testlodge by Jake Bartlett he wrote a blog post titled “Levels of Testing In Software Engineering” here he talks about the levels of testing in software engineering. There are 4 levels of testing he talks about. Unit testing, integration testing, system testing, and acceptance testing. The first testing that most people do is unit testing. It involves testing pieces of code to make sure each one is right. With unit testing it helps verify internal design and internal logic, internal paths, as well as error handling. Unit testing is usually done by the developer who wrote the code. The second level of testing is called integration testing. This level of testing test how well each of the code works together. Each class is usually combined and tested as a group. This way it identifies interface issues between modules. The third test is called system testing with this kind of testing it test the entire application. This is done in a test kind of environment where the program would be sent out to. With this kind of test, the application is tested from beginning to end. This test is usually done by the testing team and includes a combination of automated testing and manual testing. Finally, the last test is called accepting testing. With this level of testing it test if the software is ready to be released. This kind of testing is mostly done by the business user and end user. With these levels of testing it show that testing is not just a onetime thing it is multiple test just like my other blog talks about. You have to make the right kinds of test and test often.

I chose this blog because I wanted to stay on the same topic I did for my last blog and keep with testing. I liked this blog a lot because it makes things easy and clear to understand and breaks each testing in to different levels and gives a clear description of what each of the testing is about. With testing ideas, I learned that you will never have enough tests. So, to make sure you are efficient when testing you have to break down your testing into different levels. I think the blog will help me a lot in the future because I will be testing a lot of code for class, school, work, and personal projects. Know what to these how to test and when to test is the best way to use my time efficiently.

 

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

10/2/17 Coding

 

 

This is another video from Joel Spolsky. I found this video through the last blog entry from last week. In this video he talks about the impact of coding in everyday life. He uses a taxi as an example of how coders deal with coding. he mentions if the person tries to make the taxi turn right, instead of the taxi turning right, it might have the trunk pop open or the taxi turn in the opposite direction. The driver will ask what’s wrong and try to figure out the problem. The driver will go online and find another driver had the same problem asked the question then was given the answer.  The driver could use the answer to solve his problem. Before stack overflow, there was a site online where programmers post questions to a coding issue, then would have to pay the company money to see their own answers that they have written up, Stack overflow was created where programmers can write questions to the program they have a problem on and other programmers can answer. Those answers are rated by other programmers who use the site. Those ratings can help a programmer build their reputation as a programmer. This could possible lead to jobs as a programmer in the future. Programmers need every detail of instruction for the program to run properly. Like mentioned before, algorithms are used in software design to run programs on websites. These algorithms allow a site to post certain pictures, articles and other posts, based on what the user is searching for or their feelings towards a certain topic or event.

The video was interesting. Joel uses everyday trends such as Uber and Facebook to explain how coding works in general and how it is used in everyday life now. I picked this video because I really liked the last video, and video was similar to the last one. The last video talked about programming and coding effecting the future of people. This video talked about coding impacting everyday life of today. This gave me a better  idea of how a website work and how a program runs. Again this shows me what expect in the workforce of a programmer. Joel compared the early days of programmers working similar to working at an assembly line. Programmers were hired to create a program write it and run it, and doing it in small cubicles with computers that did not work properly. Now a days programmers work with he company on the spot to make sure the program runs properly and fix and problem as they arise. This gave me a better understanding on how algorithms work on a site and how to use them for when I create a site and run it.

 

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

Single Statement Unit Tests: Making tests more object oriented

In a post by Yegor Bugayenko, Single Statement Unit Tests,

“..I believe, can help us make our tests, and our production code, more object-oriented. Here it is: a test method must contain nothing but a single assert.”

He makes use of the assertThat() that is available from Hamcrest. Benefits to using assertThat() are: Reusability. Classes needed to create test assertions are reusable in other test methods and test cases. Brevity. Shorter and readable code that’s easy to understand. Readability. Using a single assert, the intent of the test will always be apparent. Immutability. No need for setters or getters if we limit use of algorithmic code in tests.

He uses and example method RandomStreamTest from OpenJDK 8, created by Brian Goetz:

@Test
public void testIntStream() {
final long seed = System.currentTimeMillis();
final Random r1 = new Random(seed);
final int[] a = new int[SIZE];
for (int i=0; i < SIZE; i++) { a[i] = r1.nextInt(); } final Random r2 = new Random(seed); final int[] b = r2.ints().limit(SIZE).toArray(); assertEquals(a, b); }

In this example there are two parts, the algorithm which creates two arrays of integers and the assertion which compares them using assertEquals(). The author recommends modifying the code to look like this:

@Test
public void testIntStream() {
final long seed = System.currentTimeMillis();
assertEquals(
new ArrayFromRandom(
new Random(seed)
).toArray(SIZE),
new Random(seed).ints().limit(SIZE).toArray()
);
}
private static class ArrayFromRandom {
private final Random random;
ArrayFromRandom(Random r) {
this.random = r;
}
int[] toArray(int s) {
final int[] a = new int[s];
for (int i=0; i < s; i++) { a[i] = this.random.nextInt(); } return a; } }

The change is the test is that there is only one statement in the method now.

Yegor notes

"The biggest benefit we get when this principle is applied to our tests is that they become declarative and object-oriented, instead of being algorithmic, imperative, and procedural."

I chose this resource because it's an interesting way to design tests and the benefits of using assertThat() might be of use to me in the future. I think it is important to keep up on the best unit-testing practices if I want to write good code to match. I'm also interested in looking more into Hamcrest.

Using assertThat() allows you to write relatively short test cases that are clear what is being tested. Sometimes tests can become bogged down with too many assertEquals() and setters and getters. Using assertThat() allows you to simply compare two immutable objects. I plan on using this, or at least trying to implement it whenever writing tests in the future along with whatever makes writing tests more readable, understable and object oriented.

The post Single Statement Unit Tests: Making tests more object oriented appeared first on code friendly.

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

Observer

The Observer pattern is very commonly used and is one of the Gang of Four design patterns which are meant to solve design problems and create reusable object-oriented software.

The book chapter from the book Game Programming Patterns by Robert Nystrom on the Observer pattern provides an example of its use in specifically game design (an achievement system), however its implementation remains the same as it would in any other type of software. The pattern essentially allows communication between systems without having to couple them together. It does this by creating observers that receive notifications from the subjects that their observing and sharing that information.

In the example provided by the chapter, it shows how a physics system can communicate to an achievement system to unlock an achievement where the player falls off a bridge:

observer

It does this without having to couple the two systems together and eventually creating a huge mess of code.

The author then goes on to describe some concerns and potential problems of using the patterns, such as speed and memory allocation, as well as their solutions. Although even if you implement this or any design pattern correctly and efficiently, it doesn’t mean that it’ll work well depending on whether or not it’s applied on the right problem.

I chose this chapter in particular because it’s likely that we will be using this pattern in the future. Also I think it’s interesting to see how these design patterns can be used in game development, so it may be useful to others who are interested in developing games. I used this pattern in the past for a system where the physics system would notify the observer when a collision happened and it would tell the sound system to play the sound for that collision. I ended up running into a lot of problems due to my poor implementation of the pattern, getting errors because of improper memory allocation. Referencing the examples from this chapter helped me learn how to fix these issues and optimize my code. However, while using the Observer pattern for my audio system worked properly, I ended up doing it differently afterwards using a service locator to provide a global point of access to the audio system as well as an event queue to prevent multiple instances of the same sound from playing at once and blowing out my ears. Although I wouldn’t use the Observer pattern in this situation again, it’ll probably be useful in the future.

Source: http://gameprogrammingpatterns.com/observer.html

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