jeudi 26 mai 2016

Native MongoDB Driver Node.js - should we store collections?

I haven't been able to find any documents outlining if it's a bad / good idea to keep a reference to a collection so that it can be re-used after the db connection has been established.

for instance, in our database.ts which is called during our server start-up. It will grab the collections and store it for use in the module which can then be references throughout the project.

example of storing the collection

/*database.ts*/
//module to keep 1 connection alive and allow us to have 1 instance of our collections.
import {MongoClient, Db, Collection } from 'mongodb';

let uri: string = 'connection_string';

export let db: Db;

export let usrCollection: Collection;

export let bookCollection: Collection;

export function initDb(cb: any) {
  MongoClient.connect(uri, function(err, database) {
    //handle err        

    db = database;
    cb(); //returns now since db is assigned.
  });
}

export function initCollections() {
  usrCollection = db.collection('users'); //non-async
  bookCollection = db.collection('book'); //non-async
}

  
/*app.ts*/
  
//in our express app when it start up
import {db, initCollections, initDb} from './database';

initDb(function() {
  //this will hold up our server from starting BUT 
  //there is no reason to make it async.
  initCollections();
});

what are some of the short coming of this pattern/build? what can I improve and what should I avoid for performance hits specificially with managing the collections.would this pattern keep my source code bug free or easy to find the bugs and extensible for the future? or is there even a better pattern - please no ext library aside from the native mongodb driver for node.js solutions, such as mongoose.

Java interface function with extra parameter

I am beginner in Java, and OOP, and i am actually working with interfaces.

Here is my problem explained with code, excuse me if it's stupid question :)

I have one interface, for example animal,that can shout.

public interface Animal{
    public void shout();
}

My class dog implement the interface, and can shout at anybody.

public class Dog implements Animal{
    public void shout(){
        System.out.println("Woof woof");
    }
}

Ok, now i want a specific dog, Class SmarterDog, that can shout to someone specific.

So my function would be void shout(String somebody), so we have just one extra parameter, but still approximatively the same code. It's still an Animal, so it should implement Animal.

How can i organize my code to simulate this function? The example i show is easy, but for more complex functions what should i do? Create an extra function in the class that implement my interface?

Thanks

Entity framework update with business model

I'm trying to implement a business layer into my application. The reason for this is that my (legacy) database is very complex for the use cases we have. So what I'm trying to do is the following

  1. Retrieve datamodel from the DbContext
  2. Transform the datamodel to a business model
  3. Pass it on to my controller to be used.

This works perfectly for retrieving objects, but updating them keeps giving me problems. Let me first give you (some of) my code (somewhat simplified): using System;

/* The datamodel*/
public class DataModel
{
    [Key]
    public int Id { get; set; }
    public double InterestRate { get; set; }
}

/*The business model */
public class BusinessModel
{
    public int Id { get; set; }
    public double InterestRate { get; set; }
    public bool IsHighInterest()
    {
        return InterestRate > 10;
    }
}

public class MyDbContext : DbContext
{
    public MyDbContext() : base("connectionstring")
    {
    }
    public DbSet<DataModel> DataModels { get; set; }
}

/* In reality I've got a repository here with a unit-of-work object instead of accessing the DbContext directly. */
public class BusinessLayer
{
    public BusinessModel Get(int id)
    {
        using (var context = new MyDbContext())
        {
            var dataModel = context.DataModels.FirstOrDefault(x => x.Id == id);
            BusinessModel = Transform(dataModel); //Do a transformation here

        }
    }

    public void Update(BusinessModel model)
    {
        using (var context = new MyDbContext())
        {
            var dataModel = TransformBack(dataModel);
            context.Entry<dataModel>.State = System.Data.Entity.EntityState.Modified;
            context.SaveChanges();
        }
    }
}

Obviously this isn't going to work, because entity framework cannot track the changes of the datamodel anymore. I'm looking for a design pattern where I can do these sort of things. Hope anyone of you can help me with this. In reality the datamodel is way more complex and the BusinessModel simplyfies it a lot, so just using the DataModel isn't really an option either.

mercredi 25 mai 2016

Best design pattern for switching between hardware interfaces

I am seeking advice about whether or not my current approach makes sense. If not, I'd like a recommendation about some type of design pattern than can be used to replace my current intuition.

My premise is that I have a camera that requries a frame grabber card with either a CameraLink or CoaXPress cable interface to connect to a PC. All communication and data transfer between the camera and computer must be controlled using the frame grabber card, so the coupling between these two physical hardware objects is very tight.

My problem is that I want to create a "Camera" object (for a GUI) which has-a "FrameGrabber" card object that it uses to acquire data and send/receive commands and data. However, I have many different frame grabber cards of many different types. Lets call them CoaxGrabberA, CoaxGrabberB, LinkGrabberA, and LinkGrabberB. The CoaxGrabbers require a different set of parameters for initialization, setters, and getters than the LinkGrabbers.

As a result, I think I need to use two levels of inheritance, but from everything I've read, inheritance should be used very rarely, and composition should be favored. As such, I am extremely doubting my design decisions, and seek some type of better design. Here's an example of some half-baked code. It's a bit lengthy, but the important part is the concept that CoaxGrabberA, CoaxGrabberB, LinkGrabberA, and LinkGrabberB are grandchildren of FrameGrabber, which must be accessible to Camera. Everything else is to fill in the meat for details you may need.

My goal is to, at runtime, select whichever framegrabber (of any make/model/interface) that I want to use for my Camera object. Furthermore, I want to easily access all of the member functions that are unique to that grandchild framegrabber type to modify the behavior of the hardware at runtime.

My question is "is there a particular design pattern to match my problem that I don't know about, which would make my life easier than using my naive, intuitive approach"

//-----------------------------------------
// Parent Class
//=========================================
Class FrameGrabber {
 public:
    virtual void sendCommandString(std::string cmd) = 0;
    virtual void startAcquisition() = 0;
    virtual void stopAcquisition() = 0;
};


//-----------------------------------------
// Children Classes
//=========================================
Class CoaxGrabber : FrameGrabber {
 public:
    //functions unique to coax grabbers
    virtual void setCommAddress(int commAddress) = 0;   
    virtual void setStatusPort(int statusPort) = 0;    

    //functions universal to all grabbers
    virtual void sendCommandString(std::string cmd) = 0; 
    virtual void startAcquisition() = 0;                 
    virtual void stopAcquisition() = 0;  

 protected:
    int _commAddress;
    int _statusPort;        

};


Class LinkGrabber : FrameGrabber {
public:
    //functions unique to link grabbers
    virtual void setBaudRate(int baudRate) = 0;
    virtual void setNumChannels(int numChannels) = 0;

    //functions universal to all grabbers
    virtual void sendCommandString(std::string cmd) = 0;    
    virtual void startAcquisition() = 0;
    virtual void stopAcquisition() = 0;

protected:
    int _baudRate;
    int _numChannels;

};


//-----------------------------------------
// Grandchildren Classes
//=========================================
Class CoaxGrabberA : public CoaxGrabber {
    //identical public members as CoaxGrabber
    //different implementation using
    //different low-level API, ex: BitFlow
}


Class CoaxGrabberB : public CoaxGrabber {
    //identical public members as CoaxGrabber
    //different implementation using
    //different low-level API, ex: Kaya
}


Class LinkGrabberA : public LinkGrabber {
    //identical public members as LinkGrabber
    //different implementation using
    //different low-level API, ex: NationalInstruments
}


Class LinkGrabberB : public LinkGrabber {
    //identical public members as LinkGrabber
    //different implementation using
    //different low-level API, ex: Imperx
}


//-----------------------------------------------------
// Finally, my Camera object, nothing too interesting here
//=====================================================
Class Camera {
public:
    CameraSystem() {
        _frameGrabber = NULL;
    }

    ~CameraSystem() { 
        delete _frameGrabber;
    }

    void setGrabber(FrameGrabber* newGrabber)
    {
        delete _frameGrabber;
        _frameGrabber = newGrabber;
    }

    void startAcquisition() {
        _frameGrabber.startAcquisiton();
    }

    void stopAcquisition() {
        _frameGrabber.stopAcquisition();
    }

    int setSensitivity(int sens) {
        _frameGrabber.sendCommandString("sens=" + std::to_string(sens)); 
    }

private:
    FrameGrabber* _frameGrabber;

};


//-----------------------------------------
// This is why I don't like my Camera object
// the actual end-user interface smells
//=========================================
Class CameraGui : QMainWindow
{
public:
    void setGrabberType(int type);
    void setCoaxGrabberCommAddress(int address);
    void setLinkGrabberBaudRate(int rate);

    CameraSystem _myCamera;
    CoaxGrabber* _myCoaxGrabber;
    LinkGrabber* _myLinkGrabber;
};


//---------------------------------------------------------------
//This function smells to me, but I cannot think of any other way
//of course, int type will be enum in actual program.
//===============================================================
void CameraGui::setGrabberType(int type) {
    switch (type) {
        case 0: 
            delete _myCoaxGrabber;
            _myCoaxGrabber = new CoaxGrabberA();
            _myCamera.setGrabber(&_myCoaxGrabber); 
            break;
        case 1: 
            delete _myCoaxGrabber;
            _myCoaxGrabber = new CoaxGrabberB();
            myCamera.setGrabber(&_myCoaxGrabber)); 
            break;
        case 2: 
            delete _myLinkGrabber;
            _myLinkGrabber = new LinkGrabberA();
            _myCamera.setGrabber(&_myLinkGrabber); 
            break;
        case 3: 
            delete _myLinkGrabber;
            _myLinkGrabber = new LinkGrabberB();
            _myCamera.setGrabber(&_myLinkGrabber); 
            break;
    }
}

//---------------------------------------------------------------
// this method of setting parameters also smells to me,
// since this data is linked to the Camera object, which
// will have no way of knowing whether the state of its
// framegrabber changed... furthermore, if I change framegrabbers,
// none of the parameter settings (state) will be remembered.
// the user will need to set them all over again.
// the only way I know to circumvent this is to allocate memory for
// every type of framegrabber, and broadcast all state changes to
// all applicable parent grabbers, which will reside in permanent
// memory until the application closes.
//===============================================================
void CameraGui::setCoaxGrabberCommAddress(int address) {
    if(myCoaxGrabber != NULL) {
        myCoaxGrabber->setCommAddress(address);
    }
}

//likewise smell
void CameraGui::setLinkGrabberBaudRate(int rate) {
    if(myLinkGrabber != NULL) {
        myLinkGrabber->setBaudRate(rate);
    }
}

Any and all advice will be greatly appreciated. Long story short, I know little about OO design patterns, but this feels like a solved problem and I feel like I'm reinventing the wheel. Is there a better, more established way to implement what I am trying to do?

Android: Effective way to manage UI and function state in an app using AsyncTask?

I'm looking for a tidy solution to something that must be common in Android applications: A clear way to manage state when the result of actions is uncertain and running asynchronously.

I realize that using a progress view will keep the app from having to deal with the user during the AsyncTask. The problem is that there's a bunch to contend with, and it seems to lose maintainability as the applications get more detailed.

For example, say we have an activity that has three states, from a UI point of view. Say the view for the activity has a bunch of things to make visible/invisible, enable/disable, set text for, etc. These things depend upon what has happened in the past sessions, this session, and through configuration changes. One might take the model of a log-in, where there are user credentials that may be untried, tried and failed, tried and worked. And say there's a database with data that becomes stale if the user does something, or if there's a failure in login, for instance. The point is, if there's a lot going on, what's an effective pattern to employ?

I realize that SharedPreferences and SQLiteDatabase are available, and I'm using both of those. It just seems haphazard. Deep in the bowels of the AsyncTask for instance, I might realize that things are not going smoothly, so rather than normal UI state, I'd like make some UI changes. Which I do, but the way I'm keeping track of all of those changes so I can handle the activity restarting due to screen orientation change, seems untidy: I'm constantly putting primitives into preferences all over the place. I can manage it now, but if this app doubled in size, it would not be unmanageable.

It seems like if you have a simple app, there's no reason to expand beyond just tweaking the views as needed. The pattern I'm looking for may or may not have long-running tasks as a central part of it, or multiple resulting states from a single starting state when a specific action is taken, but should allow for orderly management of state when there is 'a lot going on'.

Refactoring a large class into smaller classes

Hey so I'm trying to get into better coding habits after a large project of mine became somewhat unmanageable. I've started taking particular care in trying to design my classes after the SOLID principles as well as applying design patterns where needed. I've come to a bit of a fork in the road when trying to refactor a large class of mine however.

Basically the class controls behavior for a camera in a 3D game. It has a gameobject which allows me to modify it's position and rotation among other things. My problem is I have methods for several different behavioral aspects as well as fields for each behavior.For example: Adjust tilt to ground level, adjust height to ground level, smooth position, smooth rotation, smooth tilt, follow object, lock to position etc. Point being, there are a bunch of "behaviors". The amount of fields alone has become a big wall at the start of my code which I don't like very much.

I have moved some of these methods and fields to separate classes and have included references to their objects in my camera class. I have also created an interface for behaviors. So now my Camera calls UpdateBehavior on the various different objects and passes an instance of itself in as a parameter. The behavior class then operates on the camera and updates its position, tilt or rotation.

My question is, is this too tightly coupled? The camera basically calls another object to operate on itself. Is that ok? Also where do I draw the line at what is relevant in each class. I could potentially create quite a few classes based on this one class alone if I break everything up. Is this the conventional way of doing things?

Or am I being too over the top by doing this. The class itself would be about 1.5k lines long. The only responsibility it has is to move the camera in a specific way. It just does this through a bunch of different methods and I'm not sure if I should be considering tilting a separate responsibility for example.

By doing this it has helped me develop the various specific areas. Where before I'd be looking around the code trying to figure out what is associated with what exactly. Where now it is quite clear.

Any input would be much appreciated.

Javascript Facade method grouping

I'm working on a Facade class in Javascript. To make the class more manageable I would like to group related method in the facade. Consider my facade:

function Client(){this.a = 1;}

Client.prototype.methodA = function(){}
Client.prototype.methodB = function(){}

function SubClient = function(){}
Subclient.prototype.methodA = function(){}

I would like to be able to call method A in the sub client class like this using the context for the main Client:

var a = new Client() ;
a.SubClient.methodA() ;

I tried defining the subclient as an object but it doesn't use the same context. i.e. this.a is undefined

//Doesn't work - this.a is undefined
Client.prototype.SubClient = {methodA: function(){}}

Any ideas how this can be done or any suggestions. My facade class will be considerably big I would like to break it down.