dimanche 31 juillet 2016

Design pattern: child class calling base class

I have "Handlers" able to trigger "Brokers" (an object that does something - not important here).

Handlers are listening to different kind of events:

  • TimeEvent: Every 10 seconds, 10 minutes (...)
  • FileSystemEvent: Once a file copied/moved/deleted
  • DbEvent: When a record is added to a DB table
  • MailEvent: When I received an email in my Office 365 mailbox

Each handler must have:

  • Start and stop methods (start/stop catching events)
  • An instance of the associated broker
  • A way to "trigger" the broker (Process method + specific set of arguments).

Each handler should

  • Trigger the associated broker when a specific event is raised

I want to trigger brokers from the base Handler class so I centralize my logic (fire events, catch exception, manage threads etc.). However, the base handler doesn't know how to call the broker (when to call this function, what parameters to send to the Process method) >> Only specialized children handlers know how to do that.

The only way I found is to implement in the base handler an Execute method accepting an Action parameter... I don't like this approach as it's not really straight forward (child needs to call base class otherwise nothing happens). I was hoping to find a better design to handle this. In addition I can tell you my developers will tell me they don't understand how to use the system.

abstract class Handler : IHandler
{
    public IBroker Broker { get; protected set; }

    public event ProcessedEventHandler Processed;
    protected void OnProcessed(ProcessExecutionResult result) => Processed?.Invoke(this, result);

    public static IHandler Create(IBroker broker)
    {
        if (broker is ITimerTriggeredBroker)
            return new TimeHandler((ITimerTriggeredBroker)broker);
        return null;
    }

    protected Handler(IBroker broker)
    {
        if (broker == null) throw new ArgumentNullException(nameof(broker));
        Broker = broker;
    }

    public abstract void Start();
    public abstract void Stop();

    protected void Execute(Action action)
    {
        var res = new ProcessExecutionResult();
        try
        {
            action?.Invoke();
            res.IsSuccess = true;
        }
        catch (Exception ex)
        {
            res.Exception = ex;
            res.IsSuccess = false;
        }
        finally
        {
            OnProcessed(res);
        }
    }
}

TimeHandler (handling Time related events)

class TimeHandler : Handler
{
    private readonly Timer _timer;
    private readonly DateTime _start;
    private readonly TimeSpan _frequency;

    public TimeHandler(ITimerTriggeredBroker broker)
        : base(broker)
    {
        _start = broker.Trigger.StartTime;
        _frequency = broker.Trigger.Frequency;
        _timer = new Timer(_ => Execute(broker.Process));
    }
 (...)
}

FileHandler (handling FileSystem related events)

class FileHandler : Handler
{
    private readonly FileSystemWatcher _watcher = new FileSystemWatcher();

    public FileHandler(IFileTriggeredBroker broker)
        : base(broker)
    {
        if (!Directory.Exists(broker.Trigger.DirectoryPath))
            throw new DirectoryNotFoundException("Unable to locate the supplied directory");

        _watcher.Filter = broker.Trigger.Filter;
        _watcher.Path = broker.Trigger.DirectoryPath;
        _watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.DirectoryName |
                                NotifyFilters.FileName;

        _watcher.Created += (s, a) =>
        {
            if (IsCopied(a.FullPath)) Execute(() => broker.Process(a.FullPath));
        };
    }

Abstract Design Pattern

I am in process of building an application that converts documents from and to different formats. For example it will covert Word, Excel to PDF. To do so I use Office API and multiple third party libraries.

For example, if Excel is installed on user's computer I will be using Excels' API otherwise will use a third party library to do the job. My problem is in implementing Abstract Factory Pattern. I added class library for each component: "MsExcel", "Excel3rdParty", "MsWord", "Word3rdParty", "PDF" and "Common". Each project references "Common" project where I plan to keep all Interfaces and each class library will implement its own component. I apologize in advance for noob question but home someone can help me because already 2nd week i am trying to make it work and no luck. Thank in advance!

public interface IOfficeFactory
{
    IExcelFactory GetExcelDocument(string documentType);
}

public class ExcelFactory : IOfficeFactory
{
    public IExcelFactory GetExcelDocument(string documentType)
    {
        switch(documentType)
        {
            case "Excel":
                return new Excel();
            case "IExcel3rdParty":
                return new IExcel3rdParty();
            default:
                throw new ApplicationException(documentType + "type can not be created");
        }
    }
}

public class IExcel3rdParty : IExcelFactory
{
    public IExcelFactory GetExcelDocument(string documentType)
    {
        return new IExcel3rdParty();
    }
}

public class Excel : IExcelFactory
{
    public IExcelFactory GetExcelDocument(string documentType)
    {
        return new Excel();
    }
}

public interface IExcelFactory
{
}

public interface IExcel : IExcelFactory
{         
}

public interface IIExcel3rdParty : IExcelFactory
{         
}

Design pattern for methods that return object and NRVO

I have class:

class A{
public:
    A(int v){
        this->v=new int;
        *(this->v)=v;
    }
    ~A(){
        delete v;
    }
    A add(A &a, A  &b){
        A res(0);
        *(res.v)=*(a.v)+*(b.v)+*v;
        return res;
    }
    int get(){
        return *v;
    }
private:    
    A();
    int* v;    
    void operator=(const A &other);
    TreePointer(const A &other);
};

I want to use it as follows:

A finalRes=a.add(b,c).add(a,a);

It works perfectly, there is no any leaks memory. But how to implement a similar behavior and usage, without using NRVO optimization? What standard design patterns exist for this purpose?

Asked in an Interview I won't be able to program this pattern:Dynamic programming

The program of this pattern should be dynamic

Thanks

samedi 30 juillet 2016

Factory class should be singleton or static method?

I made a class which create various instance. It's like a factory. As i know the factory class is singleton or create instance as static method. but my class is spring prototype scope. it has member variable. also there are methods have to call on sequence set member variable after each methods call.

I want to know in this case how does it design. could you recommend better way or good naming?

I’m working on spring framework and java 8..

@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class FruiteFactory {

    private String type;
    @Setter
    private Integer field;  // set alfter call appleSupplier

    public FruiteFactory(String type) {
        Assert.notNull(type) ;
        this .type = type ;
    }

    public < T> T create(Class<T > clazz) {
        Object result;
        if (clazz == Apple.class) {
            result = appleSupplier.get();
        } else if (clazz == Banana. class) {
            result = bananaSupplier.get();
        } else {
            throw new IllegalArgumentException();
        }
        return (T ) result;
    }

    private Supplier<Apple> appleSupplier = () -> {
        Apple apple = new Apple();
        // ...
        return apple;
    };

    private Supplier<Banana> bananaSupplier = () -> {
        Banana banana = new Banana();
        banana.setField(field);
        return banana;
    };
}


@Service
public class FruiteService {
    @Autowired ApplicationContext context;

    public void buy(String type) {
        FruiteFactory fruiteFactory = context.getBean(FruiteFactory.class, type);

        Apple apple = fruiteFactory.create(Apple.class);
        // save the apple

        Integer no = apple.getNo();
        fruiteFactory.setField(no);

        Banana banana = fruiteFactory.create(Banana.class);
        // ....

    }
}

Why interface is used in observer pattern?

I have read in the book that the application layer is supposed to be independent of the presentation layer. Design pattern are solution to problem like that. Observer pattern is applicable when an object should be able to notify other objects without making assumptions about who those objects are.But a method such as addObserver adds the observers to the list of observers. After that, observerable know which objects are to be notified. And how those list are used? In the book I read, it said that the observerable only access observer through the interface defined in the application layer so that the layer architecture of the system is preserved. Then the interface use that list? lf so, what is the difference?

Resolution independence in LWJGL

So I started programming a game with LWJGL again and have a design question for you:

Where to position elements with absolute coordinates when resolution is dynamic.

I did it in the past like this:

  public static final float dX = SCREEN_WIDTH/1920f;
  public static final float dY = SCREEN_HEIGHT/1080f;

enter image description here

So when I wanted to add an image I tried it on FullHD on which coordinates it looked good and multiplied with dX/dY.

In my opinion I think there could be a better approach to achieve this in LWJGL but I am to inexperienced to find one.

Avoiding duplication of an if/else statement

I am buliding an application that should have some walk through only when the user is loggedin for the first time.

Each page of the application has its own implementation of how to show the walk through

I don't want to ask on every page if (firstTime) ... How can I avoid that duplication of that statement, what is the right design pattern?

It's an Angular 2 application so each page is a component... I thought it will be good to create a base component and on his ngOnInit ask that if. And then in the children implement on each one the same function. Is it possible to extend components?

vendredi 29 juillet 2016

What design pattern I should use if I want to work on something that could be generalized later

Imagine that I am working for a software company A, and the company has a dedicated business unit B working on a set of infrastructure technologies. And I work in the business unit C, and we use the system been built by B to develop our own system. Currently, if the systems built be Business unit B is insufficient to support our use case, and we want business unit B to improve their system to support us. However, our request is not highest pri for B at this moment, and we have to build our in house solution.

Now the question is, when building our in house solution, if we want to generalized this system to business unit B in the future, what should we keep in mind when building our system.

The answer I am looking for are like: should be build a library so that others could link to, or should be build our system to be a service that others could call, or should we work with business unit B together at design stage to develop some parent class for the basic unit, and our system inherit from. Or, any suggested design patterns we should use ? etc

Does this application apply Decorator Pattern?

I am new to Design Pattern and currently I am reading the Beginning SOLID Principles and Design Pattern and have reached to the Decorator Pattern section. I have already known that:

The decorator pattern allows you to dynamically attach additional functionality to a class.

The book has an example application that allow adding watermark to the original photo.

I have made my decision to implement the same application to archive the same goal but with a difference approach. The application behaves as expected but I am currently struggling how my approach different from the Decorator one (the example on the book) so I decided to ask. Any explanation would be appreciated. Here is the code:

public interface IRender
{
    void Render();
}

public class Photo
{
    IRender iRender;
    public void SetRender(IRender iRenderParam)
    {
        iRender = iRenderParam;
    }

    public void RenderPhoto()
    {
        iRender.Render();
    }
}

public class NormalRender : IRender
{
    public void Render()
    {
        Console.WriteLine("Normal Render");
    }
}

public class WaterMarkRender : IRender
{
    private void RenderWaterMark()
    {
        Console.WriteLine("Render WaterMark");
    }
    public void Render()
    {
        RenderWaterMark();
    }
}

public class Program
{
    static void Main(string[] args)
    {
        Photo photo = new Photo();
        photo.SetRender(new NormalRender());
        photo.RenderPhoto();

        photo.SetRender(new WaterMarkRender());
        photo.RenderPhoto();

        Console.ReadLine();
    }
}

Factory pattern implementations with different parameters

I am trying to make a factory that creates classes that use the same base class(or interface) but the concrete factories need different parameter sets. If feel like I'm doing something wrong since these different Enums require extra code. Could this be done better?

Classes to be created:

public interface IShapeData {}

public abstract class ShapeDataWithCorners : IShapeData
{
    public double Width { get; set; }
}

class Square : ShapeDataWithCorners {}

class Rectangle : ShapeDataWithCorners
{
    public double Height { get; set; }
}

class Circle : IShapeData
{
    public double Radius { get; set; }
}

class Oval : IShapeData
{
    public double Radius1 { get; set; }
    public double Radius2 { get; set; }
}

Factories:

public enum RoundShapeTypes
{
    Circle,
    Oval
}

public enum CornerShapeTypes
{
    Square,
    Rectangle
}

public class RoundShapeDataFactory : IShapeDataFactory
{
    private readonly RoundShapeTypes m_shapeType;

    public RoundShapeDataFactory (RoundShapeTypes shapeType)
    {
        m_shapeType = shapeType;
    }

    public IShapeData CreateShapeData ()
    {
        switch (m_shapeType)
        {
            case RoundShapeTypes.Circle:
                return new Circle ();
            case RoundShapeTypes.Oval:
                return new Oval ();
        }
    }
}

public class CornerShapeDataFactory : IShapeDataFactory
{
    private readonly CornerShapeTypes m_shapeType;

    public CornerShapeDataFactory (CornerShapeTypes shapeType)
    {
        m_shapeType = shapeType;
    }

    public IShapeData CreateShapeData ()
    {
        switch (m_shapeType)
        {
            case CornerShapeTypes.Square:
                return new Square ();
            case CornerShapeTypes.Rectangle:
                return new Rectangle ();
        }
    }
}

Classes that call the factory:

public class RoundShapeManager
{
    public IShapeData CurrentShapeData{get; set; }

    public void SetShapeType (RoundShapeTypes shapeType)
    {
        RoundShapeDataFactory factory = new RoundShapeDataFactory (shapeType);
        CurrentShapeData = factory.CreateShapeData ();
    }
}

public class CornerShapeManager
{
    public IShapeData CurrentShapeData {get; set; }

    public void SetShapeType (CornerShapeTypes shapeType)
    {
        CornerShapeDataFactory factory = new CornerShapeDataFactory (shapeType);
        CurrentShapeData = factory.CreateShapeData ();
    }
}

These "managers" are actually WPF viewmodels that will can change their representative displayed data at run-time. I removed the viewmodel specific code for brevity.

Why does Abstract Factory deal with families, and Factory Method with generating a single object?

From what I have read, the abstract factory pattern typically concerns itself with creating several objects which are all associated with the same family, and the factory method pattern concerns itself with generating a single object.

Consider the following example, which flips those concerns:

// Factory Method (base class) allowing for creation of families of objects
public class BasePizzaCreator{
    abstract ISauce CreateSauce();
    abstract IToppings CreateToppings();
    abstract ICrust CreateCrust();
}

// Abstract Factory (interface) defining contract to create a single object
public interface IPizzaFactory{
    abstract IPizza CreatePizza();
}

It is obvious that you can use them this way - but is it a violation of the spirit of the patterns? If so, why?

What I really want to understand here is this: Why is Abstract Factory the better approach for creating families of related objects, and Factory method the better approach to creating a single object?

Tasks design pattern with conditions

All the snippet code will be in java while my code will be implemented in scala, so maybe some solution could get use of the advantages of that language.

I'm trying to perform some post-conditions over some data I get after executing some code and would like to know the best pattern to use.

Let's see that when executing the command I can pass by parameter (this is java) certain information.

-DallTheSame=true -DconcreteExpectedResultPerUnit=3,1,1 -DminimumThreshold=60

Then I started to look into the best approach to solve the problem of how to be able to extend that in some future.

1. Visitor Pattern

All of the parameter will have an associated class

class AllTheSameCheck
class ConcreteExpectedResultPerUnitCheck
class MinimumThresholdCheck

all will implement the visit and then the time to execute the checks come, the same object will visit all of them and if required, will execute the check

class AllTheSameCheck {
    public void visit(Object object) {
        if(isAllTheSameDefined()){
            // do the check
        }
    }
}

and the same code for the others.

2. Decorator Pattern

Same as before in terms of classes

class BasicCheck
class AllTheSameDecoratorCheck extends BasicCheck
class ConcreteExpectedResultPerUnitDecoratorCheck extends BasicCheck
class MinimumThresholdDecoratorCheck extends BasicCheck

but it will not be a decorator as per see, because in the main execution code they will need to be defined with conditionals

Main Code:

BasicCheck basicCheck = new BasicCheck()
if(isAllTheSameDefined()){
    basicCheck = new AllTheSameDefined(basicCheck)
}
if(isConcreteExpected...Defined()){
    basicCheck = new ConcreteExpected....(basicCheck)
}

So, having into account that all the post-conditions are defined when executing the tests, which is the best design pattern in that case?

Thanks a lot!

Add a method to a function that calls the function

Creating a module I ended designing a pattern where I attach methods to a function, and I'm not sure if it is correct. It is a closure that returns a function that has some methods attached which in turn calls the function itself. I don't know if this is a bad practice or if it is considered to be ok. My objective is to provide ways to call the function with certain presents or in different ways, but I want to retain the ability to just call the function in its simpler form. Would this lead to memory leaks or anything like that?

I'm not making use of this at any point, so no danger of losing context.

Below you can find a code snippet with a simplified version.

function factory( general ){

    var pusher = setTimeout(function(){ console.log('$',general) },1000);
    var counter = 0;

    function reporter ( specific ){
        counter++;
        console.log(counter, general , specific)
    }

    reporter.middleware = function ( something ){
        clearTimeout(pusher);
        return factory ( general + something )
    }

    return reporter
}

Thanks in advance.

jeudi 28 juillet 2016

PERL: Regex Pattern (": ")

I have a text file containing some JSON content. The file is really big and it containing more than 1,00,000 lines. So manual extraction is not fair. I have written the PERL script to read each line of the file, which meets my need.

Sample Text file : Sample.txt

  "key": "Programming",
  "doc_count": 1

  "key": "Base",
  "doc_count": 1,

  "key": "Experience",
  "doc_count": 1

  "key": "Electrophoresis",
  "doc_count": 1

I would like to take the key value alone covered within double brackets, say Programming, Base, Experience and Electrophoresis.

PERL script tried: ExtractKeyValue.pl

use strict;
use warnings;

my $file = $ARGV[0];
open my $info, $file or die "Could not open $file: $!";

while( my $line = <$info>)  {
    if($line =~ /"key(.*)",/){
        print $1;
        print "\n";
        }
}

close $info;

By using this, I am getting the output like,

": "Programming
": "Base
": "Experience
": "Electrophoresis

I don't want that ": ". I have tried like, $line =~ /"key: "(.*)",/. But it is not working. The command executes but no output and no error symptoms.

G:\ExtractKeyValue_Regex>perl ExtractKeyValue.pl Sample.txt > Output_Sample.txt

G:\ExtractKeyValue_Regex>

The output should be like,

Expected Output:

Programming
Base
Experience
Electrophoresis

I could not figure out why the colon(:) and space and double quotes is not tracked by the pattern.

Any suggestion would be helpful!

Functional Programming approach for Queue pattern

Can a queue handling async operations be implemented under the principles of Functional Programming? It's an AsyncQueue basically.

var list = [];
var inProgress = false;

function Queue() {}

Queue.prototype.enqueue = function(data) {
    list.push(data);
    if(!inProgress) {
         inProgress = true;
         start(list.shift());
    }
}

function start(data) {
    // initiate some async activity, and call dequeue on completion
}

function dequeue() {
    if(list.length) {
       start(list.shift());
    } else {
       isProgress = false;
    }
}

Evidently there's some kind of state getting managed, both with the list and inProgress, not sure how can this be converted into it's Functional Programming equivalent. F# code also welcome.

Is it bad practice to use and set global variables in promise

It's common that some information, returned from a certain promise, need to be used in a later step. One example is db connection:

database.connect()
    .then(dbConnection => runStepOne(dbConnection))
    // runStepOne is async and needs db
    .then(returnValOfStepOne => runStepTwo(returnValOfStepOne, dbConnection))
    // runStepTwo needs both stepOne's return value and db - this is totally reasonable
    // but dbConnection is not available here anymore

To circumvent this, I usually do:

var db;
database.connect()
    .then(dbConnection => db = dbConnection)
    .then(() => runStepOne(db))
    // access global
    .then(returnValOfStepOne => runStepTwo(returnValOfStepOne, db))
    // access global again

Question is, is this right or wrong? Are there any better patterns for this problem?

What is best practice for production Java classes that need support for Junit testing?

I end up creating most methods as protected just to be able to import it in my Test class - but wonder what is best practice?

Design pattern for child class that contains child property

I'm wondering if there is a design pattern that would solve this problem. I have a structure that looks like this:

    public abstract class DBAccess
    {
         protected MetaData metaData;
    }

    public class OldDBAccess: DBAccess
    {
         //this class will set metatData = new OldDBMetaData(); in the constructor
    }

    public class NewDBAccess: DBAccess
    {
         //this class will set metaData = new NewMetaData(); in the constructor
    }

    public abstract class MetaData
    {
        //some variables and methods that belong to all MetaData objects
    }

    public class OldDBMetaData : MetaData
    {
        string oldName;
        //some variables and methods that belong to only OldDBMetaData objects
    }

    public class NewDBMetaData : MetaData
    {
        //some variables and methods that belong to only NewDBMetaData
    }

I want to be able to call a method in OldDBAcess that sets properties that belong to OldDBMetaData. Since metaData is a MetaData object and not an OldDBMetaData object, I've had to do this so far:

    //method in OldDBAccess
    public void SetOldName(string name)
    {
       if(metaData is OldMetaData)
       {
           OldMetaData metaData = (OldMetaData)AccountMetaData;
            if (metaData == null)
                // metaData isn't of type OldMetaData
            else
                metaData.oldName = name;
        }
     }

This works just fine, I just don't want to have to check that metaData is of type OldMetaData every time I call a method. I know that it's of this type because I set it to this type in the constructor. I want to use the metaData property in either of the derived classes or the base class, so I can't just create properties in each of the DBAccess classes. Is there a design pattern or some easy way to do this with this kind of structure?

Prevent Jackson @JsonUnWrapped to introduce duplication

I am developping an application architectured this way.
A BaseObject contains the following fields :

public class BaseObject {
    private String id;  
    private Instant creationDate;  
    private String createdBy;  
    private Instant lastEditionDate;  
    private String lastEditBy;  
    private Instant deletionDate;  
    private String deletedBy;
}

Every class extends this BaseObject so I end up with two POJOs like this :

public class Pojo1 extends BaseObject {
    private SubPojo1 subPojo1;
    private SubPojo2 subPojo2;
}

public class Pojo2 extends BaseObject {
    private SubPojo3 subPojo3;
    private SubPojo4 subPojo4;
}

These two POJOS do not have a functional relationship. They are constituted of SubPojo which group fields in a functionnal way.

Here come my problem. My application is sending data to a BI app by JSON. The BI app need to get the POJO to a "flat" format and I want to exclude the BaseObject fields.

So i came up with this :

public class FlatPojo1 extends Pojo1 {
    @Override
    @JsonIgnore
    public String getId() {
        return super.getId();
    }
    /* Override every getter of BaseObjet */

    @Override
    @JsonUnwrapped
    public SubPojo1 getSubPojo1 {
        return super.getSubPojo1();
    }
    /* Override every getter of Pojo1 */
}

My solution is working, the BI app get the data properly formatted and I can still handle my objects with sub-objects.

The thing that disturb me is the code duplication. For each flat object, I have to override every getter of my BaseObject. I would like not to.

Java does not allow multiple heritage so I can not make an abstract class that @JsonIgnore every BaseObject field and also extending my Pojo1.

I tried to come with an interface like this :

public interface BaseObjectInterface {
    String getId();
    Instant getCreationDate();
    // etc
}

My BaseObject now implements BaseObjectInterface, everything is ok.Then the plan is to create a FlatData interface that will @JsonIgnore the BaseObject fields and every FlatPojo will implements this interface. I came up with this :

public interface FlatData extends BaseObjectInterface {
    @Override
    @JsonIgnore
    default String getId() {
        BaseObjectInterface.super.getId(); // Error
    }

I get an error message telling me that I can not call an abstract method. And I can not make a default getId() method in my BaseObjectInterface because such would require an id field and every field in an interface are static.

I can not find a way to avoid duplicating all theses @JsonIgnore. Is there any way to do it ?
Thank you for your help.

Multiple patterns d3 svg

I want to change the background when the mouse is over a circle, but each circle has a different image

Here is my visualization

and this is my code, I don't know why is not working. It seems that the SVG is OK but when the mouse is over a circle nothing happens and I don't know what I'm doing wrong.

  var circle = svg.selectAll("circle")
    .data(nodes)
    .enter().append("circle")
    .attr("class", function(d) { return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root"; })
    .style("fill", function(d) { return d.children ? genderColor(d) : null; })
    .attr('id', function (d) { return 'circle-' + d.object.id; })
    .on('mouseover', circleMouseOver)
    .on('mouseout', circleMouseOut)
    .on("click", function(d) { if (focus !== d) zoom(d), d3.event.stopPropagation(); });


var defs = circle
    .append('defs')
    .append('pattern')
    .attr('id', function(d) { return 'pic-' + d.object.id; })
    .attr('patternUnits', 'userSpaceOnUse')
    .attr('width', 115.5)
    .attr('height', 100)
    .append('svg:image')
    .attr('xlink:href', function(d) { return d.object.funcionario.foto.thumbnail; })
    .attr("width", 115.5)
    .attr("height", 100)
    .attr("x", 0)
    .attr("y", 0);

  function circleMouseOver (d) {
    d3.select(this)
      .style("fill", "url(#pic-"+ d.object.id +")");
    d3.select('#text-' + d.object.id)
      .text(function(d){
          return d.object.cargo.categoria.nombre;
      })
  }

when to use module vs prototype?

Module pattern vs prototype pattern appear to do similar things in js. They essentially wrap a bunch of js code to encapsulate and provide a type of OO interface. Are these techniques essentially interchangeable or are there scenarios where one of these techniques should be used instead of the other?

DB FK & Referential Integrity, how to handle this data?

I have a situation that I am not sure how to handle. Let me start by saying that I am mainly a software programmer, fairly comfortable with databases and design, but am not an expert. My current task is to build a system which will call out to various social media APIs, and download data for numerous accounts which I have credentials for, across the various platforms. I have built C# applications using entity framework to call the APIs, translate the results into entities, and insert them into a DB.

I have designed a database which follows the structure of the API objects that are being returned to me, the structure of which is not really important, except to know that I am building a fairly normalized DB using foreign keys where appropriate.

Consider the example of Twitter, where we have

TABLE [User]
(
  UserID INT PK NOT NULL,
  --etc
)

and

TABLE [Tweet]
(
  TweetID INT PK NOT NULL,
  TweetingUserID INT FOREIGN KEY REFERENCES User(UserID),
  --etc
)

The problem we've seen has popped up, I believe mostly because our API apps are still in "sandbox mode", and we are not getting a full set of data from the API calls, that is, we might get the first 10 users when asking for "followers", regardless of the total number who follow me, but when asking for timeline tweets, I will just get back the first 20 tweets, regardless of who posted them.

SO, when I try to insert all the tweets I was given, after inserting all the users that were returned, some of the time, I will be given a tweet, created by a user who was never returned from the API call. There is a user ID present on the Tweet side, but that ID doesn't exist in the User PK. This causes a PK violation error, and the whole save operation (all entities for a given account) are thrown out.

What is the correct way to deal with a situation like this? My options, as I see them, are

A: Scan the local dbSet & the database for each entity I download that has a FK to check and make sure the referenced entity exists before trying to set the FK property, and setting it to null or a fake "missing entity" record on the PK side. This seems really inefficient, and would require me writing a whole bunch more code for every single API call type.

B: Removing all the FKs from the database so there is nothing to be violated. Leave it up to the dba's to just use outer joins and detect when a join ID is missing when they aggregate/warehouse the data. This seems wrong from a DB design perspective, and would also break all of my reference properties in the EF model.

Is there some technique I don't know of that solves this problem? Are my hands just tied on using FKs because of the quality of the data I'm getting? Have I missed something obvious?

Thanks!

DAO vs ESB for Database interaction

Can someone help me to understand the most efficient way to interact with a database. Is it a good idea to use ESB (ex: Datapower) or DAO classes in Java to interact with databases? What are the pros and cons of each approach.

How to remove Validation from the service layer

I am trying to create a service layer, however I am unsure how can I decouple my validation from the service, as it doesn't really look DRY for me. I am using ASP.net 4.0 c# with EF.

Here are my layers

BO - Business Object - Share accross all layers
DAL - Data Access Layer
BLL - Business Layer
Service - Service layer

This is one of my business object

    public class Person:Base
    {
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public DateTime DOB { get; set; }
        //public virtual Prefix PrefixID { get; set; }
        public virtual Gender GenderID { get; set; }
        //public virtual Ethnicity EthnicityID { get; set; }
    }

In my DAL folder I have two things, I have PersonDAL, GenderDAL and I have Repository Pattern IGenderRepository, IPersonRepository.

This is how they look

Repository

public interface IPersonRepository : IDisposable
{
    Person PersonID(int id);
    IEnumerable<Person> PersonFN(string _firstname);
    IEnumerable<Person> PersonLN(string _lastname);
    IEnumerable<Person> PersonDOB(DateTime _dob);
    IEnumerable<Person> List();
    void Edit(Person entity);
    void Add(Person entity);
    void Delete(Person entity);
    void Save();
}

public interface IGenderRepository : IDisposable
{
    IEnumerable<Gender> List();
    Gender GenderID(int _id);
    Gender GenderDesc(string desc);
    void Edit(Gender entity);
    void Add(Gender entity);
    void Delete(Gender entity);
    void Save();
}

Data Access Layer

public class PersonDAL : IPersonRepository
{
    private AppContext db;
    public PersonDAL(AppContext _context)
    {
        this.db = _context;
    }

    public IEnumerable<Person> List()
    {
        return db.Person.ToList<Person>();
    }

    public Person PersonID(int id)
    {
        return db.Person.FirstOrDefault((p) => p.ID == id);
    }

    public IEnumerable<Person> PersonFN(string _firstname)
    {
        return db.Person.Where<Person>((p) => p.FirstName == _firstname );
    }

    public IEnumerable<Person> PersonLN(string _lastname)
    {
        return db.Person.Where<Person>((p) => p.LastName == _lastname);
    }

    public IEnumerable<Person> PersonDOB(DateTime _dob)
    {
        return db.Person.Where<Person>((p) => p.DOB == _dob);
    }

    public void Add(Person p)
    {
        db.Person.Add(p);
        Save();
    }

    public void Edit(Person p)
    {
        db.Entry(p).State = EntityState.Modified;
        Save();
    }

    public void Delete(Person p)
    {
        Person _p = db.Person.Find(p.ID);
        db.Person.Remove(_p);
        Save();
    }

    public void Save()
    {
        db.SaveChanges();
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                db.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

public class GenderDAL : IGenderRepository
{
    private AppContext db;

    public GenderDAL(AppContext _context)
    {
        this.db = _context;
    }

    public IEnumerable<Gender> List()
    {
        return db.Gender.ToList();
    }

    public Gender GenderID(int id)
    {
        return db.Gender.FirstOrDefault((g) => g.ID == id);
    }

    public Gender GenderDesc(string desc)
    {
        return db.Gender.FirstOrDefault((g) => g.Description == desc);
    }

    public void Add(Gender g)
    {
        db.Gender.Add(g);
        Save();
    }

    public void Edit(Gender g)
    {
        db.Entry(g).State = EntityState.Modified;
        Save();
    }

    public void Delete(Gender g)
    {
        Gender _g = db.Gender.Find(g.ID);
        db.Gender.Remove(_g);
        Save();
    }

    public void Save()
    {
        try
        {
            db.SaveChanges();
        }
        catch (Exception e)
        {
            Console.Write(e.Message);
        }
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                db.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

}

My business logic still follow the repository pattern

Repository for BLL

public interface IPersonBLL
{
    IEnumerable<Person> List();
    Person ID(int id);
    IEnumerable<Person> FirstName(string _first);
    IEnumerable<Person> LastName(string _last);
    IEnumerable<Person> DOB(DateTime dt);
    Boolean Update(Person p);
    Person Add(Person p);
    Boolean Delete(Person p);
}


public class PersonBLL : IPersonBLL
{
    #region Constant
    private PersonDAL db = null;
    #endregion

    public PersonBLL(AppContext context)
    {
        db = new PersonDAL(context);
    }

    public IEnumerable<Person> List()
    {
        return db.List();
    }

    public Person ID(int id)
    {
        var found = db.PersonID(id);
        if (found == null)
        {
            return null;
        }
        return found;
    }

    public IEnumerable<Person> FirstName(string _first)
    {
        if (_first == null)
        {
            return null;
        }
        return db.PersonFN(_first);
    }

    public IEnumerable<Person> LastName(string _last)
    {
        if (_last == null)
        {
            return null;
        }
        return db.PersonLN(_last);
    }

    public IEnumerable<Person> DOB(DateTime dt)
    {
        if (dt > DateTime.Now )
        {
            return null;
        }

        return db.PersonDOB(dt);
    }

    public Person Add(Person p)
    {
        if (p.FirstName != null)
        {
            if (p.LastName != null)
            {
                p.createdOn = DateTime.Now;
                p.updatedOn = DateTime.Now;
                db.Add(p);
                return p;
            }
        }
        return null;

    }

    public Boolean Update(Person p)
    {
        if (db.PersonID(p.ID) != null)
        {
            p.updatedOn = DateTime.Now;
            db.Edit(p);
            return true;
        }
        return false;
    }

    public Boolean Delete(Person p)
    {
        var found = db.PersonID(p.ID);
        if (found == null)
        {
            return false;
        }
        db.Delete(found);
        return true;
    }

}

To avoid extra text, the gender follow the same concept. Here is my service layer and this is where I am unsure how to proceed

My first question should I have each parameter seperated, or should I wrapped them in an object like Person but not knowing if I can access BO further more. Because it the data may come from the WebAPI or it could come from WPF application.

This is my interface for IPersonService

public interface IPersonService
{
    IEnumerable<Person> FindAllPerson(Person p, string errorMessage);
    Person FindPerson(int id, string errorMessage);
    Person CreatePerson(string first, string mid, string last, DateTime dob, string pref, string gend, string ethnic, string errorMessage);
    Boolean RemovePerson(int id, string errorMessage);
    Boolean UpdatePerson(int id, string first, string mid, string last, DateTime dob, string pref, string gend, string ethnic, string errorMessage);
}

I am not to sure how can I seperate the validation, it just seem not the right place for it.

public class PersonService : IPersonService {

    private PersonBLL _personRep = null;
    private GenderBLL _genderRep = null;
    //private PrefixBLL prefix = null;
    //private AddressBLL address = null;

    public PersonService()
    {
        _personRep = new PersonBLL(new AppContext());
    }

    public Person CreatePerson(string first, string mid, string last, DateTime dob, string pref, string gend, string ethnic, string errorMessage)
    {
        Person p = new Person();
        if (validatePerson(first, mid, last, dob, pref, gend, ethnic, errorMessage))
        {
            p.FirstName = first;
            p.MiddleName = mid;
            p.LastName = last;
            p.DOB = dob;
            Gender g = validateGender(gend, errorMessage);
            p.GenderID = g;
            return _personRep.Add(p);
        }
        return null;
    }

    public Boolean RemovePerson(int id, string errorMessage)
    {
        Person p = _personRep.ID(id);
        if (p == null)
        {
            errorMessage = "Person not found";
            return false;
        }
        else
        {
            return _personRep.Delete(p);
        }
    }

    public Boolean UpdatePerson(int id, string first, string mid, string last, DateTime dob, string pref, string gend, string ethnic, string errorMessage)
    {
        Person p = _personRep.ID(id);
        if (p == null)
        {
            errorMessage = "Person not found";
            return false;
        }
        else
        {
            if (validatePerson(first, mid, last, dob, pref, gend, ethnic, errorMessage))
            {
                if (first != "")
                {
                    p.FirstName = first;
                }

                if (first != "")
                {
                    p.MiddleName = mid;
                }
                if (first != "")
                {
                    p.LastName = last;
                }
                if (first != "")
                {
                    p.DOB = dob;
                }

                Gender g = validateGender(gend, errorMessage);
                if (g != null)
                {
                    p.GenderID = g;
                }
                return _personRep.Update(p);
            }
            return false;
        }

    }

    public IEnumerable<Person> FindAllPerson(Person p, string errorMessage)
    {
        var list = _personRep.List();
        if (list == null)
        {
            errorMessage = "No user found";
            return null;
        }
        return list;
    }

    public Person FindPerson(int id, string errorMessage)
    {
        if (_personRep.ID(id) == null)
        {
            errorMessage = "No ID matches this person";
            return null;
        }
        return _personRep.ID(id);
    }

    protected Boolean validatePerson(string first, string mid, string last, DateTime dob, string pref, string gend, string ethnic, string errorMessage)
    {
        if (first == null)
        {
            errorMessage = "First Name Missing";
            return false;
        }
        return true;
    }

    protected Gender validateGender(string gend, string errorMessage)
    {
        Gender g = _genderRep.GetGenderDesc(gend);
        if (g != null)
        {
            return g;
        }
        errorMessage = "Gender Description Did not match";
        return null;
    }
}

How to reduce ajax calls to server when using form autosave

Scenario:

Company in which I'm working is developing a website. User fills each field, it is validated and then on lose focus is sent an ajax to save data. We are also using debounce to reduce the calls to server, but it is still not enough.

Issues:

From user perspective there are no issues. Although, whenever we run automated test nightly builds (in parallel on multiple machines), the ajax requests are too many. There is a moment when response comes back slower and slower, and after some time the difference is noticeable, tests failing.

I though maybe there is another way to reduce ajax calls, for example, within time period (5 seconds etc.) these calls are saved into some kind of a list and after that time sent to server as one ajax call.

Questions:

  • How to implement behavior where in specific time period all ajax requests are stored in list and then sent as only one request (chunk)?
  • Is there a pattern like this or better way to reduce ajax calls to server?

Aggregation vs Composition

What I have googled so far Aggregation means that something can be part of something but doesn't need. Composition means that after parent component is destroyed, child is destroyed too.

But then I encounter following sentence in GoF book Design Patterns: "Aggregation implies that an aggregate object and its owner have identical lifetimes", which directly contradicts to what I have learned so far.

Funny is that I only found this explanation in this book and nowhere else, so who may to say that they are wrong :) I would rather say that whole google is wrong rather than this guys.

Python: process flow avoiding nested IF statements

I have a process (class) that I split into several steps (methods). each step can only be invoked if the previous one was successful. I created a method run() that runs the process by checking each step before invoking the next one:

def run(self):
    status = False
    if step_1():
        if step_2():
            if step_3():
                etc... [several nested IFs]
                status = True
            else:
                self.logger.error('Error in step 3')
        else:
            self.logger.error('Error in step 2')
    else:
        self.logger.error('Error in step 1')
    return status

Is there a more elegant way (a design pattern?) to avoid these nested IF statements?

Thanks a lot,

how can i using oops in php show csv file

i want to show the data from the database and csv file. I*m using oops in the php where i show data from both the database and csv but in the csv function there is following error:

syntax error, unexpected '$f' (T_VARIABLE), expecting function (T_FUNCTION) in D:\xampp\htdocs\factory\4.php on line 71

Code:

<?php
interface IDatabase {
    function connect();
        function readCSV();
}


class Db implements IDatabase
{
    private $connection;
    private static $instance;

    private function __construct()
    {
        $host = "localhost";
        $user = "root";
        $pass = "";
        $name = "cart";

        $this->connection = new mysqli($host, $user, $pass, $name);
   
   if(mysqli_connect_error()) {
                        trigger_error("Failed to conencto to MySQL: " . mysqli_connect_error(),
                                 E_USER_ERROR);
                }

   }

    public  function connect()
    {
        if (self::$instance == null) {                  
            self::$instance = new Db();
        }

        return self::$instance;
    }

    public function query($sql)
    {
        $result = $this->connection->query($sql);
        $records = array();
        while ($row = $result->fetch_assoc()) {
            $records[] = $row;
        }
        return $records;
    }
}


$db1 = Db::connect();





$query = $db1->query("SELECT * FROM user_info");
foreach($query as $row=>$val)
{ echo '<tr>';
                echo '<td>'.$val['id'].'</td>';
                echo '<td>'.$val['username'].'</td>';
                echo '<td>'.$val['email'].'</td>';
                                echo '<td>'.$val['password'].'</td>';
                                echo '</tr>';
}                               

class csv implements IDatabase{
public function readCSV($f){fclose($f);}



$f = fopen("http://localhost/csv/cr.csv", "r");
while (($line = fgetcsv($f)) !== false) {
        echo "<tr>";
                $data = count($line); 
        foreach ($line as $cell) {
                echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
}

?>

thymeleaf pattern dd/MM/yyyy

I try to validate an input date to have format dd/MM/yyyy like that :

<input type="date" th:pattern="${date_format}" th:field="*{subscriptionDate}"/>

In my controller, I add an attribute to my model like that :

model.addAttribute("date_format", "dd/MM/yyyy");

But when I submit my form I have this message from my input tag :

Please respect the format

Java regex Pattern matches doesn't recognise "Escape +" [duplicate]

This question already has an answer here:

I was trying the pattern ^\\+[0-9]+ to match '+852(2)78911' but it seems that

Pattern.matches("^\\+[0-9]+", s)

is returning false. When I tried it in regexr it is working i.e. giving me a match. Am I not escaping this correctly in Java sense?

Examples of use thread safe singleton in multiple threads

There is thread safe singleton, but when we use singleton in multiple threads? When it may be helpful?

Best way to avoid copy-paste and hardcoding

' Hello, SO community.

Problem: I have many regEx patterns, such as

r'to.*school', r'built.*in'

and etc. In every case, I should execute a code, that varies from situation to situation.

Example: If pattern is 'to.*school', I want to find the verb before 'to' and that's why I write something like:

for num, part in enumerate(sentence):
    if part == 'to':
        result = sentence[num-1]

If pattern is 'built.*in', I want to find the time and that's why I write something like:

for num, part in enumerate(sentence):
    if part == 'in':
        result = sentence[num+1]

So there's the problem - how can I avoid copy-pasting code, if there's over 500 patterns and each pattern has its own way to get result?

My thoughts: I understand it should be some kind of database, which stores patterns and solutions, but how do I execute solution, if it's a string? I'm totally lost.

show data using design pattern

I want to show data from the database and also from the csv file using the FACTORY PATTERN, as I wrote a code and in the code I only wrote for the database but the code is not working but its as rough code so can anyone tell me the right one?

<?php
interface IDatabase {
    function connect();
}

class Database implements IDatabase
{

    private $db_host;
    private $db_name;
    private $db_user;
    private $db_pass;
    private $connection = null;
    public $user_id;
    public function __construct($uid)
    {$this->user_id=$uid;}
   /* {

        $this->db_host = $host;
        $this->db_name = $name;
        $this->db_user = $user;
        $this->db_pass = $pass;
    }
public static function construct()
  {
    $this->db = new db();
  }*/
    public function connect()
    {
        if ($this->connection === null) {

        $host = "localhost";
        $user = "root";
        $pass = "";
        $name = "cart";

        $this->connection = new mysqli($host, $user, $pass, $name);

   if(mysqli_connect_error()) {
            trigger_error("Failed to conencto to MySQL: " . mysqli_connect_error(),
                 E_USER_ERROR);
        }

   }
        }
    public function query($sql)
    {
        $result = $this->connection->query();
        $records = array();
        while ($row = $result->fetch_assoc()) {
            $records[] = $row;
        }
        return $records;
    }
//  $db1= database::construct();

    $query = $uid->query("SELECT * FROM user_info");
foreach($query as $row=>$val)
{ echo '<tr>';
                echo '<td>'.$val['id'].'</td>';
                echo '<td>'.$val['username'].'</td>';
                echo '<td>'.$val['email'].'</td>';
                echo '<td>'.$val['password'].'</td>';
                echo '</tr>';

    }
    class csv implements IDatabase
    {

    }

?>

Decorator pattern using Java 8

Wikipedia has an example of a decorator pattern here:

http://ift.tt/1U7sg1Q

I was trying to solve this using functional style using Java 8,the solution I came up:

1.CoffeeDecorator.java

public class CoffeeDecorator {

public static Coffee getCoffee(Coffee basicCoffee, Function<Coffee, Coffee>... coffeeIngredients) {

    Function<Coffee, Coffee> chainOfFunctions = Stream.of(coffeeIngredients)
                                                      .reduce(Function.identity(),Function::andThen);
    return chainOfFunctions.apply(basicCoffee);
}

public static void main(String args[]) {

    Coffee simpleCoffee = new SimpleCoffee();
    printInfo(simpleCoffee);

    Coffee coffeeWithMilk = CoffeeDecorator.getCoffee(simpleCoffee, CoffeeIngredientCalculator::withMilk);
    printInfo(coffeeWithMilk);

    Coffee coffeeWithWSprinkle = CoffeeDecorator.getCoffee(coffeeWithMilk,CoffeeIngredientCalculator::withSprinkles);       
    printInfo(coffeeWithWSprinkle);

}

public static void printInfo(Coffee c) {
    System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
}

}

2.CoffeeIngredientCalculator.java

public class CoffeeIngredientCalculator {

public static Coffee withMilk(Coffee coffee) {
    return new Coffee() {

        @Override
        public double getCost() {
            return coffee.getCost() + 0.5;
        }

        @Override
        public String getIngredients() {
            return coffee.getIngredients() + " , Milk";
        }
    };
}

public static Coffee withSprinkles(Coffee coffee) {
    return new Coffee() {

        @Override
        public double getCost() {
            return coffee.getCost() + 0.2;
        }

        @Override
        public String getIngredients() {
            return coffee.getIngredients() + " , Sprinkles";
        }
    };
}

}

Now, I am not so convinced with the solution in the CoffeeIngredientCalculator. If we had a single responsibility in the Coffee interface, getCost(), using the functional style and applying the decorator pattern seems a lot better and cleaner. It would basically boil down to a Function<Double,Double> ,we would not need the abstract class, separate decorators and can just chain the functions.

But in the coffee example, with 2 behaviors of the cost and description on the Coffee object, I am not so convinced that this is a significant value addition as we are creating an anonymous class,overriding the 2 methods.

Questions:

1) Is this solution acceptable ?

2) If not, is there a better way to solve it using functional style?

3) Should we stick to the usual GOF way of having an abstract class and separate decorator classes in scenarios where the object that we are decorating has multiple methods?

mercredi 27 juillet 2016

What is the best way to have multiple components of a single type?

For example I want to generalize my existing trigger box component.

I use currently it the following way

<a-camera triggerbox="triggereventname: mytriggerbox"></a-camera> 

but instead I would like to be able to have

<a-camera triggerbox1="triggereventname: SmTB; x0: -20; y0: 0; z0: -20; "
triggerbox2="triggereventname: LgTB; width: 10; height: 10; depth: 10;"
></a-camera> 

and have multiple trigger boxes, not just one, attached to the camera (or any other element).

Unfortunately all the solutions I think of (e.g. re-registering the component with different names for each instance) are horribly ugly. What is the proper way to solve this?

Which Design Pattern to use for multiple interfaces

I have a requirement where I am trying to implement design pattern for a requirement where I need an interface1, interface2, interface3 all extending baseInterface and each interface can also have its specific methods.

Now I want to come up with a pattern so that I dont need to expose my interface1,2 and 3 to client except baseInterface but then how would i call the methods of interface 1,2 and 3.

Please suggest the closest design pattern that could be used.

using factory pattern to show from database and csv

with the help of factory pattern using php i want to show the data from the database and also from the csv file if possible using the switch case .so want to know the code for showing the data by factory pattern as i am new in this.

interface IDatabase {
    function connect();
}

class Database implements IDatabase
{
    private $db_type;
    private $db_host;
    private $db_name;
    private $db_user;
    private $db_pass;
    private $connection = null;

    public function __construct($db_type, $db_host, $db_name, $db_user, $db_pass)
    {
        $this->db_type = $db_type;
        $this->db_host = $db_host;
        $this->db_name = $db_name;
        $this->db_user = $db_user;
        $this->db_pass = $db_pass;
    }

    public function connect()
    {
        if ($this->connection === null) {
            try {
                $this->connection = new PDO($this->db_type.':host='.$this->db_host.';dbname='.$this->db_name, $this->db_user, $this->db_pass);
                $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $this->connection;
            } catch (PDOException $e) {
                return $e;
            }
        } else {
            return $this->connection;
        }
    }
}

How to avoid circular reference in python - a class member creating an object of another class and passing self as parameter?

I need some help in terms of 'pythonic' way of handling a specific scenario.

I'm writing an Ssh class (wraps paramiko) that provides the capability to connect to and executes commands on a device under test (DUT) over ssh.

class Ssh:
    def connect(some_params):
        # establishes connection
    def execute_command(command):
        # executes command and returns response
    def disconnect(some_params):
        # closes connection

Next, I'd like to create a Dut class that represents my device under test. It has other things, besides capability to execute commands on the device over ssh. It exposes a wrapper for command execution that internally invokes the Ssh's execute_command. The Ssh may change to something else in future - hence the wrapper.

def Dut:
    def __init__(some params):
        self.ssh = Ssh(blah blah)

    def execute_command(command)
        return self.ssh.execute_command(command)

Next, the device supports a custom command line interface for device under test. So, a class that accepts a DUT object as an input and exposes a method to execute the customised command.

def CustomCli:
    def __init__(dut_object):
        self.dut = dut_object
    def _customize(command):
        # return customised command
    def execute_custom_command(command):
        return self.dut.execute_command(_customize(command))

Each of the classes can be used independently (CustomCli would need a Dut object though).

Now, to simplify things for user, I'd like to expose a wrapper for CustomCli in the Dut class. This'll allow the creator of the Dut class to exeute a simple or custom command. So, I modify the Dut class as below:

def Dut:
    def __init__(some params):
        self.ssh = Ssh(blah blah)
        self.custom_cli = Custom_cli(self) ;# how to avoid this circular reference in a pythonic way?

    def execute_command(command)
        return self.ssh.execute_command(command)

    def execute_custom_command(command)
        return self.custom_cli.execute_custom_command(command)

This will work, I suppose. But, in the process I've created a circular reference - Dut is pointing to CustomCli and CustomCli has a reference to it's creator Dut instance. This doesn't seem to be the correct design. What's the best/pythonic way to deal with this?

Any help would be appreciated!

Regards

Sharad

How to determine a view for the polymorphic model in MVC

I have a list of entities. Each entity inherits some base class. In the controller I should determine a corresponding view for each entity object. How should I do that?

class BaseEntity {}
class FooEntity extends BaseEntity {}
class BarEntity extends BaseEntity {}

class View {}
class FooView extends View {}
class BarView extends View {}

Controller code:

BaseEntitty entities = repository.getSomeEntities();
List<View> views = new ArrayList();
for(BaseEntity in entities) {
    View view; //How can I determine the concrete view class?
    views.add(view);
}

P.S. A proper OOP solution is preferable.

Design Pattern: Using Null to minimize heavy Database Queries

I am currently a beginner developer working on a few side projects trying to make my way into the world of android java development. My question today however applies to most OOP driven concepts. Let me get to the point.

My Android Application has some activities and methods that end up having very heavy database queries, this makes it quite slow especially because i am using an ORM (SugarORM) to make things faster (Development wise) and less buggy.

I have already found a solution to this and it seems to be working quite well, however, i thought it would be best to ask about it before integrating it through out the application. Just to know if this is generally a bad practice or not.

Unfortunately, google wasn't very helpful, mostly because the keywords needed to search for a similar question would always take me to the Null Object Pattern :|

By Example of my implementation:

private List<Book> mBooks;

public List<Book> getBooks() {
    if (this.mBooks == null)
        this.mBooks = SugarRecord.listAll(Book.class);
    return this.mBooks;
}

public List<Book> onBookListUpdated() {
    this.mBooks = null;
}

As you can see this ensures that the query is only executed once (at least until the list is expected to have changed).

What i would need to know is if this makes sense, how many programmers would actually do something like this and if it is a thing what's it called?

Furthermore if it is 'ok' to do, would it be a good idea to wrap this logic in a class? Say something Like:

public class FastList<T> {

    public interface iFastList<TT> {
        List<TT> reloadList();
    }

    public FastList(iFastList<T> inCallback) {
        this.callback = inCallback; 
    }

    private iFastList<T> callback

    private List<T> currentList;

    public List<T> getList() {
        if (this.currentList == null)
            this.currentList = this.callback.reloadList();
        return this.currentList;
    }

    public void onListChanged() {
        this.currentList = null;
    }

}

Thanks in advanced to all that will take time to answer.

Why I am getting two different results for the same design?

Quick question:

I have a bunch (cloud) of coordinates and I tend to find the four corner coordinates of the whole bunch. And by corner I mean:

MyDesiredResult = { SmallestX, BiggestY, BiggestX, SmallestY }

I use this Old Routine to get my values:

double smallestX = MyCloud[0].X;       // assing X of first element to my result controller
var tempCoordPoint = MyCloud[0];       // assign first element to my result controller

for (int i = 0; i < MyCloud.Count; i++)
{
    if (smallestX > MyCloud[i].X)      // find minimum X
    {
        smallestX = MyCloud[i].X;
        tempCoordPoint = MyCloud[i];
    }
}

MyResult.Add(tempCoordPoint);           // add to my list

However, I would need to that Four Times (for the Four results). So I am trying to optimize my code by changing it to this New Routine which I use only once:

List<CoordPoint> MySortedList = MyCloud.Select(c => new CoordPoint { X = c.X, Y = c.Y, Z = c.Z, Color = c.Color }).ToList();

MySortedList.Sort((c1, c2) => c1.X.CompareTo(c2.X));     // sort on X
var temp = MySortedList[MySortedList.Count - 1];         // hold biggest X in a temp variable
MyResult.Add(MySortedList[0]);                           // add smallest X to my result

MySortedList.Sort((c1, c2) => c1.Y.CompareTo(c2.Y)); ;   // sort on Y
MyResult.Add(MySortedList[MySortedList.Count - 1]);      // add biggest Y to my result 
MyResult.Add(temp);                                      // add biggest X to my result
MyResult.Add(MySortedList[0]);                           // add smallest Y to my result

But it gives different results. I would want to show a sample input, current output and a desired output. I can skip the sample input (huge load) and show the results. Could anyone point me towards what I am doing wrong?

P.S The old routine is the correct one!

For the same input:

Result From Old Routine:

(0, 4), (15, 12), (23, 6), (19, 0)

Result From New Routine:

(0, 4), (18, 12), (23, 6), (18, 0)

enter image description here

is this a example where abstract factory pattern is used?

Now I am developing a class for recognize a object in a photo, and this class is composed of several components (classes). For example,

class PhotoRecognizer
{
 public:
    int perform_recogniton()
    {
        pPreProcessing->do_preprocessing();
        pFeatureExtractor->do_feature_extraction();
        pClassifier->do_classification()
     }

    boost::shared_ptr<PreProcessing> pPreProcessing;
    boost::shared_ptr<FeatureExtractor> pFeatureExtractor;
    boost::shared_ptr<Classifier> pClassifier;

}

In this example, when we use this class to perform recognition, we invoke other classes PreProcessing, FeatureExtractor and Classifier. As you can image, there are many different methods to implement each class. For example, for the Classifier class, we can use SVMClassfier or NeuralNetworkClassifer, which is a derived class of the basic Classifier class.

class SVMClassifier: public Classifier
{
 public:
    void do_classification();

};

Therefore, by using different elements within PhotoRecognizer class, we can create different kinds of PhotoRecongnizer. Now, I am building a benchmark to know how to combine these elements together to create an optimal PhotoRecognizer. One solution I can think of is to use abstract factory:

class MethodFactory
{
 public:
      MethodFactory(){};
        boost::shared_ptr<PreProcessing> pPreProcessing;
        boost::shared_ptr<FeatureExtractor> pFeatureExtractor;
        boost::shared_ptr<Classifier> pClassifier;

};
class Method1:public MethodFactory
{
  public:
     Method1():MethodFactory()
     { 
          pPreProcessing.reset(new GaussianFiltering);
          pFeatureExtractor.reset(new FFTStatictis);
          pClassifier.reset(new SVMClassifier);

      }

};

class Method2:public MethodFactory
{
  public:
     Method1():MethodFactory()
     { 
          pPreProcessing.reset(new MedianFiltering);
          pFeatureExtractor.reset(new WaveletStatictis);
          pClassifier.reset(new NearestNeighborClassifier);

      }

};



 class PhotoRecognizer
    {
     public:
        PhotoRecognizer(MethodFactory *p):pFactory(p)
        {
         }
        int perform_recogniton()
        {
            pFactory->pPreProcessing->do_preprocessing();
            pFactory->pFeatureExtractor->do_feature_extraction();
            pFactory->pClassifier->do_classification()
         }

       MethodFactory *pFactory;


    }

So when I use Method1 to perform photo recognition, I can simply do the following:

Method1 med;
PhotoRecognizer recogMethod1(&med);
med.perform_recognition()

Further more, I can even make the class PhotoRecognizer more compact:

enum RecMethod
{
  Method1, Method2

};

class PhotoRecognizer
{
public:
    PhotoRecognizer(RecMethod)
    {
       switch(RecMethod)
       {
          case Method1:
             pFactory.reset(new Method1());
             break;
           ...
         }
     }

    boost::shared_ptr<MethodFactory> pFactory;

};

So here is my question: is abstract factory design pattern well justified in the situation described above? are there alternative solutions? Thanks.

Class level design for validation engine with 2 independent entities

I have a use case where there will be 3 kind of data

  1. Business_Enrollment_Program (lets denote them with BEP_1, BEP_2 ...)
  2. Validation_Rule (lets denote them with R1, R2 ...)
  3. Transaction_Type (lets denote them TT_1, TT_2 ...). This is an entity class having some attributes. On these entities Validation_Rule need to be executed.

Transaction_Type entities will look something like

public TT_1 {
private Business_Enrollment_Program;
private COMMON_FIELD_1;
private COMMON_FIELD_2;
private TT_1_SPECIFIC_FIELD;
}

public TT_2 {
private Business_Enrollment_Program;
private COMMON_FIELD_1;
private COMMON_FIELD_2;
private TT_2_SPECIFIC_FIELD;
}

Now i have 2 requirement while executing Validation rules:

  1. Set of Validation_Rule that need to be executed depends on the Transaction_Type and it's Business_Enrollment_Program. That means for TT_1 enrolled under BEP_1 we might need to execute (R1,R2) rules but for TT_1 enrolled under BEP_2 we might need to execute (R1,R3) rules.

  2. Behavior of rule will depend on Transaction_Type and it's Business_Enrollment_Program. That means for TT_1 enrolled under BEP_1 behavior of rule R1 might be different compared to TT_1 enrolled under BEP_2

For rules i can create a structure like below:

public interface Rule <T> {
    public boolean execute(T transactionType);
}

public class R1_For_TT_1 implements Rule<TT_1> {
    public boolean execute(TT_1 transactionType) {
       //Do something here
    }
}

public class R1_For_TT_2 implements Rule<TT_2> {
    public boolean execute(TT_2 transactionType) {
       //Do something here
    }
}

And i can execute the rules like below

public processTransaction(T transactioType) {
    if(t instanceof TT_1) {
        R1_For_TT_1.execute(t);
    }
    else if (t instanceof TT_2) {
        R1_For_TT_1.execute(t);
        R2_For_TT_1.execute(t);
    }
}

Issue with this approach is i am not meeting my 2nd requirement where i wanted behavior of rule to depend on Transaction_Type and it's Business_Enrollment_Program.

Any idea how can i arrange my classes and entities so that both of my requirements are fulfilled elegantly?

What/How can I optimize for my news feed API?

This is more of an architectural question.

I am designing an API (lets call it API 1) for a mobile app that will query my API for new articles. I will call another API (lets call it API 2) that returns Raw news feed to me.

You ask why is API 1 needed at all? Well, it will do lot of optimization like curate edition specific news, format it in such a way that it is easier and light for the mobile to assimilate the feed.

So API 2 return 1000+ feeds to me and then based on my curation lets say I have 500 feeds to send using API 1. Now with caching and all it is all good for my backend. The problem is with the mobile devices (especially older ones). They start breaking a sweat with huge responses (270kb after Gzip).

My solution: Pagination:

I can split the 500 news articles to 5*100 articles. The app can request for page 1,2,3,4 and 5. Potential cons: When API 1 sends fresh articles the split of 5*100 is disturbed. For instance see the news feed on mobile device:

Article 1,

Article 2,

..

Article 99,

Article 100

----Page ended----

Article 101,

Article 102,

Now after API 1 refreshes feed:

New Article 1,

New Article 2,

Article 1,

Article 2,

..

----Page ended----

Article 99 (duplicate),

Article 100 (duplicate)

Article 101,

Article 102,

What are the best practices for such a problem?

How to remove circular dependency in strategy pattern

I'm trying to grok the strategy pattern and came up with following example

  • Would like to create new games based on chess except pieces moving differently.
  • Also want to use the strategy pattern to inject behaviors (how they can move) into the pieces.

But if we have Board, Piece, and MoveBehavior objects

  • Board -> Piece because a Board contains Pieces
  • Piece -> Board because a piece needs to pass in the Board to as a param to
    • MoveBehavior which needs the Board to decide what moves are acceptable.

How can we get rid of this circular dependency? Also isn't this a common problem in more realistic examples because behaviors need large enough state to make decisions? I think if behavior is super simple I assume it's not that big of a deal to not use strategy pattern.

1 click quick checkout how to design flow in JEE

I have a webshop on which I want to include a quick checkout (i.e. 1-click checkout) and wonder about the best way to design it.

Usually with normal checkout things are pretty easy. The user at some points wants to get to the order overview. That page requires an authenticated user, so when it is opened and no user is logged in, user gets redirected to login, logs in and gets redirected to order overview where I then know the user. He confirms and I start the checkout handling and redirect the user to the order confirmation page.

In the case of 1-click checkout things are bit different. The user invokes the checkout on a page where no authenticaton is required (usually a product page that anyone can browse), so I cannot directly start checkout workflow but need to redirect first to login and then redirect to some page from there and start the processing of checkout after login. Of course I could setup a success page that login redirects to and in the backing bean of that page in @postconstruct of the backing bean execute the checkout and then display an confirmation on the page.

Seems pretty ugly though.

Alternatively I could redesign the login part to not only work on pages with redirect but be able to revert to a method once login is completed. So do a redirect to login and then call a method that I registered with the loginbackingbean before redirecting to login page. Then in that method execute the checkout and refer to a success page. Sound a bit cleaner but also not nice.

Anbody some good ideas?

Cheers Tom

Controller action naming consistency in MVC

I'm confused about the action naming consistency in C# ASP.NET-MVC, let's say I have a simple application with following layer :

Controller -> Service layer -> Data Access layer

Data Access Layer contains a 1:1 class with my database table. Let's say I have 5 tables which is User, UserAddresses, Order, OrderDetails, Product

I want to group these into 2 groups so :

CustomerController contains anything related to User and UserAddresses
TransactionController contains anything related to Order, OrderDetails, and Product

My question is usually Action naming method in controller is something like

Index  
Create  
Edit  
Delete  
etc  

So in my case, how do I keep these naming pattern while I need a separate Create, Edit, and Delete page for User and UserAddreses.

Any help will be appreciated

Apologize for bad english

Design pattern to accommodate two different ways of handling a Winform's functions

I have a WinForm that I have used to build and test an email newsletter. This form contains a number of methods and events.

I am now adding a new feature to my program to allow split testing (A/X Test) and therefore creating up to 4 different newsletters for a campaign.

Therefore I'd like to extend my form to accommodate both normal newsletters and A/X newsletters. I'm going to add two different modes to my form. Something like:

private enum CampaignMode { Normal, AxTest };

They will be very similar in appearance, except a number of controls' visibility will change.

Apart from that, almost all methods and events will have two separate ways of handling.

What design pattern should I use so that I don't have to create a new separate form?

For simplicity, let's say my form has the following methods:

  1. Constructor: probably receiving the EditMode as a parameter
  2. Load
  3. Create: Button click event
  4. SetControlViews: Based on EditMode set the visibility of controls
  5. MethodA: Specific to Normal mode
  6. MethodB: Specific to AxTest mode

Does Immutability and Singleton solves the same perpose?

What I have read is Immutability means the value once assigned remains constant, i.e. once assigned, it is reflected as the same value across the code.

Mostly Immutability is using in Functional Programming paradigm in multi threaded environment.

But.

Does singleton pattern also solves the same purpose,

Please find below of singleton written in java,

 package com.main;

class Student{
  private Student(){

  }
  public static Student INSTANCE; 
  static{
    INSTANCE = new Student();
  }

  private String name;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Override
  public String toString(){     
    return "Student is "+this.name;
  }
}


public class SingletonTest {

  /**
   * @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Student student = Student.INSTANCE;
    student.setName("Arnold");

    student = Student.INSTANCE;
    student.setName("Kevin");

    student = Student.INSTANCE;
    student.setName("Jim");

    student = Student.INSTANCE;
    student.setName("Falcon");

    student = Student.INSTANCE;
    student.setName("Sarvik");


    student = Student.INSTANCE;
    System.out.println(student);

  }

}

The output of the above code is

Student is Sarvik

In an same way, I have written singleton in javaScript as well,

as follows

var Student = (function(){
  var name = "";
  var obj = {
    setName : function(studentName){
        name = studentName;
    },
    getName : function(){
        return name;
    }
  }

  return {
    INSTANCE : obj
  }
})();


var student = Student.INSTANCE;
student.setName("Arnold")

student = Student.INSTANCE;
student.setName("Kevin");

student = Student.INSTANCE;
student.setName("Jim");

student = Student.INSTANCE;
student.setName("Falcon");

student = Student.INSTANCE;
student.setName("Sarvik");

student = Student.INSTANCE;

console.log("Student is "+student.getName());

the output is as follows

rahul@rahul:~/myPractise/JavaScript-DesignPatterns$ node singleton.js 
Student is Sarvik
rahul@rahul:~/myPractise/JavaScript-DesignPatterns$ 

In both (i.e. javaScript and java) implementation of Singleton pattern you can see that the state of object remains same, it doesn't change.

Even if we reset the value of object, the output gives the latest reset value.

So does using Singleton pattern I attained Immutability in my code of object "Student" ?

Separating parts of a class which depend on a 3rd party API into a separate assembly

I'm developing an application that processes objects from 3rd party .NET API. Processors are created by implementing the following IProcessor interface.

public interface IProcessor
{
    Process(ApiClass input);
}

Concrete implementations of this interface may also add other properties to control how the specific processors work. For example...

public class ProcessorA : IProcessor
{
    public double X;
    public double Y;

    public Process(ApiClass input)
    {
       //Code here...
    }
}

public class ProcessorB : IProcessor
{
    public string MyParameter;
    public string MyOtherParameter;

    public Process(ApiClass input)
    {
       //Code here...
    }
}

The third party API and ApiClass only function from inside the native application. However, I would like to be able to create other .NET assemblies that are able to read and write Processors, but do not need to reference the 3rd party API. Specifically I want to be able to serialize/deserialize processors to/from JSON.

So, I'm trying to determine the best way to split the parameters of a Processor and its implementation of IProcessor.Process() into two separate assemblies. One that references the 3rd party API and another that doesn't.

One option would be to make duplicate proxy versions of the objects.

//In assembly that does NOT reference 3rd party API
public class ProcessorAProxy
{
    public double X;
    public double Y;
}

//In assembly that references 3rd party API
public class ProcessorA 
{
    public double X;
    public double Y;

    public Process(ApiClass input)
    {
       //Code here...
    }
}

But this would require that I keep the properties in sync between these classes. I would also have to write mapping code to translate between them.

Another option would be to store the parameters in the proxy class, and then create a class that inherits from this class which adds the Process() method.

//In assembly that does NOT reference 3rd party API
public class ProcessorA
{
    public double X;
    public double Y;
}

//In assembly that references 3rd party API
public class ProcessorA : ProcessorAProxy
{
    public Process(ApiClass input)
    {
       //Code here...
    }
}

This option no longer has duplicate properties that I need to keep in sync. Yet if I deserialized a ProcessorAProxy I'm not sure how I could then convert it to a real ProcessorA with out having to deal with mapping values again.

Alternative to inheriting classes I could also inject the options into the class that actually does the processing through its constructor.

//In assembly that does NOT reference 3rd party API
public class ProcessorAOptions: IOptions 
{
    public double X;
    public double Y;
}

//In assembly that references 3rd party API
public class ProcessorA : IProcessor
{ 
   public ProcessorAOptions Options;

   public ProcessorA(ProcessorAOptions opt)
   {
       Options = opt;
   }

    public Process(ApiClass input)
    {
       //Code here...
    }
}

I would then deserialize a specific type of IOptions, which would then need to get passed to the constructor of the correct concrete type of IProcessor. This could be handled by a ProcessorFactory.

IOptions options = serializer.Read(); //Read the some options
ProcessorFactory fact = new ProcessorFactory(); //Create a factory
IProcessor proc = fact.GetProcessor(options); //Get the processor for options from the factory

So far I like this option the best, but I'm not sure the best way for the ProcessorFactory to map from a specific types of IOptions to the correct IProcessor type.

One option would be to create a giant if statement that checks for each option, type.

if(opt.GetType() == typeof(ProcessorAOptions))
{
    return new ProcessorA((ProcessorAOptions)opt);
}
else if(opt.GetType() == typeof(ProcessorBOptions))
{
    return new ProcessorB((ProcessorBOptions)opt);
}
etc.. etc..

This works, but seems a little inefficient, especially if I have a lot of Processor types.

Another option would be to use conventions and reflection. For example find a class which implements IProcessor, and has a constructor which takes the specific IOptions type as a parameter. Or find a class with a name that equals the name of the options class with the "Options" suffix removed (ProcessorBOptions -> ProcessorB).

Is there a better option the using reflection? Overall is there a better way to split the code that references the 3rd party API and the code that doesn't into classes in separate assemblies that are some how mapped to one another?

mardi 26 juillet 2016

Does ReentrantLock use Decorator Design Pattern in java?

ReentrantLock contains an abstract class Sync, and Sync has two subclasses FairSync and NonFairSync. I want to know is this Decorator Design Pattern?

BTW, is there any good resources about Design Pattern usage in java source code?

Factory Design Pattern and Dimond OOP issue

Hello OOP Experts and Design Pattern Experts,

In one of my project, I have to implement Factory design pattern to solve a specific issue.

I have one parent interface and two child interfaces. In next stage, I have to create a factory which will return an instance of a specific class based on given input. Please see below SAMPLE code which is easy to understand my problem and sample image as well.

Sample Diagram

enter image description here

Sample Code

enum AnimalType{ DOG, CAT }

Class Factory{
    public Animal getInstance(AnimalType animalType){
        Animal animal = null;
        switch(animalType){
            case DOG: animal = new Dog();
                break;

            case CAT: animal = new Cat();
                break;
            default:
                break;
        }
        return animal;
    }
}

/*Actual Problem */
Animal animal = Factory.getInstance(AnimalType.DOG);

  /* When I use any IDE like IntellijIdea or Eclipse it only provides eat() method after animal and dot (ie. animal. ) */
animal.<SHOULD PROVIDE eat() and woof() from Dog> but it is only providing eat()

Separation of Data and Visuals for Polymorphic Data - Avoiding Downcasting

I'd like some sage wisdom on avoiding downcasting in non-model code.

Here's an example

Let's say I'm writing an application which is quite MVC-ish, and in the model I have a state machine:

class StateDriven {
 State current;

 void Progress() {
   current = current.Progress()
 }
}

abstract class State {
 public abstract State Progress();
}

class StateA : State {
  // StateA Specific methods, properties, and Progress implementation.
}

class StateB : State {
  // StateB Specific methods, properties, and Progress implementation.
}

Now Let's say I'm writing some UI code which wants to display a panel depending on the current state, with specific information for each state.

abstract class StatePanelUI<T> where T:State {
  protected T state;
  public abstract void Draw();
}

class StateAPanelUI : StatePanelUI<StateA> {
  public override void Draw() {
    // Logic for drawing a StateA
  }
}

class StateBPanelUI : StatePanelUI<StateB> {
  public override void Draw() {
    // Logic for drawing a StateB
  }
}

How can I know which type of panel to create without creating dependencies in the model? And once I create the panel, how can I inject the correct State subclass into it without downcasting?

I'm open to any methods/patterns/ideologies, but the key here is that the model can't depend on the visuals, because in my specific case I need to write several different UIs in several different environments.

Help appreciated!

Recursively searching an object and editing a string when found

I am new to python and having issues dealing with immutable strings. My problem is as follows:

I have a tree where each node is a dictionary and each node has variable number of children. I have multiple operations I wish to perform on this tree and therefore recursively traverse it.

The setup is that I have class that traverses the tree with the following function like so:

def __recursiveDive(self, node, enterFunc, leaveFunc, parentNode):
    if self.__break:
        return

    if not self.__skipNode:
        enterFunc(node, parentNode, self)
        if isinstance(node, dict):
            for key, value in node.items():
                self.__recursiveDive(value, enterFunc, leaveFunc, node)
        elif isinstance(node, list):
            for child in node:
                if isinstance(child, dict):
                    self.__recursiveDive(child, enterFunc, leaveFunc, node)

        leaveFunc(node, parentNode, self)
    else:
        self.__skipNode = False

enterFunc and leaveFunc are defined externally and perform the required work on the tree/node.

My issue is that since python strings are immutable I feel like I am unable to modify any string fields in the tree. The enterFunc, which is a function belonging to another class and is passed to the class is as follows:

def enter(self, node, parentNode, traverser):
    if isinstance(node, str):
        search = re.search(self.regexPattern, node)
        if search:
            node = node.replace(search.group(2),self.modifyString(search.group(2)))

The changes to node here are local only. Is my only solution to have the enter and leave functions return the node?

What is the correct/pythonic way to approach this problem?

this undefined in module pattern

I'm trying to use the Revealing Module pattern together with the Constructor pattern to create somewhat beautiful JS! I want to be able to create multiple instances if "Countdown" like this:

var c1 = new Countdown();
c1.init();
var c2 = new Countdown();
c2.init();

These should be independent. So instead of declaring variables with "var", I use "this" on the prototype. I reference "this" inside a function, but it's undefined. How can I access "this"?

var Countdown = function() {};

Countdown.prototype = (function(doc) {

    return {
        init: init
    };

    function init() {
        // day
        this.d1 = doc.createElement('div');
        this.d1.setAttribute('class', 'day-1 elem');

        // ... more elements left out here
    }

    function updateView(time) {
        this.d1.textContent = getDays(secs)[0];
    }

    function getDays(secs) {
        var result = 0;
        if (secs > 0) {
            result = secs / (60 * 60 * 24);
        }

        return Math.floor(result);
    }

})(document);

lundi 25 juillet 2016

Problems Before Observer Pattern

I understand what is observer pattern and what does observer pattern do. But what is the problem if I not use observer pattern. What are the problems before observer pattern and how observer pattern overcome it? If you can give the code before the applying the observer pattern and how it overcome the problem Thanks in advance

General purpose immutable classes in C#

I am writing code in a functional style in C#. Many of my classes are immutable with methods for returning a modified copy of an instance.

For example:

sealed class A
{
    readonly X x;
    readonly Y y;

    public class A(X x, Y y)
    {
        this.x = x;
        this.y = y;
    }

    public A SetX(X nextX)
    {
        return new A(nextX, y);
    }

    public A SetY(Y nextY)
    {
        return new A(x, nextY);
    }
}

This is a trivial example, but imagine a much bigger class, with many more members.

The problem is that constructing these modified copies is very verbose. Most of the methods only change one value, but I have to pass all of the unchanged values into the constructor.

Is there a pattern or technique to avoid all of this boiler-plate when constructing immutable classes with modifier methods?

Note: I do not want to use a struct for reasons discussed elsewhere on this site.

options for displaying notifications in the browser header?

I need a modern option for displaying a notification header to the user. The implementation needs to be cross-browser compatible and as lightweight as possible. My manager recommended the use of VanillaJs so a vanillaJs plugin would be ideal but if you can make a case for a better different solution then I can pass that along to my manager.

Also, the intent of this solution is to display the notification in a wide variety of websites across the enterprise. From a ux perspective do you think this design may be better implemented as a popup? I'm wondering if this may appear less shoehorned than displaying a modern notification header in an app with an older ui design.

return an object that show which element was clicked

I want to click a div called submitButton this should tell me what the users have done. I have 3 sections. A voting section, a review section, and another type of voting section. the point is that right now I'm trying to set up the first voting section. When I click the submitButton I should get a an object that looks like {vote:down} or {vote:up} I only have two buttons in the voting section.

function gatherData(){
    var submitButton = ".submitButton";
    var result = {}
    function voteSection(){
        $(".upButton").click(function(){
            // result.vote = "up"
            //  console.log(result) ;
            $(this).data("clicked", true);
            $(this).siblings(".downButton").data("clicked",false)
        })
        $(".downButton").click(function(){
            $(this).data("clicked", true);
            $(this).siblings(".upButton").data("clicked",false)
            // result.vote = "down";
            //  console.log(result) ;
        })
    //    return result;
    }
    $(submitButton).on("click",function(){
        if($(".upButton").data("clicked")){
            result.vote = "up"
        }else if($(".downButton").data("clicked")){
            result.vote = "down";
        }
    })
    return result;
}
$(".submitButton").on("click",function(){
    console.log(gatherData())
})

Thanks for any help

Recently implementing Command Patterns for my UNITY2D game, is this efficient enough? And what's the concrete benefit of it?

So today I am learning and implementing Command Patterns for handling input and movement for object.

So my question is:

  1. Am I getting the implementation of Command Patterns right?, or do I need to modify it? If so, can somebody give me a little example on to improve it..
  2. I know that it improves code reusability.. But what difference does it make when I just use a simple MovementScript.cs to my game object component? Wouldn't it just be the same and took less time to write rather making a whole Command Pattern?

EDIT: The one i attached to the gameobject is only the InputHandler.

Here's my code which involves moving an object:

This is my Input Handler or as far as i know as The Client

public class InputHandler : MonoBehaviour
{
GameObject theObject;
public Command buttonA, buttonD;
public float acceleration, maxSpeed;

Movement moves;

void Awake()
{
    theObject = gameObject;
    moves = new Movement(theObject, acceleration, maxSpeed);
}

void Start()
{
    buttonA = new MoveLeft(moves);
    buttonD = new MoveRight(moves);
}

void Update()
{
    HandleInput();
}

public void HandleInput()
{
    if (Input.GetKey(KeyCode.A))
    {
        buttonA.Execute();
    }
    else if (Input.GetKey(KeyCode.D))
    {
        buttonD.Execute();
    }
}
}

The Command abstract class

public abstract class Command
{

//The Receiver of the command..
protected IReceiver receiver = null;

public Command(IReceiver receiver)
{
    this.receiver = receiver;
}

public abstract void Execute();
}

The Receiver class (where i implements the logics, which is the movement)

public class Movement : IReceiver
{
public ACTION_LIST currentMoves;
private GameObject theObject;
private float acceleration;
private float maxspeed;

public Movement(GameObject theObject, float acceleration, float maxspeed)
{
    this.theObject = theObject;
    this.acceleration = acceleration;
    this.maxspeed = maxspeed;
}

public void Action(ACTION_LIST moves)
{
    if (moves == ACTION_LIST.MOVERIGHT)
        MoveRight(theObject);
    else if (moves == ACTION_LIST.MOVELEFT)
        MoveLeft(theObject);
}

public void MoveRight(GameObject obj)
{
    obj.GetComponent<Rigidbody2D>().AddForce(new Vector2(acceleration, obj.GetComponent<Rigidbody2D>().velocity.y));
}

public void MoveLeft(GameObject obj)
{
    obj.GetComponent<Rigidbody2D>().AddForce(new Vector2(-acceleration, obj.GetComponent<Rigidbody2D>().velocity.y));
}

}

Interface of receiver, to make things easier..

public enum ACTION_LIST
{
    MOVERIGHT,
    MOVELEFT
}

public interface IReceiver
{
    void Action(ACTION_LIST moves);
}

The concrete command, i only posted 1 of the movement..

public class MoveRight : Command
{
public MoveRight(IReceiver receiver):base(receiver)
{

}

public override void Execute()
{
    receiver.Action(ACTION_LIST.MOVERIGHT);
}
}

Thanks!