Archive for the 'Engineering' Category

 

cache / caching notes ..

Nov 05, 2009 in Engineering

– Object dependencies

– expiration policies

– object priorities

– scavenging objects (on low memory conditions, using cache item priority)

Insert(key as String, value as Object, 
  dependencies as CacheDependency, 
  absoluteExpiration as DateTime, 
  slidingExpiration as TimeSpan, 
  priority as CacheItemPriority, 
  onRemoveCallBack as CacheItemRemovedCallback) 

– From: http://en.wikipedia.org/wiki/Weak_reference

…. – A weak reference is a reference that does not protect the referenced object from collection by a garbage collector:

…. – Used to re-connect to an object between the time the last reference was removed and the time the GC finds the object and collects it.

– From: http://msdn.microsoft.com/en-us/library/ms404247.aspx

…. – A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist.

– EHCache (Easy Hibernate Cache)

google: when, where and why use caching

http://en.wikipedia.org/wiki/Cache

http://memcached.org/

http://www.allapplabs.com/interview_questions/

Hash table notes..

Aug 26, 2009 in Engineering, Java, JavaUsage, Software

From http://techinterviewcoach.com/blog/?p=30#more-30

  • Hash tables are backed by arrays.
  • A hash function is used to map the keys to an index within the backing array.
  • Put, Get, Delete operations all run in constant ( O(1) ) time.
  • Hash function determines performance.
  • Even with the best hash function, collisions can occur.
  • Main advantage of HTs over other data structures is speed.
  • Growing HTs need to be rehashed but the cost is amortized by constant cost of ‘put’.
  • Should not use HTs for small data sets, but everybody does.
  • Rehashing should occur when the load factor (occupied array slots / array size) reaches over .75.

Extreme programming..

Jun 10, 2009 in Engineering, Software

Finally! A methodology that makes sense to me!

http://www.extremeprogramming.org/

Basic rules:

* Make frequent small releases.

* The project is divided into iterations.

* Move people around.

* No functionality is added early.

* Refactor whenever and wherever possible.

* The customer is always available.

* Write/Code the unit test first (with stubs).

* Integrate often.

* Leave optimization till last.

* All code must have and must pass unit tests.

* When a bug is found, unit tests are created.

* No overtime.

* Code must be written to agreed standards.

Interface vs Abstract Class ..

Apr 23, 2009 in Engineering, Java, JavaUsage, Software

  • — Inheritance from anything (including abstract)
    should be a function of the business model.
  • — If a class does not _really_ inherit from
    an abstract, one should not use it.
  • — Use interface to avoid the problem of multiple
    inheritance.
  • — Use interface to improve modularity.. if one
    uses an abstract class and the class changes,
    it may break subclasses.
    (not method signatures but logic/code.. changing
    method signatures is a problem for both abstract
    and interface)
  • — Use interfaces when some part of the design
    will change frequently.
  • — Interface for plug-in architectures – like
    the strategy pattern.
  • — Use abstract class to provide basic services
    for derived classes (event, message handling)
  • — In favor of abstract class:
    • — interfaces may be more difficult to read in
      code logic.
    • — interfaces are somewhat slower due to
      indirections.

Design Patterns with Java – Summary ..

Feb 10, 2009 in Engineering, Software

From
http://www.patterndepot.com/put/8/JavaPatterns.htm

  • Design patterns describe how objects communicate without becoming
    entangled in each other’s data models and methods.
    In other words, they describe methods for keeping objects decoupled.
  • Program to an interface and not to an implementation.
  • Favor object composition over inheritance.

Creational Patterns

All of the creational patterns deal with the best way to create
instances of objects. This is important because your program should not
depend on how objects are created and arranged.

  • The Factory Method provides a simple decision making class that
    returns one of several possible subclasses of an abstract base class
    depending on the data that are provided.
  • The Builder Pattern separates the construction of a
    complex object from its representation, so that several different
    representations can be created depending on the needs of the
    program.
  • The Singleton Pattern is a class of which there can be no more
    than one instance. It provides a single global point of access to that
    instance.

Structural Patterns

Structural patterns describe how classes and objects can be combined
to form larger structures. The difference between class patterns and object
patterns is that class patterns describe how inheritance can be used to provide
more useful program interfaces. Object patterns, on the other hand, describe
how objects can be composed into larger structures using object composition,
or the inclusion of objects within other objects.

  • The Adapter pattern is used to convert the programming interface of
    one class into that of another. The source interface is different than the target.
  • The Decorator pattern provides us with a way to modify the behavior
    of individual objects without having to create a new derived class.
    i.e. Add features to a class without inheritance and at runtime.
  • The Façade pattern allows one to simplify complexity by
    providing a simplified interface to complex subsystems.
    i.e. It is an aggregation mechanism.
  • The Flyweight design pattern provides an approach for handling
    many small objects (like characters in a font, for example).
  • The Proxy pattern is used when you need to represent a complex
    object by a simpler one. Used to interface to expensive-to-create
    objects. The source interface side of a proxy is the same as the
    target class (see Adapter).

Behavioral Patterns (page 129)

Behavioral patterns are those patterns that are most specifically
concerned with communication between objects.

  • The Observer pattern defines the way a number of classes can be notified
    of a change. i.e. subscribe and publish.
  • The Strategy pattern encapsulates an algorithm inside a class.
  • The Iterator pattern formalizes the way we move through a list
    or collection of data within a class using a standard interface.
    Enumerators are read-only Iterators.
  • Observer pattern..
  • MVC – Revisit:
  • The Strategy pattern
  • Visitor – revisit:

Software development methodologies notes..

Aug 26, 2008 in Engineering, Software

From http://en.wikipedia.org/wiki/Software_development_methodology

  • 3.1 Waterfall model
    .. is a sequential development process, in which development is seen as flowing steadily downwards (like a waterfall) through the phases of requirements analysis, design, implementation, testing (validation), integration, and maintenance.
  • 3.2 Prototyping
    .. is the framework of activities during software development of creating prototypes, i.e., incomplete versions of the software program being developed.
    .. Not a standalone, complete development methodology, but rather an approach to handling selected portions of a larger, more traditional development methodology (i.e. Incremental, Spiral, or Rapid Application Development (RAD)).
  • 3.3 Incremental
  • 3.4 Spiral
  • 3.5 Rapid Application Development (RAD)
    .. is a software development methodology, which involves iterative development and the construction of prototypes.
    .. Key emphasis is on fulfilling the business need, while technological or engineering excellence is of lesser importance.

Design Patterns – Singleton pattern (Creational) basic example..

Jul 12, 2008 in Engineering, Software

Pattern used to manage resources when a single instance of one is required
to coordinate actions across an application.

From http://en.wikipedia.org/wiki/Singleton_pattern

The simplest way:

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

The ‘lazy loading’ way.. by Bill Pugh (static code analysis with FindBugs and more..)

public class Singleton {
   // Private constructor prevents instantiation from other classes
   private Singleton() {}
 
   /**
    * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
    * or the first access to SingletonHolder.INSTANCE, not before. (lazy!)
    */
   private static class SingletonHolder { 
     private static final Singleton INSTANCE = new Singleton();
   }
 
   public static Singleton getInstance() {
     return SingletonHolder.INSTANCE;
   }
 }

Design Patterns – Factory pattern (Creational) basic example..

Jun 20, 2008 in Engineering, Software

This pattern allows the application to defer to runtime the decision of which
object from a related set to instantiate .

From http://en.wikipedia.org/wiki/Factory_method_pattern

abstract class Pizza {
    public abstract double getPrice();
}
 
class HamAndMushroomPizza extends Pizza {
    public double getPrice() {
        return 8.5;
    }
}
 
class DeluxePizza extends Pizza {
    public double getPrice() {
        return 10.5;
    }
}
 
class HawaiianPizza extends Pizza {
    public double getPrice() {
        return 11.5;
    }
}
 
class PizzaFactory {
    public enum PizzaType {
        HamMushroom,
        Deluxe,
        Hawaiian
    }
 
    public static Pizza createPizza(PizzaType pizzaType) {
        switch (pizzaType) {
            case HamMushroom:
                return new HamAndMushroomPizza();
            case Deluxe:
                return new DeluxePizza();
            case Hawaiian:
                return new HawaiianPizza();
        }
        throw new IllegalArgumentException("The pizza type " + pizzaType + " is not recognized.");
    }
}
 
class PizzaLover {
    /*
     * Create all available pizzas and print their prices
     */
    public static void main (String args[]) {
        for (PizzaFactory.PizzaType pizzaType : PizzaFactory.PizzaType.values()) {
            System.out.println("Price of " + pizzaType + " is " + PizzaFactory.createPizza(pizzaType).getPrice());
        }
    }
}

Design Patterns – Observer pattern (Behavioral) basic example..

May 25, 2007 in Engineering, Software

This is a (simplified) example from Vince Huston’s patterns pages. The part I found really neat is the self-registration methodology of observers.. normally, I expected the Subject to have an ‘add()’ method for observers.. this is a bit different.. nice..

// ObserverEx.java   

// From Vince Huston's site..

class ObserverEx {
    public static void main(String[] args) {
        Subject subj = new Subject();
        // Self-Register observers.. nice..
        new SomeObserver( subj );
        new OtherObserver( subj );
        // Do something to the subject..
    }
}

class Subject {
    private Observer[] observers = new Observer[9];
    private int        numObs  = 0;

    public void attach( Observer o ) {
        observers[numObs++] = o;
    }

    private void notifyObservers() {
        for (int ix = 0; ix < numObs; ix++) {
            observers[ix].update();
        }
    }

}

abstract class Observer {
    protected Subject subj;
    public abstract void update();
    public Observer( Subject subj ) {
        this.subj = subj;
    }
}

class SomeObserver extends Observer {
    public SomeObserver( Subject s ) {
        super( s );
        subj.attach(this);
    }

    public void update() {
        // Update from Subject..
    }
}

class OtherObserver extends Observer {
    public OtherObserver( Subject s ) {
        super( s );
        subj.attach(this);
    }

    public void update() {
        // Update from Subject..
    }
}


Design Patterns – Strategy pattern (Behavioral) basic example..

May 08, 2007 in Engineering, Software

A possible usage scenario without thinking ‘Strategy’ ..


// Example without using the Strategy pattern

public class WithOutStrategy { 

    public void doSomething(int theSwitch) { 

        if ( theSwitch == 0 ) { 
            AClass ac = new AClass(); 
            ac.doit(); 
        } 

        if ( theSwitch == 1 ) { 
            BClass bc = new BClass(); 
            bc.doit(); 
        } 

    } 

    public static void main(String[] args) { 

        WithOutStrategy sb = new WithOutStrategy(); 
        sb.doSomething(0); 
        sb.doSomething(1); 
    } 

} 

class AClass { 

    public void doit() { 
        System.out.println(">> doit A"); 
    } 

} 

class BClass { 

    public void doit() { 
        System.out.println(">> doit B"); 
    } 

}

And a better way of doing it with ‘Strategy’..


// Example using Strategy

public class WithStrategy { 

    public void doSomething(OClass oc) { 
        oc.doit(); 
    } 

    public static void main(String[] args) { 

        WithStrategy ows = new WithStrategy(); 
        OClass oc = null; 

        oc = new AClass(); 
        ows.doSomething(oc); 

        oc = new BClass(); 
        ows.doSomething(oc); 
    } 

} 

// Options class 

abstract class OClass { 
    public abstract void doit(); 
} 

class AClass extends OClass { 

    public void doit() { 
        System.out.println(">> doit A"); 
    } 

} 

class BClass extends OClass { 

    public void doit() { 
        System.out.println(">> doit B"); 
    } 

}