Refactoring Desktop Snowfall

Using the refactoring checklist I will attempt to improve the design of  my Desktop Snowfall project

  • Can the code be Tested?  – The application is GUI based application with not a huge amount going on underneath.  Also some of this is subjective ie is the snow realistic? So it is impossible to test for. The current class diagram looks likes this:

  • Do you need a seam?
    • extract methods using protected not private that use the seam.
  • Create Tests

To create the tests I will need to extract the GUI from the other logic e.g generation of the snow. I started by creating an Environment package and an Environment interface that can store the environmental variables, screen size etc. This is then injected into the snowfall class. Additionally a factory pattern could be used for creating the items in the weather. Hence as weather factory interface could created and injected into the snowfall class. For future flexability objects that fall are defined by a Map held by the environment. Keys in the map are the class names of the objects and the int is the percentage occurrence in the environment.  Therefore the amount of objects created is still controlled by the user through the variable renamed from amountOfAnow to theAmountOfWeatherObjects.

I then created implementations and tests for them and I then integrated them into the design.

  • Start with the deepest branch to shortest branch – Refactored
  • Keep changes small and consistently retest. – Refactored
  • Remove complexity – Refactored
  • Methods should not have more than 10 lines of code – Refactored with a couple of instances where a method is 12 lines of code.
  • Replace conditionals with strategy pattern. – Refactored – achieved with introduction of weatherObjects, WeatherFactory and Enviroment interfaces.
  • Remove local variables – Refactored
  • Remove comments – use descriptive method names. – Refactored
  • Remove cryptic or clever code, – Refactored
  • Remove abbreviated code – Refactored
  • Refactor with dependency injection – Refactored used with implementing strategy pattern.
  • Refactor using SOLID
    • Single Responsibility Principle (SRP)
      • All classes now have singular responsibilities
    • Open Closed Design Principle
      • Up to this point I have amended, restructured the program to fit in with design principles. One I have completed this list. I will hold to this more strictly. Which begs the question. Should it have come first or last.
    • Liskov Substitution Principle (LSP)
      • implemented with the WeatherFactory, Environment, WeatherObject and Weather classes.
    • Interface Segregation Principle
      • At present the interfaces are basic and largly singular in purpose. e.g Environment interface only for retreiving details about the weather.
    • Dependency Inversion Principle
      • Achieved by making Environment, Weather and WeatherFactory dependent on abstractions.
  • Refactor using other design principles
    • Encapsulate what changes.
      • Reviewed – no further changes needed.
    • Don’t Repeat Yourself (DRY)
      • Reviewed. No further changes needed
    • Don’t look for things. Ask for things. (Dependency Injection)
      • Reviewed. No further changes needed.
    • Favor Composition over Inheritance
      • Reviewed. No further changes needed
    • Program to the Interface not to the Implementation
      • Reviewed. No further changes needed
    • Delegation Principles
      • Reviewed. No further changes needed

Now the structure of the program now looks like this:

I will update the source forge and the projects page in the coming days.

Refactoring – Liskov Substitution Principle (LSP) Applied to JobMan

In the previous article I introduced 2 base classes Job and SpawnableJob. Their purpose was to forfill the closed open principle. However, as a side effect when all jobs are returned from the database spawnablejobs was also returned. This breaks the LSP as it is not intended that SpawnableJobs are substutable for Jobs and to do so would violate the single responsibility principle.

So to fix this. Spawnable will change so it has a filed of jobToBeReplicated  which will hold an instance of Job and will no longer inherit from Job.

WhitestarMediaLibrary – database management, Oh CRUD.

As part of implementing the WhitestarMediaLibary project once it had been reviewed using SOLID principles, In this post I will cover adding a database interface and implementation.

The first thing that I realised when I came to implement the database interface is I had not considered the update and delete operators. This would be in keeping with the CRUD paradigm. Creating the interface was standard fare, as was moving the database parts of the WhitestarMusicLibrary to a new class DB40MusicDatabase.

Another item I noticed was missing from the design stage was exceptions so I created 2 exceptions: MediaNotFound and UnsupportedMedia. The class structure is now:

In addition to this a general search method has been added to the Database interface. This search method takes a predicate WhitestarMedia instead of using method overloading e.g search(String track), search(Date year) etc. The only issue this presents if one wanted to search for a date range. However at this stage I am trying to focus on structure (SOLID) and not creating functionality.

 

 

Implementation – It is easy to have ideas but practicing them can be hard.

Constantine Stanislavski once wrote:

It is easy to have ideas in art but it can be hard to put them into practice.

I have long learnt that this applies to everything, not just art. In recent posts I have reviewed a project, WhitestarMediaLibrary, using SOLID and other design principles. I have got to the stage where I feel I should start writing some code and altering the project so it reflects the new structure.

However, there are issues with the implementation and over the next couple of posts I will cover these.  The first of these problems is in regard to the libraries. In previous posts I discussed using a Properties object that contains the class to be injected and any configuration that is required for the object is then fed the same properties object. What I did not decide in previous posts is which class is responsible for instantiating the library.  I also added two custom exception classes if an error occurs when instantiating the library. The resulting class diagram is below:

 

 

I am now thinking, was this the best way to do this? Could I have used a factory method where a class takes the config object instantiates the library and the factory feeds the library the properties file? This would be more in keeping with Single Responsibility Principle. Now the WhitestarLibrary class retrieves libraries but delegates the creation and initialisation to a factory class e.g. LibraryFactory. The resulting structure is now:

 

 

Job Manager – Mind poored out into coding…

Back in 2006 I started a project called JobMan. It was inspired by GTT (Getting Things Done) methodology. Its primary purpose was to facilitate the quick creation of projects that could be broken further and further down into smaller and smaller tasks. As they say in GTT you cannot complete projects, only tasks related to the projects. I also wanted to be able to accurately log the amount of time spent on a project.

The initial UML drawings for the project are given below:

Start-An-Application-with-an-existing-file-that-exists
Start-Application-With-existing-file-that-is-not-found
Stop Watch UseCase
Word-Processor-Use-Case
Creating-A-Job
JobManager Class Diagram 1
JobManager Class diagram 2
JobManager Class Diagram 3
JobManager Use Case Diagram 1
JobManager Use Case Diagram 2

I intended to use other open source projects where possible and did so for a date picker and DB40 for an embedded database. Also at the time I was more intent on learning than creating something that would be used by someone other than myself. Hence, after the initial design, I coded and created features on a whim. I poured my mind out into my coding and tidied it up afterwards, usually when I found a bug.

The project was important in my development as it made me realise that projects need planning to avoid massive restructuring later. I learnt that design patterns could solve the problems I previously procrastinated over. Also my UI design needed work, which prompted me to buy ‘Filthy Rich Clients’ by Chet Haase and Romain Guy,although some of their work is now redundant given the slow rise of JavaFX2.

 

By 2009 I released  the project on sourceforge and then released its  current version in 2016 after spending quite some time using it in my current position. From this usage a number of bugs were fixed and the project optimised, e.g caching, listing subtasks by reference and not by objects.

 

Solid… Solid like a sock!

As continuation of the post Design Patterns and Good Practice post I will review and amend the Whitestarmedialibrary using the SOLID design principles.

Single Responsibility Principle

 

As it has been described to me the Single Responsibility Principle (SRP) is:

There should not be more than one reason for a class/method to change, or a class should always handle single functionality.

Also responsibilities should not be mixed into one class. The benefit being there is less coupling and therefore it is easier to change parts of the system without breaking something. Now do I understand this?  This may not be as silly a question as one might think. When I looked up SRP I found an article at https://www.toptal.com/software/single-responsibility-principle which discusses this directly from an MVC perspective. He argues the application logic is divorced from the controlling class. If I apply this to the WhitestarMediaLibrary the application structure could look like this:

This reduces the role of the WhitestarMediaLibrary to handing out various libraries and opening the initial database or databases. Do I want a situation where 2 or more libraries are interacting with the one database? Do I have a database for each media? Or do I restrict the library to manage one type of media at a time? This seems restrictive given someone may want to play music whilst they game or record TV whilst watching a film. I will delay this decision further down the line until I have applied the other SOLID principles.

However, I do need to move the database management to another class. This class shall be called WhitestarDBManager.

Open Closed Design Principle

 

Wikipedia states Open Closed Design Principle (OCDP) as “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification” My first thought was that because this library is an uncompleted project this principle would not apply to the Whitestarmedialibrary. Only then, when the project is compiled and used in another project, would this principle apply.  However, if I declared WhitestarMedia as abstract it will allow for possible dependency inversion later and allow the possibility of new media types to be added later.

 

Liskov Substitution Principle(LSP) Principle

When looking for instances where I have overridden classes, I was unable to find anywhere I violated the super classes features. The only classes where I  could do this were  the WhitestarMedia class and its subclasses. However, the parent class in this instance was created to group common behaviour not as an interface for a subclass to implement.

 

Interface Segregation Principle

This has been stated in Jpassion course as:

 

“Clients should not be forced to implement interfaces they don’t us. Instead of one fat interface many small interfaces are preferred based on groups of methods, each one serving one sub module.”

 

At present there are no formal interfaces used. This however may change when I come to implement playlists.

 

Dependency Inversion Principle

Wikipedia describes this as:

 

  1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  2. Abstractions should not depend on details. Details should depend on abstractions.

 

As suggested above (in the OCDP section), changing WhitestarMedia to abstract changes the dependency between a library and its media to the abstract WhiteStarMedia and a specific media implementation e.g WhiteStarMedia_Music. However, could this also be applied to libraries themselves? In the above SRP section I moved the functionality of the database and the media management to specific classes. A WhiteStarMediaLibrary Interface could be created so new libraries can be added later. If the interface defined a constructor that required the type of media managed, the main whitestarMediaLibraryClass would could keep the various libraries in a collection instead of specific local variables. It would also allow multiple libraries of the same type to be added e.g. a library for online music service and one for a local service e.g. mp3 collection.  The resulting structure would look be:

This brings me back to another delayed decision, are databases to be single or multiple users? If I want a system where there can be multiple libraries managing media of the same type and some of these are streaming services such as Netflix or Spotify, then we would not be handing a database to them. A better option may be handing over a configuration file when initialising the library. This could be as simple as a properties file that is retrieved from local storage.  The file could be created and configured by the type specific library itself. This is then handed back to the WhitestarMediaLibrary when a close method is invoked. The DBmanager can  be moved to a utility library and then whether the library is shared or not is left to the implementation of the whitestarMediaLibraryInterface.  The resulting structure is reduced to:

All of the classes are then placed into packages e.g. Utility or WhitestarMediaTypes

Design Patterns & Good Practice

As part of refreshing my skills I have started a Jpassion.com course ‘Design Patterns’.

So I can practice what I am learning I decided to update an unfinished project titled WhitestarMediaLibrary (2009). It was originally for a DVR project as WINTV, at the time, was unreliable. This is not an issue since I moved to Linux and Mythtv does everything I want with the exception of the music library. The name Whitestar comes from the Babylon5 universe and all my media centre pc’s have carried the name, I am now on Whitestar9.

Anyway, this media manager is to have the following functions:

  • Manage 4 types of media; TV, Film, Music and Games
  • Pull metadata from the internet
  • Group classifications of genres. When I want to find Rock tracks I don’t want to search for every type of rock i.e soft metal, Hard Rock, thrash etc. I want to click on rock and it return all the tracks in that category.
  • Provide facilities such as playlist creation.

Below is a class diagram of the current implementation.

There are some classes missing here. In particular, extended Whitestarmedia classes for music and game that have been created with attributes specific to those types.

So to begin with,and for the next few posts, I will take this back to basics and review this project using SOLID principles (Single Responsibility Principle (SRP), Open Closed Design Principle,  Liskov Substitution Principle ,(LSP) Interface Segregation Principle, Dependency Inversion Principle).

Rest…When you don’t know where you are going any road will take you there.

I have taken some time to decide on where I should focus my energies. Learn a new language C++, C#, PHP? Given I have already invested a significant amount of time learning and creating programs in Java I have decided that, for now, I will stick with the Java eco system.

This leaves me with the next problem, what to focus on? The state of Java desktop is negligible, as far as I am aware it is not distributed now with  new PC’s.  The nightmare that was Java applets and how it has, rightfully, been kicked out of web browsers.  This leaves the realm of back-end server stuff.

The problem with this is I tend to learn by rote .I create programs I intend to use myself. So I need a trajectory which requires me to create something I could use or that someone else will use. i.e at my place of work. So the options I have thought of are:

  • I currently work in the NHS at a GP practice so I could create a comprehensive intranet site instead of the static one currently in place. Using a local PC as the server. For a practice of no more than 20 pcs the desktop machine should cope with the workload.
  • Create a service that allows me to access recordings, videos and music on a mythtv box from across the web.
  • Build the basic structure for a new clinical system.  The NHS currently uses EMIS Web (Egton) and System One (The Phoenix Project). Given the amount of frustration with the service provided by the current provider this is incredibly appealing and daunting in equal measure.
  • Do both the first and the second in this list.  Create a service that has a solid foundation for a practice intranet site. Then start to add facilities for patient documentation, management etc.

This last option is appealing as it would allow me the scope to create a replacement clinical system whilst knowing that, for the time being, its main purpose is to be a practice intranet site.  This leads me to my next choice, given it is a intranet site, it should lever the strengths of the web. i.e Rest.

I have had “REST in Practice: Hypermedia and Systems Architecture” by by Jim Webber , Savas Parastatidis and  Ian Robinson sitting on my shelf for a couple of years and, as I hate to waste anything, this is the way I am going to go.  In January I also signed up to Jpassion.com (see the upcoming post) which, although the site looks a little tired, it has some good content. It has a REST course.

So I will use both of these to start the MTMC intranet project (MTMC is the abreivation of the GP practice where I work).

It is now time to set sail, though all this floating about makes me sleep restlessly…