KUP Assessments – Bash scripts to test endpoints

For integration testing and the testing of endpoints I have previously indicated I am going to use a bash script of curl commands to achieve this. The first iteration of the script is given below:

#!/bin/sh

#URI's
baseURI="http://localhost:8080/kupassessments/"
create="account/create/"

#test the index url
responseIndexPage=$(curl --write-out "%{http_code}\n" --silent --output /dev/null $baseURI) 2>/dev/null
#test the creation of an account
responseAccountCreation=$(curl --write-out "%{http_code}\n" --silent --data "username=Boot&email=boot@r-a-w.org" --output /dev/null $baseURI$create) 2>/dev/null
echo Bash Script Test of KUPassessments
#result of testing the index page
echo Index Page response: $responseIndexPage
echo Create AccountResponse: $responseAccountCreation

The resulting output is:

Bash Script Test of KUPassessments
Index Page response: 200
Create AccountResponse: 404

The 404 is because the query does not contain any data. I also will have run a an SQL script to reset the database.

The database is cleared using the following script ClearAccountTestingData.sql

delete from accounts where username='boot';

This needs to be run each time the bash script starts to ensure that the database is in a state that is expected for the tests. However this needs the location of the script to be included. So it may be best to execute the the SQL from the testing bash script.

Now I have noticed that the second error is not, in fact due to the data already existing but the fact that the request is incorrect. From searching round the request needs to be rewritten so it sends the request in json.

resources:

KUP Assessment Implementation Diary – Connecting up and dependency injection

Here is a question. when do you inject. Tools like Grice do this for you. But if you are to do it manually, when do you do it? how far do you inject.

We could use the KUP assessments class as an injector class however this would break the single responsibility principle so it would be better to have a separate injector class (KupInjector). Then I simply ask it for various services leaving the configuration of the services to IkupInjector. The classes to be injected shall have a mix of setter and interface injection. This reflects the use of both classes and interfaces used in the structure of the system.

My first implementation of the IkupInjector shall use a properties file to retieve the string class names of the classes to be created. This is then placed in the base directory of the server to which can be edited as needed and the service restarted. The first test in the bash script has been created to test the URI for the index page and and account creation. Using curl is something I am definitely need to work on as it took me a significant amount of time to do even the simplest command.

Sources:

RAW Rota – Convert Requirements into specific test cases

irotaFactory

  • Produces X number of proposed rotas for a specified time period

Irota

  • A collection of shifts and events for staff
  • fitness score that was generated at creation time can be retrieved
  • fitness score is final
  • events can be amended
  • staff can be amended
  • Staff can be added to the rota so events and clinics can be allocated to them
  • Staff can be removed
  • Staff cannot be removed if they are allocated shifts or events.
  • Shift can be amended
  • Change Istaff
  • Change date
  • Change period

Istaff

  • Holds Name
  • Holds Staff referrence number

Holds Role

Event

  • Holds Name of event
  • Holds period of event

IrotaRule

  • holds staff ref
  • Takes a rota and provides a fitness score of how well the rule fits

IstaffDatabase

  • Holds Istaff

IrotaDatabase

  • Holds Irota

IruleDatabase

  • Holds IrotaRule

IrotaMediator

Formerly the RotaCoordinator class, the IrotaMediator interface follows the mediator pattern this lously couples the classes encapsulating the communication. between them. It is ultimatly is where the requirements list is forfilled.

KUP Assessments Security Checklist

• Risk Assessment and ongoing risk tracking.

The following risks are immediately identified:

1. Single developer

2. Lack of experience

In light of the above I shall adopt a concept from the martial arts world, referred to as the ‘economy of movement’ This means to strip out non essentials and take the most direct route to implementing the software. This does not mean to cut corners but to optimise the time spent developing essentials not superfluous elements of the system. e.g Artwork, fancy GUI interfaces etc.

3. The use of ‘Basic Authorisation’ and SSL

There must be some monitoring of any new threats/ compromises to this method of authentication. The issue of caching the usernames and passwords must be tackled. Initial solutions include offering an option of sending a request that sends a username and password of clear which the system then returns code such as 203 – Non-Authoritative Information

4. Ensure singleton for resources such as creating accounts, assessments is truly singleton

ref: https://www.oracle.com/technetwork/articles/java/singleton-1577166.html

• Separate databases

The databases are already account and assessment. If we added authentication with its own manager this would allow usernames and passwords to be separated from account and assessment. This also has the benefit of decoupling the authentication from the accounts in the system later moves to another authentication method .e.g OAuth2.

• Salted Hashes of Passwords, user data etc.

Hashing should not use MD5 but SHA256 from the java security library ref: https://www.youtube.com/watch?v=hNKfEwTO3AQ Salts should be kept in a separate database away from the password database. Salts should be kept in a separate database away from the password database.

• Create reusable security controls I.e dependency injection.

• Security controls should be vetted and standardised

• Build training, testing and other activities around the security controls.

• Use OWASP Security Verification Standard (V3).

The basic level of standard shall be used. The system should not hold more information other than security questions, email address, username & password and assessments authored. This will also simplify GDPR legislation. If the amount of personal information changes then this the checklist should be reviewed in case further level of requirements need to be implemented.

1.1 Verify that all application components are identified and are known to be needed.

All the components would have been identified in the development process.

2.1 Verify all pages and resources by default require authentication except those specifically intended to be public (Principle of complete mediation).

Added to checklist for creating unit tests

2.2 Verify that all password fields do not echo the user’s password when it is entered

Added to the client testing checklist

2.4 Verify all authentication controls are enforced on the server side.

To be added as unit tests for the KUPfacade interface. And a set of tests using curl using a bash script.

2.6 Verify all authentication controls fail securely to ensure attackers cannot log in.

Added to unit tests for components requiring authentication.

2.7 Verify password entry fields allow,or encourage,the use of passphrases, and do not prevent long passphrases/highly complex passwords being entered.

Create a scheme that is enforced or encouraged by the client for minimum requirements there shall be a unit test to ensure the authentication manager enforces this. The is kept in the related post (KUP Assessments – Password Schema)

2.8 Verify all account identity authentication functions (such as update profile, forgot password, disabled/ lost token, help desk or IVR) that might regain access to the account are at least as resistant to attack as the primary authentication mechanism.

The project initially thinking it would use security questions. I have now decided that security questions are too weak a process and an email recovery service should be employed using the JavaMail API.

2.9 Verify that the changing password functionality includes the old password, the new password, and a password confirmation.

Added to unit test for authentication manager.

2.16 Verify that credentials are transported using a suitable encrypted link and that all pages/ functions that require a user to enter credentials are done so using an encrypted link.

This is completed using a bash script and curl.

2.17 Verify that the forgotten password function and other recovery paths do not reveal the current password and that the new password is not sent in clear text to the user.

Added to unit test for password recovery and authentication manager.

2.18 Verify that information enumeration is not possible via login,password reset, or forgot account functionality.

This shall be controlled by the hosting service and has been added to the ongoing threat assessment/ management.

2.19 Verify there are no default passwords in use for the application framework or any components used by the application (such as “admin/password”).

Shall be blocked by the password scheme in the system – common passwords.

2.20 Verify that request throttling is in place to prevent automated attacks against common authentication attacks such as brute force attacks or denial of service attacks.

This to be done by limiting bandwidth or another resource. Rate limit everything that could slow down or break the application. Use a simple counter kept in a quantised bucket

  • Decide on limit

Should not be too aggressive. Log if limits are reached and amend limits if required.

Bursting should not be required. Simple but different levels of limitting when authoring to participating

  • Decide identifier for limit

Must be an combination of IP address and username for authoring and IP address, browser and resource requested

  • Decide on exceptions for rules

Dynamic rating – all users. In this project no.

IP addressees – have exceptions for any monitoring tools or datacentre ranges (addresses that end web consumers should not be using). Also no limiting of yahoo, google etc.

Source: https://www.youtube.com/watch?v=Q53eR7mFsRo

2.22 Verify that forgotten password and other recovery paths use a soft token, mobile push, or an offline recovery mechanism.

Added to PasswordRecovery unit test.

2.24 Verify that if knowledge based questions (also known as “secret questions”) are required, the questions should be strong enough to protect the application

Secret questions are not used in this application.

2.27 Verify that measures are in place to block the use of commonly chosen passwords and weak passphrases.

Added to passwordschema unit test from general resource and privacy tests.

2.30 Verify that if an application allows users to authenticate, they use a proven secure authentication mechanism.

Basic authentication and ssl is to be used.

2.32 Verify that administrative interfaces are not accessible to untrusted parties

This is to be achieved via a bash script and unit test on authentication manager

3.1 Verify that there is no custom session manager, or that the custom session manager is resistant against all common session management attacks.

There are no sessions in the planned service.

3.2 Verify that sessions are invalidated when the user logs out.

There are no sessions in the planned service. However there is a dummy resource where passwords in a browser can be clear out of cache using username and password of 203 – Non-Authoritative Information. This has been added to the unit tests for authentication manager.

3.3 Verify that sessions timeout after a specified period of inactivity.

There are no sessions in the planned service.

3.5 Verify that all pages that require authentication have easy and visible access to logout functionality.

There are no sessions in the planned service. However there is a dummy resource where passwords in a browser can be clear out of cache using username and password of 203 – Non-Authoritative Information. This has been added to the unit tests for authentication manager.

3.6 Verify that the session id is never disclosed in URLs, error messages, or logs. This includes verifying that the application does not support URL rewriting of session cookies.

There are no sessions in the planned service.

3.7 Verify that all successful authentication and re-authentication generates a new session and session id.

There are no sessions in the planned service.

3.11 Verify that session ids are sufficiently long, random and unique across the correct active session base.

There are no sessions in the planned service.

3.12 Verify that session ids stored in cookies have their path set to an appropriately restrictive value for the application, and authentication session tokens additionally set the “HttpOnly” and “secure” attributes.

There are no sessions in the planned service.

3.16 Verify that the application limits the number of active concurrent sessions.

There are no sessions in the planned service. There will be throttling provided and added to use case for RequestThrottler.

3.17 Verify that an active session list is displayed in the account profile or similar of each user. The user should be able to terminate any active session.

There are no sessions in the planned service.

3.18 Verify the user is prompted with the option to terminate all other active sessions after a successful change password process.

There are no sessions in the planned service.

4.1 Verify that the principle of least privilege exists – users should only be able to access functions, data files, URLs, controllers, services, and other resources, for which they possess specific authorization. This implies protection against spoofing and elevation of privilege.

Added to the unit test for authentication manager.

4.4 Verify that access to sensitive records is protected, such that only authorized objects or data is accessible to each user (for example, protect against users tampering with a parameter to see or alter another user’s account).

Added to unit test of authentication manager.

4.5 Verify that directory browsing is disabled unless deliberately desired. Additionally, applications should not allow discovery or disclosure of file or directory metadata, such as Thumbs.db, .DS_Store, .git or .svn folders.

Should be managed by hosting service.

4.8 Verify that access controls fail securely.

Added to the authentication manager unit tests.

4.9 Verify that the same access control rules implied by the presentation layer are enforced on the server side.

Implemented in the password schema, password recovery and authentication managers via unit tests.

4.13 Verify that the application or frame work uses strong random anti-CSRFtokens or has another transaction protection mechanism.

The service will need to use a HMAC based Token pattern verfy this. Ref: https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.md

This introduces a HMACsevice interface that take responsibility for generating tokens.

4.16 Verify that the application correctly enforces context-sensitive authorisation so as to not allow unauthorised manipulation by means of parameter tampering.

On unit test list for authentication manager and HMACservice

5.1 Verify that the runtime environment is not susceptible to buffer overflows, or that security controls prevent buffer overflows.

The java language has some protection as it is strongly typed, automatic bound checks and automatic memory management. Additionally account to OWASP.org java/j2ee is not affected as long as native methods or system calls are not invoked.

5.3 Verify that server side input validation failures result in request rejection and are logged.

Created new interface AssessmentValidator which checks the input of participant and author. Added to unit tests for AssesmentValidator .

5.5 Verify that input validation routines are enforced on the server side.

Added to AssessmentValidator unit test

5.10 Verify that all SQL queries, HQL, OSQL, NOSQL and stored procedures, calling of stored procedures are protected by the use of prepared statements or query parameterization, and thus not susceptible to SQL injection

Added to assessmentValidator interface unit tests

5.11 Verify that the application is not susceptible to LDAP Injection, or that security controls prevent LDAP Injection.

The system will not be using LDAP for user credentials or search filters.

5.12 Verify that the application is not susceptible to OS Command Injection, or that security controls prevent OS Command Injection.

Create JAX-RS filter or interceptor that filters all parameters in the uri’s Interface URIsanitiser created and added to unit test list. Additionally the service will not invoke Runtime.exec in order to call operating system commands

5.13 Verify that the application is not susceptible to Remote File Inclusion (RFI) or Local File Inclusion (LFI) when content is used that is a path to a file.

The URI sanitiser has added unit test that will not allow file extensions to proceed.

5.14 Verify that the application is not susceptible to common XML attacks, such as Xpath query tampering, XML External Entity attacks, and XML injection attacks.

Added to assessment validator unit tests

5.15 Ensure that all string variables placed into HTML or other web client code is either properly contextually encoded manually, or utilize templates that automatically encode contextually to ensure the application is not susceptible to reflected,stored and DOM Cross-Site Scripting (XSS) attacks.

The OWASP java-html sanitiser shall be used: https://github.com/OWASP/java-html-sanitizer if it is decided html will be used when submitting new assessments and submitting assessments. This shall be used as a composit part of the assessementValidator.

5.22 Make sure untrusted HTML from WYSIWYG editors or similar are properly sanitized with an HTML sanitizer and handle it appropriately according to the input validation task and encoding task.

Added the the AssessmentValidator interface.

7.2 Verify that all cryptographic modules fail securely, and errors are handled in a way that does not enable oracle padding.

Added unit tests to the passwordschema, HMACservice and athenticationManager. There will be no error for PAD error or MAC error returned to the user (added to unit test for authenticationManager). Timing attacks shall be countered by failing attacks to always take 5 seconds or other arbitatary length of time. Ref: https://www.youtube.com/watch?v=evrgQkULQ5U

7.7 Verify that cryptographic algorithms used by the application have been validated against FIPS 140-2 or an equivalent standard.

Added to unit tests for athentication manager.

8.1 Verify that the application does not output error messages or stack traces containing sensitive data that could assistan attacker, including session id, software/ framework versions and personal information.

Added to unit test for authentication manager and bash script using curl

9.1 Verify that all forms containing sensitive information have disabled client side caching, including autocomplete features.

Added to unit test for Client side application

9.3 Verify that all sensitive data is sent to the server in the HTTP message body or headers (i.e., URL parameters are never used to send sensitive data).

Added to the unit test for KUP_Facade

9.4 Verify that the application sets appropriate anti-caching headers as per the risk of the application, such as the following: Expires: Tue, 03 Jul 2001 06:00:00 GMTLast-Modified: {now} GMTCache-Control: no-store, no-cache, must-revalidate, max-age=0Cache-Control: post-check=0, pre-check=0Pragma: no-cache

Added to the unit test for KUP_Facade

9.9 Verify that data stored in clientside storage – such as HTML5 local storage, session storage, Indexed DB, regular cookies or Flash cookies – does not contain sensitive or PII).

Added to client application unit test

10.1 Verify that a path can be built from a trusted CA to each Transport Layer Security(TLS) server certificate, and that each server certificate is valid.

Added to bash script using curl

10.3 Verify that TLS is used for all connections (including both external and backend connections) that are authenticated or that involve sensitive data or functions, and does not fall back to insecure or unencrypted protocols. Ensure the strongest alternative is the preferred algorithm.

Added to bash script using curl

10.11 Verify that HTTP Strict Transport Security headers are included on all requests and for all subdomains, such as Strict-Transport-Security:max-age=15724800; includeSubdomains

Added to bash script using curl

10.13 Ensure forward secrecy cipher share in use to mitigate passive attackers recording traffic.

Bash script and curl to ensure elipitic curve or diffi-hellman key when exchanging keys during TLS – check with service provider

10.14 Verify that proper certification revocation, such as Online Certificate Status Protocol (OSCP) Stapling, is enabled and configured.

Bash script and curl – check with service provider

10.15 Verify that only strong algorithms, ciphers, and protocols are used, through all the certificate hierarchy, including root and intermediary certificates of yours elected certifying authority.

Bash script and curl – check with service provider

10.16 Verify that the TLS settings are in line with current leading practice, particularly as common configurations, ciphers, and algorithms become insecure.

Bash script and curl – check with service provider

11.1 Verify that the application accepts only a defined set of required HTTP request methods, such as GET and POST are accepted, and unused methods(e.g.TRACE,PUT,and DELETE) are explicitly blocked.

Added to unit test for KUP_Facade and bash script using curl

11.2 Verify that every HTTP response contains a content type header specifying a safecharacter set (e.g., UTF-8, ISO 8859-1).

Added to the unit test for KUP_facade

11.5 Verify that the HTTP headers or any part of the HTTP response do not expose detailed version information of system components.

Added to Bash script using curl and unit test for KUP_facade

11.6 Verify that all API responses contain X-Content-Type-Options:nosniffandContent-Disposition:attachment;filename=”api.json”(or other appropriate filename for the content type).

Added to KUP_facade unit test

11.7 Verify that the Content Security Policy V2 (CSP) is in use in a way that either disables inline JavaScript or provides an integrity check on inline Java Script with CSP noncing or hashing.

Added to KUP_facade and assessment validator unit tests

11.8 Verify that the X-XSS-Protection: 1; mode=block header is in place.

Added to KUP_facade unit test and bash script using curl

16.1 Verify that URL redirects and forwards only allow white listed destinations, or show a warning when redirecting to potentially untrusted content.

Added to KUP_facade unit test

16.2 Verify that untrusted file data submitted to the application is not used directly with file I/O command, particularly to protect against path traversal, local file include, file mime type, and OS command injection vulnerabilities.

Added to assessmentValidator

16.3 Verify that files obtained from untrusted sources are validated to be of expected type and scanned by antivirus scanners to prevent upload of known malicious content.

No files to be uploaded to the system only formatted text. Added to unit test for assessmentValidator

16.4 Verify that untrusted data is not used within inclusion, class loader, or reflection capabilities to prevent remote/local file inclusion vulnerabilities.

Only assessmentValidator can instantiate assessments which is only done from classess only in the sourcecode of the server and not defined by the text entered into the assessment. The assessment instantiation is only done after the assessment has been validated. Added to assessmentManager unit tests.

16.5 Verify that untrusted data is not used within cross-domain resource sharing (CORS) to protect against arbitrary remote content.

Only system schema and components implimenting the assessment interfaces are used – added to assessmentValidator.

16.8 Verify the application code does not execute uploaded data obtained from untrusted sources.

Added to unit test for assessmentValidator.

16.9 Do not use Flash, Active-X, Silverlight, NACL, client-sideJava or other client side technologies not supported natively via W3C browser standards.

Added to unit test for client application.

17.1 Verify that ID values stored on the device and retrievable by other applications, such as the UDID or IMEI number are not used as authentication tokens.

Added to unit test for HMAC service, Client application and KUP_Facade

17.2 Verify that the mobile app does not store sensitive data on to potentially unencrypted shared resources on the device (e.g. SD card or shared folders).

No App planned at this time.

17.3 Verify that sensitive data is not stored unprotected on the device, even in system protected areas such as key chains.

Added to client unit test

17.7 Verify that the application sensitive code is laid out unpredictably in memory(Forexample ASLR).

Using the JAVA platform negates this threat.

17.9 Verify that the app does not export sensitive activities, intents, content providers etc., for other mobile apps on the same device to exploit.

This is to be browser based and not needed at this time.

17.11 Verify that the app’s exposed activities, intents, content providers etc. validate all inputs.

This is to be browser based and not needed at this time.

18.1 Verify that the same encoding style is used between the client and the server.

Added to unit test for Client Application and KUP_Facade

18.2 Verify that access to administration and management functions within the Web Service Application is limited to web service administrators.

Added to athenticationManager unit tests

18.3 Verify that XML or JSON schema is in place and verified before accepting input.

Managed by JAX-RS

18.4 Verify that all input is limited to an appropriate size limit.

Added to new interface InputCheckFilterInterface

18.5 Verify that SOAP based web services are compliant with Web Services – Interoperability (WS-I) Basic Profile at minimum.

Not applicable for this project.

18.6 Verify the use of session – based authentication and authorization. Please refer to sections 2, 3 and 4 for further guidance. Avoid the use of static “API keys” and similar.

No sessions are to be used in this project. (REST)

18.7 Verify that the REST service is protected from Cross-Site Request Forgery.

HMAC already added to unit tests

19.1 All components should be up to date with proper security configuration(s) and version(s). This should include removal of unneeded configurations and folders such as sample applications, platform documentation, and default or example users.

A monthly review of security reports should be undertaken so new exploits can be mitigated or resolved.

For a list of terms (Glossary) please see post (KUP Assessments – Glossary)

Unit testing features of security

See the unit test post for resulting unit tests.

Independent review by a 3rd party. e.g a IT Security consultant.

Not to be implemented at this stage.

Updated Class Diagram

Updated Class Diagram

KUP ASSESSMENT DEVELOPMENT

Project Goal

A service that allows/ precipitates the creation and sharing of assessments of any kind from risk assessments to simple checklists. Assessments can scored using different schemes including secondary and primary contributory factors. These could then be assessed using Bayes theorem.

Initial Requirement List

  • Manage users
  • Users can create edit and amend own assessments
  • Users can create documentation for their assessments
  • Users can access documentation on how to create assessments.
  • Assessments can use a number of different scoring schemes.
  • Non users can use assessments and email/ print/ save results

Suspected Target Technologies

  • JAX-RS
  • MySQL
  • HTML5
  • JavaScript

Initial Use Case

Initial Use Diagram (PIC)

KUP Assessments

It has been a while since I have posted anything. Work commitments have kept me distracted, however I have still managed to do some programming. I have started a new project titled “KUP Assessments”. For the next several posts I will outline the development process of the service.

The projects main goal is to allow users to create assessments that can be completed by other users. This assessments can be shared and not have to be recreated needlessly.

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 – Other Design Principles – JobMan

Encapsulate what changes

A factory pattern could be used to encapsulates job creation. The factory could be for each specific interface -e.g SpawnableJobs. The structure now takes the following form.

Don’t Repeat Yourself (DRY)

After applying the other principles – I cannot see any duplication of functionality at this time.

Don’t look for things. Ask for things. (Dependency Injection)

This is already achieved by the implantation of the factory method for creating Jobs. It is also done via injecting the numbering scheme at database creation.

Favor Composition over Inheritance

Composition has already been used for the implementation of SpawnableJob.

Program to the Interface not to the Implementation & Delegation Principles

This was covered when jobman was reviewed for Single Responsibility Prinicple and Interface Segregation Principle.

 

Conclusions

This was a useful exercise and will allow some of the work I did on JobMan to be reused in other projects. I will move the GUI code to a separate  repository which will be placed on the Sourceforge page and the projects page of this website.

Refactoring – Dependency Inversion Principle (DIP) Applied To JobMan

Already in the previous posts I have moved the Database to an interface where JobDatabase interacts with abstract base classes of Job and SpawnableJob. Meaning that neither Databases are dependent of details of implementions of Job and SpawnableJob and conversely they are not dependent the JobDatabase class as this is declared through interfaces. So the resulting structure is now:

I also renamed the currently implemented JobDatabase to JobDataBaseDB4OEmbedded.

Refactoring – Open Closed Principle applied to JobMan

The MainJob and Replicator classes could turned to Abstract or I could introduce new base classes. I had previously deleted the Job class but this needs reinstating with MainJob extending Job. Then there could also be a replication base class that then extends the Job class functionality and introduces the functionality associated with spawning a Job. The base class in this instance could be referred to as SpawnableJob. I have chosen to introduce base classes mainly because I prefer the names of the base classes.

In future Job Classes could have further functionality added e.g a job with attached documents.

This would require minimum amendments to the JobDatabase class.

The class diagram now looks like this: