Boom Beach Tips

boom-beach-TOP-screenshots-pic-6

Boom beach: the awesome strategy mobile game that’s deceptively simple – as well as strategically challenging. It is practically two games -tower defense and real time strategy – in one. We hope that this collection of Boom Beach tips will be of help! Continue reading

Please like & share:

Monkey City Tips and Tricks

Do you like defense games? Monkey City is an exciting and sort of weird game where one makes monkeys to defend against swarms of colorful balloons (called “bloons” in the game) in order to claim pieces of land for their own.

Continue reading

Please like & share:

Review of Java Concepts 4th Ed. by Wiley Publishing

java script

 

Review of Java Script Concepts 4th Edition

By David Hsu

Wiley presents us with an intro to Java that presents its core concepts in a comprehensive way.; Its author, Cay Horstmann, teaches at San Jose State University. I used it as textbook for my college courses and am happy to have discovered that his book has greatly aided the writing of my Java tutorial. Consisting of  902 pages divided into 19 chapters, Review of Java Concepts is both well-organized and beginner-friendly.
Continue reading

Please like & share:

Collections & Sorting

Stamp Collector

Collections is a class with only static methods, devoted to operations on objects with collecting characteristics, List, Map, and Set. It can:

  • copy collections
  • put all contents of a collection into another
  • sort collections
  • reverse the order of collections
  • randomly shuffle a collection
  • find frequency of elements
  • and more, but perhaps the most often used is sort.

Sorting our objects can be done by three standard methods:

  • equals()
  • compareTo()
  • compare()

The latter two are the ways that Collections uses to sort data.

 

equals()

This is a method included with class Object, so therefore it is included with every type of object.

It returns a boolean value (true or false) saying whether this object is “equal” with another.

It can and is expected to be overridden to compare objects by your customized way.

Example (try it):

class Cat
{
   int age;
   Cat(int age)
   {
      this.age = age;
   }

   public boolean equals(Cat other)
   {
      return this.age == other.age;
   }
}

 

compareTo()

This method comes from the java.lang.Comparable<T> interface:

int compareTo(T object)

is implemented to compare this object with another to give a negative value for this object being less than, 0 for equals, or positive value for greater than the other.

This is the more convenient compare method, but must be implemented in every class you want to compare.

Example (try it):

class Cat implements Comparable<Cat>
{
   int age;
   Cat(int age)
   {
      this.age = age;
   }
 
   public int compareTo(Cat other)
   {
      if (this.age < other.age)
       return -1;
      else if (this.age == other.age)
       return 0;
      else
       return 1;
   }
}

Note that a simpler way to write the method above is:

return this.age - other.age; //- value for <, 0 for ==, + value for >

 

compare()

This method comes from the java.util.Comparator<T> interface:

int compare(T obj1, T obj2)

is implemented in a separate class that compares another class’s objects to give a negative value for the first object being less than, 0 for equals, or positive value for greater than the second object.

It is needed when you cannot make a class implement compareTo() because it is not modifiable. It is also used when you want different ways to compare objects, not just one (such as by name or age)..

Example (try it):

class Cat
{
   int age;
   Cat(int age)
   {
      this.age = age;
   }
}

class CatComparatorByAge implements Comparator<Cat>
{
   public int compare(Cat first, Cat second)
   {
      if (first.age < second.age)
         return -1;
      else if (first.age == second.age)
         return 0;
      else
         return 1;
   }
}
Please like & share:

Design Patterns

Design patterns are common, effective solutions to software design problems.

 

Iterator Pattern

An object traverses and accesses elements of a collection, rather than the programmer directly manipulating the collection.

Purpose is to simplify traversal of a collection and hide the details of its inner workings.

Example:

LinkedList list = new LinkedList();
//...add elements...
ListIterator iterator = list.listIterator();
while (iterator.hasNext())
{
     Object element = iterator.next();
     //do something with element
}

This is better than a version of LinkedList that would allow the user to access its nodes directly, like so:

Node node = list.head;
while(node != null)
{
     //do something with node.element
     node = node.next;
}

This is because this complicates things (in working with links) and thus is prone to errors.

In Java, list iterators can be imagined like the cursor in a text processor that moves along characters, the characters being like elements of a list.

Adding element adds it and advances the iterator position by one.

Adding element adds it and advances iterator position by one.

 

Singleton Pattern

A public one-of-a-kind object exists as a static variable.

Purpose is to ensure only one object of a type is publicly available.

Example:

class System
{
     //single God instance.
     static God god = new God(); 
     private class God
     {
          void create()
          {
          }
     }
}

 

Observer Pattern

Henri_Matisse,_1916-17,_Le_Peintre_dans_son_atelier_(The_Painter_and_His_Model),_oil_on_canvas,_146.5_x_97_cm,_Musée_National_d'Art_Moderne,_Centre_Georges_Pompidou,_Paris

An object notifies another object (the “observer”) whenever a change to a data has occurred.

Purpose for this pattern is encapsulation of data and distribution of responsibility.

Example:

//make button.
final JButton button = new JButton();
 
//make observer for mouse events.
MouseListener listener = new MouseAdapter()
{
     public void mouseClicked(MouseEvent e)
     {
          button.setText("clicked");
     }
};
 
//make it observe the button.
button.addMouseListener(listener);

Model-View-Controller (MVC) is an architecture that uses this pattern. Example: visualize a posing artist’s model (Model), a painter of the model (View), and a director of the model (Controller). The director controls the model’s state. Whenever it does, the model notifies the painter to update his representation of the model visible to the user.

Example:

// Model.
class Model
 {
     String state;
     Painter painter; //representer of model
 
     //notify painter when state changed.
     void notify()
     {
          painter.repaint(this);
     }
}
 
// View.
class Painter
{
     void repaint(Model model)
     {
          //update representation of model.
     }
}
 
// Controller.
class Director
{
     Model model;
     Director(Model model)
     {
          this.model = model;
     }

     void setModelState(String newState)
     {
          model.state = newState;
          model.notify();
     }
}

//The tester.
class Tester
{
     public static void main(String[] args)
     {
           Model model = new Model();
           model.painter = new Painter();
           Director director = new Director(model);
           director.setModelState("Sitting");
     }
}

Another way to think of Model-View-Controller, is Data-Output-Input. the input changes the data (as an interface to it), while the output represents the data to the user in whatever state it currently is in.

 

Adapter Pattern

A class (the “adapter”) implements an interface by blank methods to save its users from implementing every method when some are unneeded.

Purpose is nothing more than saving code.

Example:

//make button.
final JButton button = new JButton();
 
//make adapter implementing one method of an interface.
MouseListener listener = new MouseAdapter()
{
     public void mouseClicked(ActionEvent event)
     {
          button.setText("Clicked");
     }
};
button.addMouseListener(listener);

This is the same as, but shorter than, this:

//make button.
final JButton button = new JButton();

//make adapter implementing one method of an interface.
MouseListener listener = new MouseListener()
{
     public void mouseClicked(MouseEvent e)
     {
            button.setText("Clicked");
     }
     
 
     //implement unneeded methods as blank.
     public void mouseMoved(ActionEvent e)
     {  
     }
     public void mouseEntered(MouseEvent e)
     {
     }
 
     public void mouseExited(MouseEvent e)
     {
     }
 
     public void mousePressed(MouseEvent e)
     {
     }
 
     public void mouseReleased(MouseEvent e)
     {
     }
};
button.addMouseListener(listener);

 

Composite Pattern

composite

A class acts a container for its siblings and using this container simply uses all its contained objects, as a proxy.

Example:

abstract class Item
{
     abstract void use();
}
class Toy extends Item
{
     void use()
     {
          System.out.print("Beep!");
     }
}

class Perfume extends Item
{
     void use()
     {
          amount -= 1;
     }
 
     int amount = 10;
}

//Compositing class.
class Bundle extends Item
{
     # held items.
     List items = new ArrayList();
 
     # this simply calls use() of each held item.
     void use()
     {
          for (Item item: items)
              item.use()
     }
}

 

Decorator Pattern

rosiejetsons

A class acts as a container and proxy for a sibling, but also defines new features to enhance it.

This sounds like the Composite pattern, but Composite intends to collect, while Decorator intends to enhance.

Example:

//Class to be decorated.
class Robot
{
     void run()
     {
           ...
     }
}

//Decorating class.
class JetBot extends Robot
{
     //robot to enhance.
     Robot robot;
     JetBot(Robot robot)
     {
          this.robot = robot;
     }

     //enhancing features.      
     int fuel = 100;

     ...
}

 

Command Pattern

An action, in the form of an algorithm, is contained in an object to remember and use the algorithm later.

Example:

abstract class Job
{
     abstract void do();
}
class CleanJob
{
     void do()
     {
          //...
     }
}
class PrintJob
{   
     void do()
     {
          //...
     }
}

 

Strategy Pattern

Different algorithms that fulfill the same goal differently are saved.

Purpose is to save actions for use in different scenarios.

Similar to Command, but Strategy algorithms are intended for one goal, while Command algorithms are for different goals.

Example:

//strategy to sort Accounts.
class AccountComparatorByName implements Comparator<Account>
{
     public int compare(Account first, Account second)
     {
          return first.name.compareTo(second.name);
     }
}
 
//another strategy.
class AccountComparatorByID implements Comparator<Account>
{
     public int compare(Account first, Account second)
     {
          return first.id – second.id;
     }
}
 
//test: make list.
List list = new List();
list.add(new Account(8152, "David"));
list.add(new Account(1372, "Shawn"));
list.add(new Account(3283, "Ruth"));
 
//try sorting strategies.
Collections.sort(list, new AccountComparatorByName());
Collections.sort(list, new AccountComparatorByID());

 

Template Method Pattern

An abstract class contains one concrete method (the “template”) that calls several abstract methods, which are defined by concrete classes.

Example:

abstract class Game
{
     //Template method.
     void play(int players)
     {
          initialize();
          while (!isEnd())
               turn();
     }

     //Abstract methods.
     abstract void initialize();
     abstract void turn();
     abstract boolean isEnd();
}

class Chess extends Game
{
     void initialize()
     {
          //...
     }
     
     void turn()
     {
          //...
     }

     boolean isEnd()
     {
          //...
     }
}

class Poker extends Game
{
     void initialize()
     {
          //...
     }
     
     void turn()
     {

          //...
     }

     boolean isEnd()
     {
          //...
     }
}

 

Factory Method Pattern

A method implements an abstract method for only creating and returning objects.

Example:

abstract class AsexualOrganism
{
     abstract Object reproduce();
}
 
class Virus extends AsexualOrganism
{
     //factory method.
     Object reproduce()
     {
          return new Virus();
     }
}

Example:

//make list.
List list = new LinkedList();
 
//create iterator by the factory method iterator().
Iterator iterator = list.iterator();
 
//iterator() implements List’s method iterator().

 

Abstract Factory Pattern

An abstract class with factory methods has several subclasses in their own object creation theme.

Example: “LookAndFeel” classes for graphical applications

 

Chain Of Responsibility Pattern

Belt-conveyor-handling

Several handlers handle a request in sequence, like workers over a conveyor belt.

Example:

//make button.
final JButton button = new JButton();
 
//make two ActionListeners handling the same event.

ActionListener one = new ActionListener() 
{
     public void actionPerformed(ActionEvent e)      
     {
           System.out.println("Clicked!");
      } 
};

ActionListener two = new ActionListener() 
{
     public void actionPerformed(ActionEvent e)      
     {
          button.setEnabled(false);
      } 
};

button.addActionListener(one);
button.addActionListener(two);

 

Memento Pattern

An object’s old state is saved (like a “snapshot”) to later return to it.

Coupled with the Command Pattern, it is a useful pattern to create undo functionality by.

Example are found in How to Implement Undo/Redo.

 

Proxy Pattern

An object acts an interface (actor on behalf) to another object, being used exactly like that other.

Examples can be found in Adapter, Composite, and Decorator sections above.

Please like & share:

Software Process

The software process is the organized process of creating software, from its inception to obsolescence.

Software engineers broke down formally the software process into five stages:

  • Analysis
  • Design
  • Implementation
  • Testing
  • Deployment

Different software methodologies integrate these stages in their own way.

 

Analysis Stage

In the first step, we identify the whys of the software: what it will accomplish. This is done by:

  • Requirements specification
  • Use Cases/Storyboarding

Requirements specification is a document that:

  1. Details the functional (specific actions done) and non-functional (system constraints) requirements of the software.
    1. Functional example: System must authenticate user prior to servicing him/her.
    2. Nonfunctional example: System must authenticate under 1 second.
  2. Translates what the business owners want out of their software product into technical specifications as reference for the project team.
  3. Is a predictor of costs, production schedules, and risks of the software.

We record the steps of hypothetical cases of using the software called use cases. Example:

  Use Case: Eating

  1. Cat opens door.

  2. Cat pushes a dispenser button.

  3. Dispenser gives food.

  4. Cat eats food.

    Variation #1:

  5. Cat cannot open door.

  6. Cat waits for customer service.

  7. Continue with step 2.

Storyboarding is basically use cases but pictorially illustrated. Example (from wiki):

776px-Storyboard_for_The_Radio_Adventures_of_Dr__Floyd

 

Design Stage

Here, we plan what classes of objects will exist in the software and what each class is responsible for. This is done with:

  • CRC cards
  • Class diagrams
  • Sequence diagrams
  • State diagrams
  • Outlines in Javadoc

CRC cards are paper index cards used to identify:

  1. Classes that will exist in your program (usually the nouns found in the analysis stage)
  2. Responsibilities of those classes, ie. the methods (usually the verbs)
  3. Collaborators of each responsibility (which other classes are involved in each method)

crccard

Class diagrams are tables showing classes, their variables and methods, and relationships between them using arrows:

RELATIONSHIP Description Arrow Human Class Example
Aggregation Has as instance/class variable, “has-a” aggregation Has Arm
Dependence Manipulates, “uses” dependence Uses Food
Inheritance Subclasses, “is-a” inheritance Is Animal
Implementation Implements interface implementation Implements Worker

Example:

372px-KP-UML-Generalization-20060325_svg

Sequence diagrams show the timeline of a typical program run, in method calls (and optionally their return values). Example:

sequencediagram

State Diagrams show a program in different states with actions between them. Example:

statediagram

Outlining in Javadoc is writing Javadoc comments before blank classes and methods (“a program skeleton”) that would be filled out in the implementation stage. Example:

/** Cat.
     @author David Hsu
*/
class Cat
{
     /** Say something.
          @param what what to say.
     */
     void say(String what)
     {
     }

     /** Sleep.
          @param minutes number of minutes to sleep.
     */
     void sleep(int minutes)
     {
     }
}

 

Implementation Stage

Here, we give substance to the design of the previous stage by means of programming code.

Implementation may only result in a prototype (“earliest-type”), meaning incomplete software, but may still be runnable and it can be built on later.

 

Testing Stage

Here, we test the implemented product in all its aspects to ensure that each works properly.

Different kinds of testing exist, including:

  • Unit – testing each module of a software separately, to ensure it is working properly.
  • Regression – re-testing a software when a new feature has been added, to ensure it broke nothing that is older.

 

Deployment Stage

Here, the software product is released to the targeted audience.

This may include both installing and configuring the product on target systems.

 

Methodologies

Methodologies have been created to involve the above software stages in different ways to suit different software, most famously:

 

Waterfall Methodology

waterfall

The software process steps are done in sequence, but no step can be returned to after finishing it.

Its disadvantage is risk, because steps are often mistaken for finished when it really isn’t.

Its advantages are simplicity (and thus manageability) and suitable use in small projects where requirements are well understood.

 

Evolutionary Methodology

The software process steps are done in order, and any of those steps can be revisited at any time, as opposed to Waterfall.

 

Spiral Methodology

spiralmodel

The waterfall model but with all the steps repeated some number of times.

The products of the first few cycles are called prototypes (“earliest types”). A user interface prototype is common for this.

 

Extreme Methodology

This is a methodology that simplifies development by removing formal practices and focusing on the “best practices”, including:

  • Minimalizing the software (removing unnecessary things)
  • Refactoring (simplifying) code
  • Conforming to readable coding standards
  • Pairing programmers for tasks
  • Re-testing the whole software whenever a new feature is added
  • Scheduling consistent work hours to stabilize progress
Please like & share:

Print shortcut

These alternative ways help print to console faster and, thus, debug and other actions faster by shorter typing:

 

  • Use the import static statement:
import static java.lang.System.out;

To print, call:

out.println(something);

 

  • Another way is to write this method in whatever class you want to print something from:
static void say(Object o)
{
     System.out.println(o);
}

This acts like a proxy method to System.out.println(), which is no different at all from it, just a shorter name (you can also choose your own name of course).

You can now print by writing:

say(something);

 

  • If you need to use this method often, you can write it inside a new, preferably with a short name, class:
class I
{
     static void say(Object o)
     {
          System.out.println(o);
     }
}

 

Hope this will increase your productivity!

Please like & share: