Category Archives: Week 10

CS@Worcester – Fun in Function 2017-11-20 21:07:22

The article this blog post is written about can be found here.

I decided this week to research the Law of Demeter, also known as the principle of least knowledge. I chose this article specifically to write about because it provides a source code example in Java, it gives examples of the sort of code that the Law of Demeter is trying to prevent, and it explains why writing code like that would be a bad idea.

The Law of Demeter, as applied to object-oriented programming, is a design principle consisting of a set of rules about which methods an object should be able to call. The law states that an object should be able to call its own methods, the methods of arguments that are passed to the object as parameters, the methods of objects created locally, the methods of objects that are instance variables, and the methods of objects that are global variables. The general idea behind it is that objects should know as little as possible about the structure or properties of anything besides itself. More abstractly, objects should only talk to their immediate friends, not to strangers. Adhering to the Law of Demeter creates classes that are loosely coupled, and it also follows the principle of information hiding.

The sort of code that the Law of Demeter exists to prevent are chains of function calls that look like this:

objectA.getObjectB().getObjectC().doSomething();

The article explains that this is a bad idea for several reasons. ObjectA might get its reference to ObjectB removed during refactoring, as ObjectB might get its reference to ObjectC removed. The doSomething() methods in ObjectB or ObjectC might change or get removed. And since your classes are tightly coupled when you write code like this, it will be much harder to reuse an individual class. Following the law will mean your classes will be less affected by changes in other classes, they’ll be easier to test, and they will tend to have fewer errors.

If you want to improve the bad code so it adheres to the Law of Demeter, you need to pass ObjectC to the class containing the original code in order to access its doSomething() method. Alternatively, you can create wrapper methods in your other classes which pass requests onto a delegate. Lots of delegate methods will make your code larger and slower, but it will also be easier to maintain.

Before reading this article, seeing a chain of calls like that probably would have made me instinctively recoil, but I wouldn’t have been able to explain exactly what was wrong. The bad examples given in this article clarified the reasons why code like that is weak. The article also gave me concrete ways I can follow the Law of Demeter in future code.

From the blog CS@Worcester – Fun in Function by funinfunction and used with permission of the author. All other rights reserved by the author.

Blog 6

Soft Qual Ass & Test

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

CS@Worcester – Fun in Function 2017-11-20 19:03:56

The blog post this is written about can be found here.

I picked this blog post because because we’ve been utilizing mock objects in class lately, and this post explains in-depth the logic behind using them in addition to succinctly summarizing the different types of mock objects.

Using mock objects focuses a test on the specific code we want to test, eliminating its dependencies on other pieces of code we don’t care about at the moment. This way, if a test fails, we can be sure it’s because of a problem in the code under test and not in something called by it. This greatly simplifies searching for faults and reduces time spent looking for them.

Mock objects also serve to keep the test results consistent, especially when the real object you’re creating a mock of can undergo unpredictable changes. If you utilize a changing database, for instance, your test might pass one time and then fail the next, which gives you no useful information.

Mock objects can also reduce the time necessary to run tests. If code would normally call outside resources, running hundreds of tests which utilize the actual code could take a long while. Mocks of these resources would respond much more quickly. Obviously we want to test calls to the actual resources at some point, but they aren’t necessary in every instance.

“Mock” is also used as a generic term for any kind of imitation object used to replace a real object during testing, of which there are several. Fakes return a predictable result, but the result isn’t based on the logic used to obtain a result in the real object. Stubs return a specific result in response to specific input, but they aren’t equipped to handle other inputs. Stubs can also retain information about how they were called, such as how many times and with what data. Mocks are far more sophisticated versions of stubs which will return values in similar ways, but can also hold expectations about how many times each method should be called, in which order, and with what data. Mocks can ensure that the code we’re testing is using its dependencies the exact way we want it to. Spies replace the methods of the real object a test wants to call instead of acting as a stand-in for the object. Dummies are objects that are passed in place of another object, but never used.

Creating the most sophisticated type of mock seems like it might take more time than it’s worth, but existing mocking frameworks can take care of most of the work of creating mock objects for your tests.

In the future I expect to write tests that utilize mocking. This post, along with Martin Fowler’s article, has given me a good starting point in being able to utilize them effectively as well as decide how elaborate a mock needs to be for a particular test.

From the blog CS@Worcester – Fun in Function by funinfunction and used with permission of the author. All other rights reserved by the author.

CS@Worcester – Fun in Function 2017-11-20 17:12:09

The blog post this information is sourced from can be found here.

I chose this blog post because it briefly summed up the general responsibility assignment software patterns, which I wanted to learn about. GRASP are patterns that serve as guidelines to which classes or objects should be assigned responsibilities. There are nine patterns in total.

A general method for deciding which class to assign a responsibility to is to assign it to the information expert: the class that has the necessary information to carry out the responsibility in full.

When trying to decide which object should be responsible for creating new instances of a class, the Creator pattern says that the responsibility of creating Class A instances should be assigned to Class B if Class B contains instances of Class A or gathers instances of Class A into one place, if Class B keeps a record of Class A objects, if Class B is closely associated with Class A objects, or if Class B has all the information necessary to create a Class A object – that is, it’s an information expert about the responsibility of creating Class A objects.

The controller pattern answers the question of what should handle input system events. Controllers can represent the entire system, device, or subsystem, in which case they’re referred to as façade controllers. They can also be use case or session controllers, which handle all system events of a use case. The controller doesn’t itself do the work, but instead delegates it to the appropriate objects and controls the flow of activity.

The low coupling pattern holds that responsibilities should be assigned in such a way that coupling remains as low as possible – that is, there is low dependency between classes, high reuse potential, and changes in one class have a low impact on other classes

High cohesion means the responsibilities in a class are highly related or focused on a single goal. The amount of work one class does should be limited, and classes shouldn’t do lots of unrelated things.

If behavior varies based on type, polymorphism holds that the responsibility of defining that variation should be assigned to the types for which the variation occurs.

Pure fabrication classes exist to maintain high cohesion when assigning responsibilities based on the information expert pattern would not. They don’t represent something in the problem domain.

Indirection maintains low coupling by assigning mediation responsibilities between two classes to an intermediate class.

The protected variations pattern assigns responsibilities that create a stable interface around points of likely variation or instability to protect other parts of the system from being affected by any variation/instability.

This post gave me ideas I can refer back to when solving the problem of which of several classes should be assigned a particular responsibility. The problems addressed by these design patterns exist in just about every software development project, so there’s no doubt I will find it useful in the future.

From the blog CS@Worcester – Fun in Function by funinfunction and used with permission of the author. All other rights reserved by the author.

#6_343

From the blog CS@Worcester – Not just another CS blog by osworup007 and used with permission of the author. All other rights reserved by the author.

The Decorator Pattern

Today I will be talking about the decorator pattern. I found a blog on the decorator pattern by Bambielli’s Blog. The decorator pattern, according to the blog, allows objects to have new responsibilities at runtime without changing any code in their underlying classes. The blog writer then makes a point to favor composition over inheritance because it can reduce the frequency of runtime errors. It also conforms to the “open for extension closed for modification” rule of good programming. Decorating a class is essentially extending objects to add functionality at runtime. This allows things to be more current and up to date for user demands. In the UML diagram provided by the blog, the abstract decorator class extends the abstract component, which gives the abstract decorator the implementations to be used in place of the component implementations. The decorator classes extend the abstract decorator class, and provide the abstract decorator class with the current overriden methods.

 

The blog uses a pizza shop as an example. Pizza can come in a variety of toppings and crusts. The decorator pattern allows us to construct any combination of pizza toppings. Concrete classes DeepDish and ThinCrust extend Abstract Class Pie. The decorator pattern comes into effect with the topping decorator. The Abstract Class ToppingDecorator extends Abstract Class Pie, and the ToppingDecorator class has two decorators, PepperoniDecorator and CheeseDecorator.

 

The blog points out some disadvantages to the decorator pattern, one being that decorating objects manually is a hassle due to the large number of parameters to pass. The solution to this? Use the factory pattern in combination with the decorator pattern to make the objects for you, eliminating you having to manually pass all the parameters.

 

I chose this pattern because I am always looking to learn how to improve my code and make it  more efficient. Learning different design patterns is a great way to help my cause. The only thing about design patterns is that they aren’t always widely applicable. Most design patterns are specific for a small number of cases, so learning more design patterns helps me to overcome more situations that I face when coding. I think this blog really helped my understanding of the decorator pattern. I had looked at a few before this one, and the decorator pattern seemed to be pretty vague to me. The pizza example in this one really helped solidify my understanding of this pattern. All the examples from the other blogs had lots of code samples, and not a lot of explanation. Though simple and basic, I really liked the pizza topping example. I hope to apply this in future practice. I would like to have a program that allows users to make a number of different combinations (such as a sandwich topping program, or a car customizer program (color, size, etc.)). This pattern seems to be really effective with being able to create whatever combination of choices the user asks for.

 

Here’s the link: http://www.bambielli.com/posts/2017-04-02-decorator/

 

From the blog CS@Worcester – The Average CS Student by Nathan Posterro and used with permission of the author. All other rights reserved by the author.

Test Automation

This week I read on article on Automated Testing. The article explains why Test Automation software is the best way to increase the effectiveness, efficiency and coverage of our software testing. As per the article, an automated testing tool is able to playback pre-recorded and predefined actions, compare the results to the expected behavior and report the success or failure of these manual tests to a test engineer. Once automated tests are created they can easily be repeated and they can be extended to perform tasks impossible with manual testing. Because of this, savvy managers have found that automated software testing is an essential component of successful development projects. Some of the major merits of using Automated Testing over the Manual software testing are:

Automated Software Testing Saves Time and Money: Once created, automated tests can be run over and over again at no additional cost and they are much faster than manual tests. Automated software testing can reduce the time to run repetitive tests from days to hours. A time savings that translates directly into cost savings.

Vastly Increases Your Test Coverage: Automated software testing can increase the depth and scope of tests to help improve software quality. Lengthy tests that are often avoided during manual testing can be run unattended. They can even be run on multiple computers with different configurations. Automated software testing can look inside an application and see memory contents, data tables, file contents, and internal program states to determine if the product is behaving as expected. Test automation can easily execute thousands of different complex test cases during every test run providing coverage that is impossible with manual tests.

Testing Improves Accuracy: Even the most conscientious tester will make mistakes during monotonous manual testing. Automated tests perform the same steps precisely every time they are executed and never forget to record detailed results. Testers freed from repetitive manual tests have more time to create new automated software tests and deal with complex features

Automation Does What Manual Testing Cannot: Even the largest software and QA departments cannot perform a controlled web application test with thousands of users. Automated testing can simulate tens, hundreds or thousands of virtual users interacting with a network, software and web applications.

Automated QA Testing Helps Developers and Testers: Shared automated tests can be used by developers to catch problems quickly before sending to QA. Tests can run automatically whenever source code changes are checked in and notify the team or the developer if they fail. Features like these save developers time and increase their confidence.

Source: https://smartbear.com/learn/automated-testing/

From the blog CS@Worcester – Not just another CS blog by osworup007 and used with permission of the author. All other rights reserved by the author.

Post #12

Last class, we were divided into teams to begin working on the software technical code review.  I thought it would be useful to look up what kinds of practices are the most effective, with regard to reviewing code.  I found a post by Gareth Wilson entitled “Effective Code Reviews – 9 Tips from a Converted Skeptic” , which explains the intuition behind the process of conducting code reviews and then provides a list of nine tips to help readers get started with their own reviews.  I hope that this article will help me be more effective in my contribution to the team’s overall review.

Wilson begins the post by listing the benefits of coducting code reviews as: it helps you find bugs, it ensures radability and sustainability of code, it spreads understanding of the implementation throughout the team, it helps new teammates get up to speed with the team’s process, and it exposes each member of the team to different approaches.  He explains that many entry level software engineers don’t appreciate the value of code reviews, at first, and that he was no different until he realized that the code reviews he was apart of were being conducted poorly. After gaining some experience and developing new working strategies at different companies, Wilson now feels confident enough to provide advice on how to conduct code reviews effectively.  His nine tips to performing effective code reviews are:

  • Review the right things, let tools do the rest – IDE’s and developer tools are in-place to not only help you troubleshoot problems and assure quality, but also help you notice the small style and syntax errors that are detrimental to readability and uniformity of code.  Knowing this, you should let the tools make note of those problems instead of including them in a code review.  Ensuring that code is correct, understandable, and maintainable is the goal, so that should be the focus of any code review.
  • Everyone should code review – Conducting code reviews spreads the understanding of code implementation, and helps new developers get up-to-speed with the working practices of an organization, so the ivolvement of veteran reviewers and newcomers is equally valued.
  • Review all code – A proper code review means that it was done as thoroughly as possible.  Wilson believes that no code is too short or simple to review, and that reviewing every line of code means that nothing is overlooked, and that you can feel more confident about the quality and reliability of code after a rigorous review of it is done.
  • Adopt a positive attitude – Code reviews are meant to be beneficial experiences and, by heading into them with a positive attitude and responding to constructive criticism appropriately, you can maximize the potential for this.
  • Review code often and in short sessions – Wilson believes that the effectiveness of a code review will begin to dwindle after about an hour, so it is best to refrain from reviewing for any longer than that.  A good way to avoid doing this is to set aside time throughout the day to coincide with breaks, to help form a habit and resolve issues quicker whilst code is still fresh in the head of developers.
  • It’s OK to say “It’s all good” – Not all code reviews will contain an issue.
  • Use a checklist to ensure consistence – A checklist will help to keep reviewers on track.

I think these tips are useful to consider and I hope to apply them in the upcoming code review.

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

Observer Pattern

The Observer Pattern is an example of a behavioral pattern. In object oriented programming, which most of the application nowadays are built of, you cannot talk about it without considering the state of objects. Object oriented programming is all about object interactions. There are cases where objects needs to be informed about the changes of other objects are often. If you want to have a good design, you would want to have to decouple the objects as much as possible for modularity. The observer pattern might be the best pattern for that job.

The Observer Pattern can be used whenever a “subject” needs to be observed by the concrete objects.

Intent:

  • Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

How to Implement Observer Pattern:

  • Observable – interface or abstract class defining the operations for attaching and de-attaching observers to the client. In the GOF book this class/interface is known as Subject.
  • ConcreteObservable – concrete Observable class. It maintain the state of the object and when a change in the state occurs it notifies the attached Observers.
  • Observer – interface or abstract class defining the operations to be used to notify this object.
  • ConcreteObserver concrete Observer implementations

It is pretty simple how it works. After creating your subject class, it will then instantiate your ConcreteObservable class and set the states of the objects. Then the Observer class checks if there are any update or notifications from the subject and then update is  called on to the ConcreteObservers.

 

The observer pattern is used when:

  • the changes in one object also happens in other objects without keeping the object tightly coupled.
  • or when our design needs to be enhanced in the future with new observers with minimal changes.

Common example of Observer Pattern:

  • Model View Controller Pattern – the observer pattern is used in the model view controller(MVC) architectural pattern. In MVC the observer pattern is used to decouple the model from the view. View represents the Observer and the model is the Observable object.

Observer Pattern in UML Diagram:

observerpatternuml

 

I selected this topic because I have read many articles and tutorials about this subject, and since I was making a tutorial about it, I might as well write about it in this blog.

The observer pattern is an exceptional pattern to learn in object oriented design in my opinion. Since, most of the programs written these days are object oriented, it is a good resource to know that when you have a one-to-many dependency between objects, it is useful to use the observer pattern. You can use this pattern to create a notification system for your application.

Reference:

Observer Pattern by OODesign

From the blog cs-wsu – Computer Science by csrenz and used with permission of the author. All other rights reserved by the author.

Getting Experience

As a junior in college majoring in CS, naturally I cannot stop worrying about what is going to happen to me after I finish college. I recognize that I am not the best programmer in my major, there are plenty of colleagues I know with more experience, better grades, and stronger connections that will help move their career down the line. Comparatively, I worry about my own standing in the industry once we all graduate, so what am I to do? Firstly, enough self deprecating, I need some experience.

https://www.quora.com/How-do-you-get-a-programming-job-or-internship-if-you%E2%80%99re-a-sophomore-CS-major-but-dont-have-experience-How-do-you-choose-a-project-and-set-goals-for-it

This link is a question posted on quora.com asking how to get a job as a CS major in college with little experience outside the classroom, with advice from people currently in the field. The first person down the list of answers, Jane Huang, has particularly useful and calming advice. She goes over 5 points explaining how to answer this question, each of which can apply to various people with the same question.

Her first statement is meant to immediately disarm any person panicking and stressing out over what to do. She emphasizes that although it seems like life is hitting us fast, we are still very young and have plenty of time on our hands to gain experience with. She includes that interviewers will cut you some slack generally as they expect you to learn as you go.

Next she states that its very important to learn a framework, any framework. You can get by as long as you know either ruby on rails or django in python, since most frameworks are similar and you can adjust accordingly after you learn at least one. This isn’t a particularly daunting task, you can learn django in about a week if you practice it about three hours a day. It is also important to just start working on a project that you can manage, it doesn’t have to be original or groundbreaking, just finishing a project is good experience and something you can show as knowledge outside the classroom.

Lastly she makes the point that you might not enjoy coding, and should consider another field you might enjoy more. This isn’t meant to demotivate anybody in the field, you can do it if you believe you can do it. Her point is that if you are afraid switching your major too late and hate the idea of having to spend another year in college to make up for it, imagine spending many more years in a field you find you don’t like and dragging yourself to work every day to support yourself or your future family. Conversely, you don’t have to absolutely love programming in order to succeed professionally. It isn’t required that you have an extreme passion for programming, so really don’t think about it too much but don’t commit to it if you honestly don’t like it.

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