mercredi 2 novembre 2016

a design pattern to replace do while and sleep

I'm using a rest API with two method:

  1. The first one start a job and it return the job id (RunJob).
  2. The second one get me the job termination stats:(GetJobStat

    This is the code that I'm using :

        var id = RunJob();
        Console.WriteLine(string.Format("id {0}",id));
        do
        {
            Thread.Sleep(100);
        } while (GetJobStat(id));
        Console.ReadLine();
    
    

    My question is there any better ways to manager my GetJobStat call than using do while with sleep, I'm searching for a design pattern to optimize my code.

Why Does Colon Mess Up Grep -v Option?

I was using grep to print all lines not containing :.

The code is:

grep -v '.*:.*' file.txt

However, it prints only the lines containing colon.

Why is that? I'm using grep GNU 2.25. Your positive support and input is highly appreciated.

Deciding a dessign pattern

I have this Map object, representing a GoogleMap. I may contain markers with info windows. Markers may be clustered. Markers may respond to DOM events (click, drag, etc.). All this stuff comes from 3rd party library egeloen/ivory-google-map.

I want to create this map, add Marker objects with coordinates, that are kept in database, add a InfoWindow according to informaction kept in the same database, but keep my controller clean form all this marker/infowindow creation repetitive code.

There are two cases:

  • Static map - markers are clustered, not draggable or removable, on click they show info window.
  • Editable map - markers are not clustered, they are draggable, new markers can be added on click, info window shows different content.

The use should look like:

$map = (new StaticMap($places))->getMap(); //places holds coordinates, infowindow content
// or 
$map = (new EditableMap($places))->getMap();

What design principals should I apply to reach this goal. Because I dont want controller to know about all these Marker, Map, InfoWindow classes.

My own solucion is to create abstract class for common behaviour.

abstract class AbstractMap
{
    public function __construct(array $place)
    {
        $this->map = new Map();

        $this->proccessPlaces($places);
    }

    public function getMap() {
       ...
    }
}

class StaticMap extends AbstractMap {}

class EditableMap extends AbstractMap {}

The proccess of creating markers, infowindows is verbose and I don't think the factory pattern is suitable. Maybe Builder or Decorator? Or maybe extend the 3rd party Map class and add missing behaviour?

c# func parameter not being used

I have a legacy app that logs the input / output of services. Currently, every method has the same lines to log the request and response objects. I would like to use AOP, but without adding any extra tool (Postsharp, Castle, etc), or wrap every service class into another class (ServiceWrapper).

In order to do that, I'm trying to create a Generic class that knows that it should log the request and response objects. Here's what I'm trying:

using System;

namespace ProxyTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var request = "request";
            var fooService = new FooService();

            ServiceProxy.Invoke(r => fooService.DoFoo(request), "abc");

            Console.Read();
        }
    }

    class ServiceProxy
    {
        public static void Invoke(Func<object, object> service, object request)
        {
            Console.WriteLine("input:" + request);

            var response = service(request);

            Console.WriteLine("output:" + response);
        }
    }

    class FooService
    {
        public string DoFoo(object a)
        {
            return a +  ": returning: Do Foo";
        }
    }

}

Although it's working, the "abc" string is just to compile the application, but it's not being used as the request parameter. If I remove that, the code does not compile. Am I missing something?

ManagedBean Design Issue

enter image description here

The image above is the template for my website. Left and top menus will stay forever (left one will be toogleable though). Only frame(green area) will change and when user scrolls, only the green area will be scrolled, menus will stay in screen.

So, my idea is to use <ui:include src="somepage.xhtml" /> when designing the webpage templated above. My problem is every ``` sub page will have its own managedbean. Is this a good design choice? And for the main managedbean how should i call subpages? by just firing an event on menu click and replacing the current frame? What will be the scope of frame beans? RequestScoped or ViewScoped?

Please guide me, thanks

mardi 1 novembre 2016

Javascript DRY Pattern - function

New to OO, I am making a game and I have this as my initialState :

let initialState = {
  grid : null,
  player : {
    coordinates : null,
    health : 100 ,
    weapon : "Stick",
    expLevel : 1
  },
  enemies : [],
  weapons : [],
  items : []
}

when DOM is loaded, I am able to initialize weapons and items corretly. However, both of these properties share the exact functionality except the object literal that is initialized :

initialState.weapons = placeWeapons(3);
initialState.items = placeItems(2);

where placeWeapons

function placeWeapons(numberofWeapons){
  let weapons = [];
  let availableSpots = [];
  let placementWeapons = []; //list of coordinates that will place weapons
  let grid = initialState.grid;

  //collect whats available of coords that are not taken in initialState.occupiedCoordinates
  grid.forEach( (row, rowIndex) => (
    row.forEach( (cell, colIndex) => {
      if (cell === 1){
        availableSpots.push([rowIndex,colIndex])
      }
    })
  ))

  //lets place the weapons. When placed, it will update initialState.occupiedCoordinates
  while( placementWeapons.length < numberofWeapons ){
    let randCoords = availableSpots[Math.floor(Math.random() * availableSpots.length)];
    if (grid[randCoords[0]][randCoords[1]] === 1){
      placementWeapons.push(randCoords);
      grid[randCoords[0]][randCoords[1]] = 0
    }
  }
  placementWeapons.forEach( coord => {
    let weapon = {
      name : "Weapon Name",
      coords : coord,
      damage : 3
    }
    weapons.push(weapon)
  })
  return weapons;
}

placeItems

function placeItems(numberofItems){
  let items = [];
  let availableSpots = [];
  let placementItems = []; //list of coordinates that will place items
  let grid = initialState.grid;

  //collect whats available of coords that are not taken in initialState.occupiedCoordinates
  grid.forEach( (row, rowIndex) => (
    row.forEach( (cell, colIndex) => {
      if (cell === 1){
        availableSpots.push([rowIndex,colIndex])
      }
    })
  ))

  //lets place the items. When placed, it will update initialState.occupiedCoordinates
  while( placementItems.length < numberofItems ){
    let randCoords = availableSpots[Math.floor(Math.random() * availableSpots.length)];
    if (grid[randCoords[0]][randCoords[1]] === 1){
      placementItems.push(randCoords);
      grid[randCoords[0]][randCoords[1]] = 0
    }
  }
  placementItems.forEach( coord => {
    let item = {
      name : "Item Name",
      coords : coord,
      health : 3
    }
    items.push(item)
  })
  return items;
}

How can I DRY this pattern?

What is the difference between Builder and Facade Pattern in C#?

In Builder Pattern, We implement all the methods defined in the Interface and then we make calls to the methods in a order to get result/product class

 class Director
    {
        public void Construct(IBuilder builder)
        {
            builder.BuildPartA();
            builder.BuildPartB();
            builder.BuildPartB();
        }
    }

    interface IBuilder
    {
        void BuildPartA();
        void BuildPartB();
        void GetResult();
    }

    class Builder1 : IBuilder
    {
        List<string> product = new List<string>();
        public void BuildPartA()
        {
            product.Add("PartA ");
        }

        public void BuildPartB()
        {
            product.Add("PartB ");
        }

        public void GetResult()
        {
            foreach (var p in product)
            {
                Console.WriteLine("the product created is :" + p);
            }
        }
    }

    class Builder2 : IBuilder
    {
        List<string> product = new List<string>();
        public void BuildPartA()
        {
            product.Add("PartX ");
        }

        public void BuildPartB()
        {
            product.Add("PartY ");
        }

        public void GetResult()
        {
            foreach (var p in product)
            {
                Console.WriteLine("the product created is :" + p);
            }
        }
    }

    class Product
    {
        List<string> parts = new List<string>();
        public void Add(string part)
        {
            parts.Add(part);
        }

        public void Display()
        {
            Console.WriteLine("\nProduct Parts -------");
            foreach (string part in parts)
                Console.Write(part);
            Console.WriteLine();
        }
    }

    public class Client
    {

        public static void Main()
        {
            // Create one director and two builders
            Director director = new Director();

            IBuilder b1 = new Builder1();
            IBuilder b2 = new Builder2();

            // Construct two products
            director.Construct(b1);
            Product p1 = b1.GetResult();
            p1.Display();

            director.Construct(b2);
            Product p2 = b2.GetResult();
            p2.Display();

            Console.Read();
        }
    }

In the Facade Pattern we Abstract all the methods implementation to the client and simply the steps to the user

 internal class SubsystemA
    {
        internal string A1()
        {
            return "Subsystem A, Method A1\n";
        }
        internal string A2()
        {
            return "Subsystem A, Method A2\n";
        }
    }
    internal class SubsystemB
    {
        internal string B1()
        {
            return "Subsystem B, Method B1\n";
        }
    }
    internal class SubsystemC
    {
        internal string C1()
        {
            return "Subsystem C, Method C1\n";
        }
    }
    public static class Facade
    {
        static SubsystemA a = new SubsystemA();
        static SubsystemB b = new SubsystemB();
        static SubsystemC c = new SubsystemC();
        public static void Operation1()
        {
            Console.WriteLine("Operation 1\n" +
            a.A1() +
            a.A2() +
            b.B1());
        }
        public static void Operation2()
        {
            Console.WriteLine("Operation 2\n" +
            b.B1() +
            c.C1());
        }
    }
    class Client
    {
        static void Main()
        {
            Facade.Operation1();
            Facade.Operation2();
        }
    }

In both the patterns we call a series of methods and create a result out of it. The only difference in the Builder Pattern is that it returns the product object of a class apart from that is there any other difference between Facade and Builder Pattern