Enterprise Programming

From Computing Study
Jump to: navigation, search

Design Patterns

What are Design Patterns? How do these differ from other programming styles?

A design pattern describes a generic problem and also a range of different solutions depending on the problem's constraints. In software engineering, they enable expert designs to be reused in many different applications. Each pattern describes a problem that occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over without ever doing it the same way twice. It is a template solution to a recurring design problem, with reusable design knowledge. It is an example of modifiable and reusable design. It is Problem / Solution pairs in context. Patterns capture the static and dynamic structure and collaboration among key participants in software designs.

Different Types Of Design Patterns

Creational - Deal with initialising and configuring classes and objects, e.g. Factory, Abstract Factory, Builder, Prototype, Singleton.

Structural - Deal with decoupling interface and implementation of classes and objects, e.g. Adapter, Bridge, Facade.

Behavioural - Deal with dynamic interaction among societies of classes and objects, e.g. Interpreter, Observer.

A pattern has four essential elements

Pattern name and possibly aliases
As with classes, the name should be short, but as descriptive as possible

Problem
What is the problem that arises in this context. Generally explained in terms of conflicting forces, such as requirements and constraints - use generic terminology to describe the problem

Solution
Including explanatory text, models, and/or example code

Consequences
Good and bad things about what happens if you use the pattern, variants on the pattern, references to other relevant patterns

Design patterns build on Object Oriented concepts, they don't replace them.

Benefits of patterns

Learning about existing and searching for domain-specific patterns would improve communication among designers on a team, among designers on different teams, between a designer and themselves. It would improve documentation, the use of pattern names in documentation carries a lot of information and saves space. You can reuse them without creation and maintenance of code libraries, they are not tied to any specific language. They will improve future designs as collective experience is applied to new projects.

The structure and features of the Singleton Pattern

The Singleton Pattern is a class for which we only want exactly one instance, and to which we may want global access. You reference the object globally through its class definition. It contains a class variable called "instance" whose value is an instance of the object. There is a static method called instance() that:

  • Creates an instance, if not created yet
  • Returns the instance of the class
  • Allows multiple instances in the future without affecting a singleton class's clients
  • Can be updated from different places, e.g. when different kinds of messages are generated

Use of a Singleton Pattern with advantages and disadvantages

The Singleton Pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a Singleton does not yet exist, they must both check for an instance of the Singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation.

Overriding the clone method, in order to prevent the object from being cloned from outside.

The Singleton Pattern is often used in conjunction with the Factory method pattern to create a system-wide resource whose specific type is not known to the code that uses it. An example of using these two patterns together is the Java Abstract Window Toolkit (AWT). You use a singleton when you need to manage a shared resource, for instance a printer spooler. Your application should only have a single instance of the spooler in order to avoid a conflicting request for the same resource. Another example would be a database connection or a file manager.

public class Singleton {
    private static final Singleton INSTANCE = new Singleton();
    
    // Private constructor prevents instantiation from other classes
    private Singleton();

    public static synchonized Singleton getInstance() {
        return INSTANCE;
    }

    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }
}

The Observer Pattern

Used when you need to communicate a change on one object to a number of other objects

Why is this pattern solution so good?

Better encapsulation of functionality

  • Basic subject is not overly concerned with the Observers

Loose coupling between the Subject and Observers

  • No hard coded assumptions about Observers' class types - they implement an interface called Observer
  • No hard coded assumptions about Oberver's method names - they inherit from interface function update()

Reuse Observable / Observer functionality

  • This Observable / Observer generic functionality has no coupling to a particular situation - use for database, document viewing, client-server systems

Good Observer Design Patterns

Java has the Observable class and the Observer interface

"Subject" extends functionality from the java.util.Observable class

Observer.png

Observer2.png

Use of the Observer Pattern and advantages

Also known as model - views, publish - subscribe

  • When a file is updated by one program on Windows (Subject), all the other programs that are using it (Observers) are notified
  • When an online auction is being performed over a number of days, users can register an interest in receiving bid updates. The bid history (Subject) would then process each bid event and notify registered Observers about any changes. An Observer may send a "latest price" email, for instance

Key features of design patterns are that the language used is generic, i.e. it can be applied to any similar problem, independent of what the Subject and Observers actually are.

Structure and features of the Factory Design Pattern

A factory pattern is called a factory because it is used to produce / create other objects or products.

A product is an abstract class / interface which is extended / implemented by a number of concrete product classes

Factory.png

Example program that can be refactored with the Factory Pattern

public class ImageReader {
    private int filetype;
    private String fileContents;
    private byte[] decodedImage;
    public ImageReader( InputStream in ) {
        // Figure out what type of file this input stream represents
        // (e.g. gif, jpeg, png, tiff)
        fileType = file_type;
        decodeFile(fileType);
    }

    private decodeFile(fileType) {
        switch( filetype ) {
            case imagereader.GIF:
                // do gif decoding (many lines)
                break;
            case imageReader.JPEG:
                // do jpeg decoding (many lines)
                break;
            case imageReader.PNG:
                // do png decoding (many lines)
                break;
            // etc...
} } }

The code for image decoding is within the same class as the rest of the program. As the number of file types supported gets larger, the code will quickly become huge, unwieldy and hard to maintain. Having lots of different functions in one huge 'god' class makes it difficult to track errors when they occur.

Why does this suit the Factory design pattern?

This problem suits the Factory Pattern because the parent class can't always anticipate the class of objects it must create; and the parent class wants its subclasses to specify the objects it creates. It is a way to encapsulate a group of individual factories (decoders) that have a common theme.

Possible refactoring stages have a separate object for each file type and program to an interface

public Interface ImageReader {
    public ImageReader (InputStream in);
    public getDecodedImage();
}

public class GifReader implements ImageReader {
    public GifReader (InputStream in) {
        // Check it's a gif, throw exception if not
        // else decode it
    }

public getDecodedImage() { return DecodedImage; }

public class JpegReader implements ImageReader { // ... }

Then use them as:

public class MyProg {
    public static void main (String [] args) {
        String filename = args[0];
        ImageReader out;
        if (endsInDotGif(filename)) {
            out = (ImageReader) new GifReader(file_input_stream);
        } else if (endsInDotJpeg(filename)) {
            out = (ImageReader) new JpegReader(file_input_stream);
        }
        print(out.getDecodedImage);

Problem: this solution will need to be repeated every time an ImageReader is created

Solution 2: Use a Factory Pattern

public class ImageReaderFactory {
    public static ImageReader getImageReader(InStream is {
        int imageType = figureOutImageType(is);
        switch(imageType) {
        case ImageReaderFactory.GIF:
            GifReader r = new GifReader(is);
            return ((ImageReader) r);
            break;
        // etc ...
} } }

In the calling code the factory would be used like:

ImageReader img = ImageReaderFactory.getImageReader(is);

Spring MVC

Springmvc.png

https://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/spring-mvc-intro.html

Spring MVC was developed to address the complexity of enterprise application development. It is an open-source lightweight inversion of control (IoC) and aspect-oriented container framework. It provides clean separation between control an presentation. An IoC container controls the object life cycle and manages object dependencies. A set of enterprise services aimed at simplifying application development such as JMS, RMI etc.

The servlet (Controller) will act as controller and will handle the requests, including initial request. In addition the controller will retrieve data from the model and forward data to the JSP (Push Model). Controller will manage the flow of traffic between the user and system.

JSP (View) will host the Java Server Pages, HTML pages etc. It will be used for the presentation side. ALl JSPs should be created here. JSP pages will be pushed to the user by the controller. Domain classes are created in the model, and are then used by the controller.

RMI - Remote Method Invocation

In RMI a remote interface is an interface that declares a set of methods that may be invoked from a remote Java virtual machine. A remote interface must satisfy the following requirements:

  • A remote interface must extend, either directly or indirectly , the interface java.rmi.Remote.

Each method of declaration in a remote interface or its super-interfaces must satisfy the requirements of a remote method declaration as follows:

  • A remote method declaration must include the exception java.rmi.RemoteException (or one of its super classes, such as java.io.IOException) in its throws clause in addition to any application-specific exceptions. Application-specific exceptions do not have to extend java.rmi.RemoteException

Java RMI architecture and the role of each component

Layer: the client and server program

Stub and Skeleton Layer: Intercepts method calls made by the clients and redirects these calls to a remote RMI service

Remote Reference Layer: Understands how to interpret and manage references made from clients to the remote service objects

Transport Layer: Based on TCP/IP connections between machines in a network. It provides basic connectivity as well as some firewall penetration strategies.

Rmi.png

How is the naming service provided in Java RMI?

Naming class used in the Java Naming and Directory Interface (JNDI). The naming class provides methods for storing and obtaining references to remote objects in a remote object registry. Each method of the Naming class takes as one of its arguments a name that is a java.lang.String in URL format (without the scheme component) of the form:

    //host:port/name

where the host is the host, remote or local where the registry is located, port is the port number on which the registry accepts calls, and where name is a simple string uninterpreted by the registry. Both host and port are optional. If host is omitted, the host defaults to the local host. If the port is omitted then the host defaults to 1099, the "well-known" port that RMI's registry rmiregistry uses.

bind() or rebind(): declares that an object is bound to a name
lookup(): retrieves a reference to a remote object
list(): retrieves a directory of available objects

In client-server technology / architecture, a server responds to a remote client. A call back is a method invocation from one application (App A) to another application (App B), as a result of action that was performed by App B earlier. App A may run on a client and App B may run on a server. To perform the call back mechanism the system that App A suns acts as a server and that of App B runs as a client.

Object Serialization

To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object. A Java object is serializable if it's class or any of it's superclasses implement java.io.Serializable.

To marshal and unmarshal the parameters involves the object serialization and does not truncate types.

The methods of local object and their bytecodes are not passed directly in the ObjectOutputStream. At times the name of the class of the objects may be needed, that is to be loaded by the receiver if all the class is not available locally.. Just like the names of the classes, the class files themselves will not be serialized. All classes must load during the process of deserialization using the normal mechanisms of class loading. It allows developers to save and retrieve Java classes to any I/O stream.

import java.io.Serializable

public class Person implements Serializable {

}

Hibernate

Provide a Java-centric view of persistence information. Java developers are not database developers, therefore by solving this problem will lead to a reduction of the need for developers to know and fully understand database design and SQL.

Intentions behind introducing such a framework

  • Provide Java-centric view of persistence information
  • Works with plain old Java objects
  • Supports Object-Oriented concepts (encapsulation, inheritance, polymorphism)
  • Eliminate the need to hard-code SQL statement
  • Queries can be written/defined in external files and also in an object
  • Prevent leakage of concerns. Domain model should only be concerned about modelling the business process, not persistence, transaction management and authorisation.
  • Transparent and automated persistence - complete separation of concerns between domain model objects and the persistence mechanism. Persistent solution does not involve writing SQL

Comparison between JDBC and Hibernate

JDBC

  • Data Access Object and Data Transfer Objects
  • Abstracts CRUD operations
  • Allows different storage implementations to be 'plugged in' with minimal impact to the rest of the system
  • Decouples persistence layer
  • Encourages and supports code reuse

Hibernate Provides domain objects as Plain Old Java Objects in response to queries and these persist across domain objects

Hibernate-jdbc.png

Cloud Computing

Cloud Computing Infrastructure

Application Servers - Host variety of business applications
Database Servers - Persist organisational data
Networks - Interconnect systems
Internet Access - For email, internet etc
Desktop - Client to server hosted applications
- Host productivity tools e.g. Word
Mobile - Remote access to company infrastructure
Definition of Cloud Computing

Transparently Scalable

  • Can handle large variations in workload transparently
  • Extra hardware added and removed without human intervention

IT Resources

  • Servers, storage, networks, routers, load balancers
  • applications, database servers, application servers, development software

Seemingly infinite pool of resources

  • Virtual machines
  • Share resources and improve utilisation

Self Service

  • New resources can be added or removed as required immediately
  • No management intervention required
Components
  • Clients - thick, thin, mobile
  • Distributed servers - archiving, reliability / backups, load overflow
  • Data centre - hosting applications and databases

Software As A Service

Business apps hosted by a provider and delivered as a service

  • No need to install software on the client computer
  • Often accessed via a web browser

Advantages:

  • Pay-per-use, no upfront costs
  • Receive latest updates transparently
  • No in-house admin or installation costs
  • Can now get traditional software as SaaS



SaaS Examples:

Salesforce.com

  • Customer relationship management software
  • Tools for sales people to find customers and keep in contact with them
  • Gives a birds eye view of customer status, in-flight orders, order history, leads, approvals etc.
  • Shared machines and databases
  • Sophisticated proprietary query optimisation and indexing
  • Easy 'tunnels' for sharing across customers
  • Ajax web interface with various communications services. E.g. tracking for Twitter, collaborative tools etc.
  • Plug-ins for extensions via Platform-as-a-Service "Force.com"

Why use them?

  • Their value proposition: outsource you main corporate IT to them
  • They bill per month - Force.com $15/user/month
  • They can offer it cheaper than corporate IT
  • Leverage the same infrastructure, design and support across many companies at the same time - "multi-tenancy".

Some customers

  • Dell, AMD, SunTrust, Spring, Computer Associates

Author Solutions

  • Needed to streamline its book publishing process
  • Required a common platform on which to integrate disparate back and front office systems, to speed up the publishing process and increase visibility into business metrics
  • Created a customised application on Force.com
  • Took less than 6 months to develop
  • Benefits calculated as 1.5 times faster at a cost of 67% of equivalent on-premises development

Office suites from Microsoft and Google

  • Email - Word processor - Spreadsheet

Software plus services

  • mixed mode of operation - local software mixed with cloud services
  • Service Oriented Architecture (SOA) - integrate services from different providers
  • Accessed using well-defined standards - JSON, SOAP, XML
  • Covers a wide range of functionality - storage, CC payments, maps, address finder etc.

Platform As A Service

A computing platform that includes software for development, middleware (web servers, messaging systems) and deployment. Organisations can concentrate on application development, there is no need to buy or maintain resources required to execute the software during the entire development cycle, from testing to production.

Major benefits:

  • Easy to use
  • Automatic scalability
  • Reliability, performance, security of major providers
  • Cost efficient
  • Free trial periods
PaaS Examples

Google App Engine

  • Provides tools and development stack for Python, PHP and Java
  • Development tools available
  • Application automatically scaled
  • Free for 1.5GB storage and 8.5 hours CPU time per day
  • Free for 12 months or $300 usage
  • Free limits occasionally increased

Microsoft Azure

  • Provides Windows Azure operating system
  • Development tool support
  • Data storage services
  • Runs on a virtual machine

Force.com

  • SalesForce.com PaaS for building applications
  • Provides custom application development platform
  • Applications rapidly built using Force.com tools

Heroku

Infrastructure As A Service

IaaS means resources delivered as a service - servers, networks, memory, CPU, and is based on the virtualisation of machines. A key feature of IaaS is instant provisioning - new resources can be made available on demand within minutes and are accessed on virtual networks.

Examples of IaaS

Amazon Elastic Compute Cloud (EC2)

  • Amazon supplies a set of machine images
  • It supports various operating systems (Windows, UNIX, and Linux, but not MAC)
  • Allows provisioning of high-memory or high-CPU image instances
  • Multiple software options available on pre-packed machine images
    • App servers: Jboss, WebLogic, WebSphere
    • DB servers: MySQL, SQL Server, DB2
  • Software developer tools available
  • Various other services
    • Storage service
    • Message service
    • Map reduce

Eucalyptus An open source cloud platform, it is used for private clouds where you provide the hardware and Eucalyptus provides the software.

Ajax

The core concepts and technologies involved to implement Ajax-based systems are: JavaScript client side processing - sending and receiving requests to the server using XML and/or JSON; xHTML, HTML byitself is not strict enough; server-side software, which could be JSP and Servlets or cgi service; and up-to-date browser.

Advantages of Ajax over HTML and HTTP

HTML and HTTP are weak because they are not interactive and use coarse-grained updates. Web applications are more frequently being designed to run inside the browser because everyone has one, so your application does not require software installation and your users will always get the latest version. Ajax provides frequent small updates to the application's content rather than relying on infrequent large updates that normally need to be asked for by the user.

Ajax-vs-html.png

Three formats used by Ajax systems to interchange data between client and server

XML

  • Human readable
  • Strict syntax format - no room for error
  • Support for schemas and namespaces, which has two main benefits:

The ability for party A to specify the format of the data and party B to check that they are supplying something that matches this format. Crucial when passing data between different systems, where a deviation from the expected format might mean that the data cannot be processed or worse, processed incorrectly.

The ability to mix data intended to be written or read by multiple sources in the same document. With the SOAP protocol namespaces allow for the separation of 'Envelope' or 'Wrapper' data, which is passed alongside the serialised application data.

  • Parsing standards - DOM, SAX, StAX
  • Standards for querying - XQuery and XPath

JSON

  • More compact, which means it's quicker loading, especially on slow networks
  • More structural information in the document
    • Can easily distinguish between the number 1 and the string "1" because numbers, strings and booleans are represented differently in JSON
    • Can easily distinguish between single items and collections of size 1 using JSON arrays
  • Easier to represent a NULL value
  • Easily consumed by JavaScript

Text

The basic Ajax process
function loadDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState === 4 && this.status == 200) {
            // handle the response
            document.getElementById("demo").innerhtml = this.responseText;
        }
    };

    // This is where you create the request
    xhttp.open("GET","ajax_info.txt","true");
    xhttp.send();
}

Java-based Questions and Answers

final, finally, and finalize - what are the differences and what are best practices?

final is used for read-only fields, classes that should not have sub-classes, or methods that should not be overridden. finally is part of the try/catch structure to denote code that should always run, whether an exception was thrown or not. Finalizers shouldn't be used very much at all, but provide a mechanism to run code when an object is being garbage collected. They may have been replaced by cleaners now.

final fields prevent you from assigning a different value or object reference to that variable but you can change the content of the object if what was assigned was a reference to a mutable object.

final Person person = new Person("Joe")
person.setName("Miller")

Java Garbage Collector - when does it run? Can you force it to?

The garbage collector runs when it thinks it needs to. Because the Java garbage collector is generational, different groups of objects are considered with different frequencies. Newly-allocated objects are checked for garbage more frequently than older objects. You can suggest that the garbage collector run by calling System.gc (though like finalizers, you generally shouldn't need to do this).

How does String concatenation (String1 + String2) act differently to using the StringBuilder class?

Simple string concatenation in Java can be transformed by the compiler into code that uses a StringBuffer or StringBuilder. The only time it matters is when you are doing concatenation in a non-simple way, like concatenating in a loop or doing piecewise concatenation across many methods. In those cases, the StringBuilder will be more efficient.

Strings in Java are immutable - once created they wont be modified. Adding one to the other still keeps it in memory, so if you loop over it 100 times, you will have 100 objects that will take up memory, will force you to run the garbage collector and so on. StringBuilder is the oposite - it operates on one object and modifies it as it sees fit.

What happens to a variable if you don't declare an access status (public, private, protected)?

Members without access modifiers are package-private by default. Any code in the same package is able to access them. Package-private is more public than private, but less public than protected.

How do each of the types of errors behave? What is a checked / unchecked method? What is the most common error, how is it managed? What happens when there is an error during compile time vs runtime and how can you manage them? Can you ignore them? How/when?

The hierarchy looks like this:

   Throwable
       |
  +----------+
  |          |
Error    Exception
             |
      RuntimeException

Unchecked exceptions are RuntimeException and its subclasses. Checked exceptions are Exception and its subclasses, except RuntimeException and its descendants. Error is off to the side.

Checked exceptions may only be thrown by a method if it is listed in the method's header. Unchecked exceptions can be thrown at any time, and the most common is probably NullPointerException. They do not need to be declared in you method's header. Errors can also be thrown at any time, but generally represent conditions that are difficult to recover from, like OutOfMemoryError.

public class RunTimeException {
    public static void main(String[] args) {
        String foo = null;
        foo.length();  // kaboom!
    }
}

will compile and run, however, when it runs it will blow up with a NullPointerException

public class CompileTimeError {
    public static void main(String[] args) {
        String foo = 4; // kaboom!
    }
}

will not let you compile it, meaning that it will never run. Attempting to compile it results in the message

java: incompatible types: int cannot be converted to java.lang.String

For compile time errors you can't really work around them, you have to fix them in order to run. Runtime exceptions you can handle more, using try/catch or other error handling patterns. maybe if an ArithmeticException occurs you could tell the user that they gave a bad input, instead of your entire program just stopping. Perhaps you want to log all exceptions that occur, perhaps you want to try the action again, etc. There is a lot more flexibility there.

What is special about the Set datatype, what happens if I put multiples of an identical object into a set instead of, say, a list?

Sets contain at most one of any given object. Whether two objects are seen as the same is determined by their equals method, but keep in mind that something else is usually consulted as well. HashSet uses hashCode as a coarse-grained equality check (i.e. two objects with the same hash code might be equal to each other, but two objects with different hash codes will never be equal to each other), and SortedSet will use the provided comparer or the object's own compareTo method to cut down the set of objects that must be compared with equals. Technically, a SortedSet might never call equals - compareTo is like a richer equals, and is supposed to be consistent with equals.

A common beginner mistake is to override equals without also overriding hashCode.