Author Archives: erik

Java: The Factory Method Pattern

In this blog post, Justin Albano talks about the Factory Method Pattern and gives us an example.

The Textbook Definition

According to the Gang of Four book that defined the technique, the intent of the Factory Method pattern is as follows:

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Using the Factory Method involves creating two sets of interfaces: “(1) the product interface that constitutes the object to be created and (2) the creator interface that constitutes the object that will instantiate the product.” The UML diagram for the Factory Methods is below:

The author explains the UML diagram as the following:

Using the general pattern, we build a Creator interface, which includes one or more Factory Methods, as well as any number of other methods. This interface may also be an abstract class with defined methods or even a default implementation of the Factory Method that returns a default instance of Product. From this interface, a set of ConcreteCreator classes are created that return desired ConcreteProduct instances that implement the Product interface.

An Example in Java

  • We create an encryption mechanism that allows the user to supply a string of text and a file name, which is then encrypted and written to disk. Using the Factory Method allows us to use multiple encryption algorithms.
  • We create implementations for two encryption algorithms: (1) SHA-256 and (2) SHA-512. “For both implementations, we will use the Apache Commons encryption implementations (org.apache.commons.codec.digest.DigestUtils).”
  • In the end you should be able to do something like this:
    PersistedFile file =
       new PersistedFile("/foo/bar/text.txt", "Hello, world!", new Sha256Encryptor());

    View complete example here

    Colloquial Definition

    A method whose sole responsibility is to abstract the creation process of an object and return that object.

    I chose this resource because I am interested to learn new implementations of popular design patterns such as the Factory Method. This resource gave a detailed explanation along with other patterns that can be good alternatives to the Factory Method pattern like the Template Method pattern and Strategy Pattern. I believe the content of the article is very detailed and informative. The example they used is very interesting and I’m going to implement the code myself to test it out. I plan to use this and many other design patterns in the future. I learned more about the Factory Pattern method and when it is appropriate to use it.

    The post Java: The Factory Method Pattern 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.

    Code Quality: Fighting Primitive Obsession Code Smells

    In this blog post, Anna Makowska talks about primitive obsessions code smells and what you can do to fix them. The author chose to focus on primitive bbession code smell because some smells are harder for developers to detect intuitively.

    “Primitive data types are basic built-in building blocks of a language. They’re usually typed as int, string, or constants. As creating such fields is much easier than making a whole new class, this leads to abuse. Therefore, this makes this smell one of the most common ones.”

    Examples

    • Using primitive data types to represent domain ideas. For example, using an integer to represent an amount of money or a string for a phone number.
    • Using variables or constants for coding information. An often-encountered case is using constants for referring to users roles or credentials (like const USER_ADMIN = 1).
    • Using strings as field names in data arrays.

    Consequences

    • Code becomes less flexible because of use of primitives instead of objects.
    • Primitive data types are much harder to control. As a result, we may get variables that aren’t valid (supported by the type) or meaningful.
    • Primitives are often related to dedicated business logic. Therefore, leaving this logic unseparated may violate the Single Responsibility Principle and the Open/Closed Principle.
    • When data type logic is not separated in a dedicated class, adding a new type or behavior makes the basic class grow and get unwieldy.
    • By using primitives, the developer loses the benefits that come with object-oriented design, like data typing by class name or type hinting.

    Replace Data Value With Object

    • Instead of a set of primitive values, the programmer has full-fledged classes with all the benefits that object-oriented programming has to offer (typing data by class name, type hinting, etc.).
    • There is no need to worry about data validation, as only expected values can be set.
    • When relationship logic extends, it will be placed in one place dedicated to it.

    I chose this resource because it had plenty of good information on the primitive obsession code smell, when it’s going to lead to problems and how to fix that. I learned two more fixes, Replace Type Code With Subclasses, State, or Strategy (patterns) and Replace Array With Object for when “values of a coded type aim to control the behavior of the program.” I felt the content to be quality content from a author who has experience with spotting and fixing code smells. I will use this information in the future, by keeping an eye out for primitive obsession code smells.

    The post Code Quality: Fighting Primitive Obsession Code Smells 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.

    What Is Project Valhalla?

    In this blog post, Justin Albano explains what Project Valhalla is.

    “Project Valhalla is an OpenJDK project started in 2014 and headed by Brian Goetz with the purpose of introducing value-based optimizations to Java Development Kit (JDK) 10 or a future Java release. The project is primarily focused on allowing developers to create and utilize value types, or non-reference values that act as though they are primitives. In the words of Goetz: Codes like a class, works like an int.”

    “Project Valhalla has a very specific purpose: To cease the requirement that Java developers choose between performance and abstraction.”

    What Are Value Types?

    “Value types are groups of data whose immediate value is stored in memory, rather than a reference (or pointer) to the data.” Doing this means saving memory otherwise taken up by overhead data. “Taking data and directly placing its value into memory (rather than a reference) is called flattening and its benefits are more acutely demonstrated with arrays.” “In an array of value types, the values are directly placed into the array and are guaranteed to be in contiguous memory (which increases locality and, consequently, the chance of cache hits). This idea is illustrated in the figure below:

    The benefits to using Value Types are listed by the author:

    • Reduced memory usage: There is no need for additional memory used to store object metadata.
    • Reduced indirection: Because objects are stored as reference types in Java, each time you access it, it first must be dereferenced, causing additional instructions to be executed.
    • Increased locality Using flattened value objects removes indirection, increasing likelihood values are adjacently stored in memory.

    One of the major differences between reference types and value types:

    “The identity of a reference type is intrinsically bound to the object while the identity of a value type is bound to its current state”

    The reason I picked this resource is because I did not know about Project Valhalla and it seemed like an interesting article to learn about. It’s not quite ready to be released in JDK but it’s a useful addition to Java that increasing performance and saves memory. I feel the content of the post was interesting and informative. I learned the benefits of using Value Types versus using pointers and the improvements that have been made to Java. Value Types may soon be released in an upcoming JDK and I would like to know how to utilize them when saving memory is crucial.

    Additional resource: Minimal Value Types article

    The post What Is Project Valhalla? 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.

    Creating Your Code Review Checklist

    In this blog post, Erik Dietrich goes over creating a code review checklist. If you were to Google “Code review checklist”, the author lists results that may show up:

    • Does every method have an XML comment?
    • Do classes have a copyright header?
    • Do fields, methods, and types follow our standard naming convention?
    • Do methods have too many parameters?
    • Are you checking validity of method parameters?
    • Does the code have “magic” values instead of named constants?

    He then goes on to list two problems with going through a sometimes lengthy checklist:

    • You can’t keep 100+ items in your head as you look at every method or clause in a code base, so you’re going to have to read the code over and over, looking for different things.
    • None of the checks I listed above actually require human intervention. They can all be handled via static analysis.

    His suggestion for stream-lining the process of going through a big checklist is to automate the easy stuff. “Get static analysis tools that developers can install in their IDEs and run prior to delivering code, which will flag violations as errors or warnings. Get static analysis tools that run on the build machine and fail the build for violations.”

    Code Review for the Important Stuff

    The author lists an example checklist for a code author:

    • Does my code compile without errors and run without exceptions in happy path conditions?
    • Have I checked this code to see if it triggers compiler or static analysis warnings?
    • Have I covered this code with appropriate tests, and are those tests currently green?
    • Have I run our performance/load/smoke tests to make sure nothing I’ve introduced is a performance killer?
    • Have I run our suite of security tests/checks to make sure I’m not opening vulnerabilities?

    The author lists an example checklist for a code reviewer

    • Does this code read like prose?
    • Do the methods do what the name of the method claims that they’ll do? Same for classes?
    • Can I get an understanding of the desired behavior just by doing quick scans through unit and acceptance tests?
    • Does the understanding of the desired behavior match the requirements/stories for this work?
    • Is this code introducing any new dependencies between classes/components/modules and, if so, is it necessary to do that?
    • Is this code idiomatic, taking full advantage of the language, frameworks, and tools that we use?
    • Is anything here a re-implementation of existing functionality the developer may not be aware of?

    I chose this resource because it had very useful information on code review, which ties into QA. I feel the content of the article is very informational and useful to my future career. It is a good starting point for making sure you have thoroughly checked the quality of your code and automated tests are only going to increase in use, so it makes sense to automate what you can.

    The post Creating Your Code Review Checklist 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.

    API Design with Java 8

    In this blog post, Per-Åke Minborg talks about the fundamentals of good API design. His inspiration for writing this article is a blog post by Ference Mihaly which is essentially a check-list for good Java API design.

    “API combines the best of two worlds, a firm and precise commitment combined with a high degree of implementation flexibility, eventually benefiting both the API designers and the API users.”

    Do not Return Null to Indicate the Absence of a Value

    Using the Optional class that was introduced in Java 8 can alleviate Javas problem with handling nulls. An example below shows the implementation of the Optional class.

    Without Optional class

    public String getComment() {
    
        return comment; // comment is nullable
    
    }


    With Optional class

    public Optional getComment() {
    
        return Optional.ofNullable(comment);
    
    }

    Do not Use Arrays to Pass Values to and From the API

    “In the general case, consider exposing a Stream, if the API is to return a collection of elements. This clearly states that the result is read-only (as opposed to a List which has a set() method).”

    Not exposing a Stream

    public String[] comments() {
    
        return comments; // Exposes the backing array!
    
    }

    Exposing a Stream

    public Optional getComment() {
    
        return Optional.ofNullable(comment);
    
    }

    Consider Adding Static Interface Methods to Provide a Single Entry Point for Object Creation

    Adding static interface methods allows the client code to create onjects that implement the interface. “For example, if we have an interface Point with two methods int x() and int y(), then we can expose a static method Point.of(int x, int y) that produces a (hidden) implementation of the interface.”

    Not using static interface methods

    Point point = new PointImpl(1,2);

    Using static interface methods

    Point point = Point.of(1,2);

    I selected this resource because it relates to design principles, and it’s something that I do not know well. I would like to learn more about APIs and good practices for designing them using Java. The article had useful information and topics that I didn’t know well. A few more pointers from the article I learned:

    • Favor Composition With Functional Interfaces and Lambdas Over Inheritence – Avoid API inheritance, instead use static interface methods that take “one or several lambda parameters and apply those given lambdas to a default internal API implementation class.”
    • Ensure That You Add the @FunctionalInterface Annotation to Functional Interfaces – signals that API users may use lambdas to implement the interface
    • Avoid Overloading Methods With Functional Interfaces as Parameters – Can cause lambda ambiguity on the client side.

    I would like to learn more about using AWS Lambdas, and learning more about APIs in general. I plan to use this information if I am ever to work on Java APIs which is possible. I want to make sure I have the best practices and the check list mentioned in the start of the article seems like a good starting point.

    The post API Design with Java 8 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.

    Java: The Strategy Pattern

    In this blog post, Justin Albano talks about the basic Strategy pattern and the “fundamental principles that make for solid strategy implementations.” He also goes into the use of Dependency Injection (DI) “to select a strategy implementation” along with a walkthrough of a basic payment system using the Strategy pattern.

    The purpose of the Strategy pattern is “to decide the algorithm used in a specific context” by encapsulate algorithms into classes with the same interface, and by using the same interface, we allow the algorithms to be interchangeable based on what is needed. The following is a UML class diagram of the Strategy pattern:

    The way the author makes sense of the Strategy pattern is to see the Context class as a desk, “where the Strategy interface represents a slot in the desk that accepts drawers” and each the concrete strategy implementations “can be thought of as actual drawers, where some are completely undivided, and others have various divider configurations; some may be good at storing papers, while others may be better at organizing pens, pencils, and paper clips. Each serves its own purpose and excels in a specific context, but vary only in their internal configuration: The external configuration of each drawer is the same so that it can be accepted by the desk.”

    I selected this article because I wanted to learn more about the Strategy patterns, and design patterns as a whole. This post had topics that I didn’t know about like Dependency Injection, using the Introduce Parameter Object refactoring technique. It also goes well into detail an implementation of a payment system showing both the Strategy pattern and Factory pattern. I feel my knowledge of the Strategy pattern has improved after reading this article, and seeing it implemented in a new way helps me understand it more. The author is very detailed and explains the topic clearly. I learned about the importance of selecting the appropriate strategy, whether it’s more appropriate to have a run-time selection (a conditional run-time selection will require logic whose complexity is proportional to the number of possible concrete strategies) or a static selection (Strategy is selected once when the application starts-up and is never reinitialized for the duration of the execution of the application. I plan on using the Strategy pattern when I am developing software, the Strategy pattern has many uses in the world of software development and will continue to be utilized.

    The post Java: The Strategy Pattern 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.

    Unit-Test Smells: What To Look Out For

    In this blog post, Erik Dietrich talks about unit-test smells. Like code smells, it’s an indicator of something that just isn’t right and could lead to big problems when debugging.

    1. Tests Are Difficult to Write This is usually because the code you are testing is confusing or not “clean”. The solution to this problem is to have clean testable code.

    2. You Do Weird Things to Get at the Code Under Test The author notes the overuse of things like reflection schemes to invoke and test private methods and using the “Internals Visible To” attribute to expose test methods, this makes things complicated and your unit-tests brittle because you lose the flexibility of the methods by testing the internal details. Testing this way is an indicator that you could be creating iceberg classes, or encapsulating too much all in one place.

    3. Excessive Mocking Important concept used to speed up unit-testing but using it excessively can indicate design problems.

    4. Context Logic in Production Code, the author notes the code below:

    public static void SaveToDatabase(Customer customerToWrite)
    {
        if (AreWeTesting)
            WriteWithMockDatabase(customerToWrite);
        else
            Write(customerToWrite);
    }

    and see’s this as context logic because “your production code becomes aware of the context in which it is used. This makes your code really brittle, and, frankly, it adds clutter.”

    5. Slow Running Tests Slow tests lead to those tests not being run as much as other tests, this can also indicate you’re doing something wrong like accessing a database or writing a file. It could also be an indication of an inefficient piece of code.

    6. Intermittent Test Failures There may be cases when a test fails once in a blue moon, the author advises not ignoring the anomaly, but to figure out exactly when and why it fails.

    The reason I selected this resource is because it has interesting information from someone who works with various organizations doing unit-testing. The author seems to have a lot of experience in the field of software testing and knows the in-and-outs and dos-and-donts when it comes to unit-testing. I learned some good tips on what unit-test smells to look out for when unit-testing software. Tests that are hard to write, test where you have to bypass and invoke private methods to test, excessive mocking, using context logic in production code, slow running tests, and intermittent test failures. A lot of this information will benefit me, as it is good practice when writing good unit-tests. I expect to use this information in my professional career as a reminder to write clean testable code and write unit-tests with these smells in mind.

    The post Unit-Test Smells: What To Look Out For 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.

    The Technical Skills You Need to Have as a Software Developer

    In this blog post, John Sonmez talks about “soft skills” and how they can help you become a better software developer. Here are some tips from the author:

    1. Instead of trying to learn several programming languages at the same time it’s better to have one language that you know in and out, that you are comfortable writing.
    2. Structure your code well by writing “good, clear, understandable code that doesn’t require a large amount of comments because the code itself is communicative.” – John Sonmez
    3. Having a good understanding of object-oriented design and managing complexity as most popular languages rely heavily on object-oriented design and analysis.
    4. Understanding how to create algorithms, and how to modify known algorithms to match your specific needs.
    5. Understanding of data structures like arrays & vectors, linked-list, stacks, queues, trees, hashes and sets. These are important to know well, especially if you are being interviewed.
    6. Knowing a development platform well is a good idea because some places design for specific platforms (PC, Mac, etc)
    7. Learning a framework, or a complete stack. “A framework is simply a set of libraries that are used to develop code on a particular platform or on multiple platforms.” and “A stack is a set of technologies, usually including a framework, that are commonly used together to create a full application.”
    8. Basic Database Knowledge, how to add, modify, delete and work with different database systems.
    9. Source Control, understanding how to use tools like GIT.
    10. Testing, more often projects are being created in small increments and tested as they go, this is allowing developers to catch bugs before they begin to cascade.

    I chose this resource because I’m always looking for information on becoming a better software developer and want to become an asset to wherever I dedicate my work. Some of the information is general information but I do think it’s important to work on maintaining these core skills to improve the quality of your work. I learned the importance of working on knowing at least one language very well, along with knowing one platform very well knowing how to implement popular data structures, writing good algorithms and knowing when to use what. I learned the importance of object oriented design and how prevalent it is today. I learned about frameworks and stacks and what they are, and the importance of understanding how databases work. I also learned that more recently developers are being expected to know how to test their code, especially with agile testing.

    The post The Technical Skills You Need to Have as a Software Developer 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.

    How to Work With Someone Else’s Code

    In this blog post, Justin Albano gives advice on working on code written by others. It can be tough making changes or adding to code that you did not write yourself, another reason why clean code is so important, it helps other have a clear idea of what’s going on. The author notes pitfalls that you should watch out for when working with someone else’s code:

    Our Ego: We think we know best, but must respect the code and original author.
    The ego of the original author: Working on code written by someone else may lead to questioning decisions made by others which must be met with working with the original author.
    Fear of the unknown: Many times you are going to be working on code that you know very little about and will be responsible for those changes. It’s important a framework is built to ensure changes can be made comfortably with no worry.

    Some techniques for maintaining clean, functional code:

    1. Ensure Tests Exist When current tests are not sufficient, you must create them yourself, which can be challenging. Other times, having tests provided for you, you can learn from the tests what the intent of the code is.
    2. Talk to the Person Who Wrote It Communication is key, if you have the chance to talk to the author of the code you’re working on you can get some insight if you’re having trouble.
    3. Remove All Warnings This ensures quality of code, and reduces code rot.
    4. Refactor Changing the internal structure to make it easier to understand without modifying behavior.
    5. Leave it Better Than You Found It Do your due diligence when it comes to maintaining quality for you, and future people working on the same code.

    I chose this resource because it gives advice on working with other people’s code, working with existing test cases, or adding your own. It reinforces the idea of clean code because you should leave the code better shape than you found it (if that’s possible). I feel the article had some good information that I will definitely use in the future. I will be working with code that was written by someone else, and will need to write test cases for changes made to the code and maintain it still functions the same. I learned techniques for dealing with code written by others, and doing my best to respect the original purpose of the code.

    The post How to Work With Someone Else’s Code 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.

    Clean Code Principles

    In this blog post, Marcus Biel gives his thoughts on clean code, what that is, how to implement, estimate, and accurately design good software that does exactly what it should and nothing more. What is clean code? The author writes,

    “It’s the idea that your code should be precise and as close to perfect as possible. If you have more code than you need, it shouldn’t be there.”

    This concept relates to YAGNI (you ain’t gunna need it), and is an essential part of having clean and readable code. Adding features that might be needed later is a good way to bloat your code and run into bugs. Clean code requires time to fully understand the problem, this is sometimes tough when working in an environment where you are being pushed by those who don’t understand what goes into software design. Sometimes you will be asked to meet deadlines that will make you rush, in turn you can end up with poorly written code. The language and wording in code is also very important, using variables and names that are clear and make sense help others read and understand what is going on in your code. I selected this resource because having clean code is a huge part of being a good programmer, along with tips on clean code, the author has tips on designing code by running tests first, working with co-workers and clients to understand what features are most important, and what features are not beneficial.

    “To me, being a software craftsman is about having a focused attitude and about taking responsibility for your code, your job, and your time. So, from beginning discussions to end results, your one focus should be on maintaining your own high standards and creating the best possible product for your client.” – Marcus Biel

    This post had a good amount of information and insight on clean code, and being a good developer in general. Important aspects from the post I think are being clear when naming variables, methods, and classes, leaving out code that is not needed (YAGNI), and making accurate timelines for projects. Rushing to write code before you fully understand the problem can lead to more problems down the road. I expect to use concepts of clean code in my professional career, I believe it’s very important to make a good product that will benefit you, your company, or your client.

    The post Clean Code Principles 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.