mercredi 30 septembre 2015

In Observer Design pattern, are Subject and Observable the same thing?

In Observer design pattern, the observer observes the subject or the observable. It gets notified by their updates. I am confused whether those two things are the same things? Or there is a subtle difference between the two?

Google Guava cache pass extra parameters to load/loadAll

I have a

LoadingCache<Long, String> idNameMap

that needs to be populated. The ids are unique in the context of my application. However, due to the way data is stored in the table, I need to pass in extra parameters to database query to complete a fast database lookup. Which means that I should be able to pass these parameters to my loadAll method which currently looks like:

@Override
public Map<Long, String> loadAll(Iterable idsIterable) throws Exception {
    //pass in ids and extra parameters to improve database query speed
}

Those extra parameters do not need to be part of my cache. My question is that what pattern should I use to solve this problem?

Lazy evaluation with pair factory in C++

I'm trying to implement lazy in C++ like in this Python example using decorators:

@lazy
@factory(Category)
def func(self):
    return self.__raw_data  # for building object include object type and **params

I found Getting Lazy with C++ and Lazy evaluation in C++ post but they haven't helped me. I don't understand how implement the lazy.

What is difference between factory design pattern and DAO design pattern

Comparing these two patterns I see that they are quite similar: both of them have interface (Product/Dao), factory (ProductFactory/DaoFactory) and concrete implementation (ConcreteProduct,ConcreteDao). Factory creates some concrete implementation object and this object is used by client via interface. So are they similar or I don't understand something? Or is Dao pattern a specific implementation of factory pattern?

Pulling data from a class instance that may not yet exist in Java

In my Data Structures with Java University Course, we've been tasked with making a simple Social Network.

One of the profile methods defined by a given interface is recommend, which is supposed to go into the array of profile objects holding the list of people. This instance follows, pick one, go into that instance's array follow list and return a profile from there as a suggestion of someone to follow.

I don't really understand anything about how to go about this, because I'm supposed to anticipate an instance of a class which doesn't exist yet.

I don't expect whoever responds to do my homework for me, but any guidance about how to start this would be greatly appreciated.

How to design logging in MSTest test suite such that each test case writes to it's own log file

What I want to do

I want to include logging in my tests preferably using System.Diagnostics such that each test case writes to its own log file (let's say the format is {test-case-name}.log). The catch is that the logging statements will not be in the test methods themselves, but in a separate class hierarchy, which the different test methods will share. An example:

Test classes:

  1. BaseTestClass (abstract)
  2. DerivedTestClass_Firefox: BaseTestClass (has test methods like TestA_Firefox,TestB_Firefox)
  3. DerivedTestClass_Chrome: BaseTestClass (has test methods like TestA_Chrome, TestB_Chrome)

OperationClass (includes basic actions done by tests and has the logging statements): Let's say it has methods: OperationA, OperationB, etc. Now different test methods can share these operations. So if OperationA has Logger.LogInfo("Doing operation A"), then this message should go to the correct log file according to what test called it. The tests need to be able to run in parallel. I will be using MSTest if it matters.

My current solution

I made a static Logger class like below:

    public static class Logger
    {
        //stores tracesource objects against tracesource names (same as test method name)
        //entries are added in this by the [TestInitialize] method in BaseTest, as it has access to the calling test method name (from TestContext)
        private static Dictionary<string, TraceSource> TraceSourceMap = new Dictionary<string, TraceSource>();
        //automatically determines which log file the message should go to
        //from the stack trace and test method naming conventions
        private static string GetCallingTestName()
        {
            StackTrace stackTrace = new StackTrace(); 
            StackFrame[] stackFrames = stackTrace.GetFrames();

            foreach (StackFrame stackFrame in stackFrames)
            {
                if (stackFrame.GetMethod().Name.ToLower().EndsWith("_firefox") ||
                    stackFrame.GetMethod().Name.ToLower().EndsWith("_chrome") ||
                    stackFrame.GetMethod().Name.ToLower().EndsWith("_ie"))
                {
                    return stackFrame.GetMethod().Name;
                }
            }
            return null;

        }
        private static TraceSource GetTraceSourceObject()
        {
            string traceSourceName = GetCallingTestName();
            TraceSource ts = TraceSourceMap[traceSourceName];
            return ts;
        }
        public static void LogInfo(string logMessage)
        {                      
            TraceSource ts = GetTraceSourceObject();
            ts.TraceInformation(String.Format("[{0}] {1}\n", DateTime.Now.TimeOfDay, logMessage));

        }
   }

The [TestInitialize] method in BaseTestClass sets up TraceSource with the name as the calling test method name, adds the listener (a log file with same name as test name) and then adds this object in Logger class's dictionary.

The issue is that this design completely depends on test naming. The tests must have _firefox, _chrome, etc. in the end, and none of the other methods can end like this, because then it'll be impossible to tell through stack trace what is a test method or what is an operation (unless I impose further pattern in test method naming). On the other hand, this is very less code and will work perfectly even if I run tests in parallel.

Problem/ Question

I want to know in what other way I can achieve the same result and if this design is actually that bad. One idea might be to create a logger object in [TestInitialize] of BaseTestClass (recall that before this I don't know what the logging file will be as it depends on test name, so can't do this at constructor time) and then somehow pass this logger to OperationClass. But then there is only one instance of logger object for the whole test class and this would be a problem if I want to run tests in parallel right? (As each test method logs in a different place, so each test method needs its own "version" of logger object. Even for parallely running tests I guess the test class is instantiated only once?)

Design Pattern for specific business partners, vendors, accounts etc

So I am thinking about a proper way to tackle this problem as far as a naming classes and a design pattern perspective is concerned. Think of a solution which is a engine - it gets input, does processing and produces an output.

Here is my interface to start with.

 public interface IFileProcessing
    {
    string InputFilePath { get; set;} 
    string OutputFilePath { get; set;}
    string ProcessedFilePath { get; set; }
    string ExtractionFieldsFromWebService{ get; set; }
    void ProcessFile(string FileName, string FilePath);
    }

BusinessModel: This is my business model, I have a ice cream shop and I designed classes to do my supplier based financials based on industry types(Lines of business). I sell ice creams of many types, which I buy from different suppliers, and at the end of the month I try to reconcile my account by line of business using classes I created for cost calculation purposes.Method Process file contains the algorithm specific to LOB calculation.

All this is happening based on 5 different models(line of businesses), aka classes I defined. Lets say for example, My classes handle my calculation of my costs

public class IceCreamLOB : IFileProcessing
public class FrozenCustardLOB : IFileProcessing
public class GelatoLOB: IFileProcessing
public class FrozenCustard: IFileProcessing

So far everything is generic to the line of businesses mentioned above. The complexity comes when I am being asked to design classes specifically for suppliers, aka example, BreyersLOB, or KlondikeLOB, which is say my biggest account and these accounts need special processing specifics. I don't know if I should be naming my classes specific to supply vendors. How can I maintain logical processing specific to a supplier in a class without naming the class a specific vendor. Is there a good pattern when you come across a situation like this.

How would I go about scaling this without using inheritance, or do I need to go there? So would you ever name your classes specific to the vendor/business partner you work with? Like Klondike and Breyers

How to design a large JavaScript Application [on hold]

I am searching for solutions how to design a "large" javascript application.

I tried to draw the cross relations, which I will need: http://ift.tt/1WxZg1w

I have a fix template of the App and dynamic content, like site1. The App is connected via Websocket to a server and I have a lot of cross realtions of vars as you can see in the drawing.

My question is now: How to design and split up the party in a nice way. How can I react on events in the application, so for example change the JS value of vars inside the "site1 widget" and the other way.. how to send for example x/y via the websocket to the server..

Thank you very much :)

Python voice comparing, words recognizer

I am looking for some open source tool to solve my problem.

I need to compare two or more sound files spoken by the same person. I am not talking about voice recognition which I am using in another part of project (wit.ai and cmusphinx). What I need is to record a child (which did not speak correctly due to some mental disabilities) speaking fe. Single word, and then ask him/her to speak the same word again. And if he/her would not pronounced it correctly (with some precision of course) an error would be raised.

I would be gratefull for any help :)

Need Architectural Style/Pattern For Providing Pre/Post Hooks To Common Tasks In ERP

I am preparing an architecture for a Financial ERP, especially GL, Account Receivables etc. on ASP.Net MVC 5. I need to inject some extensibility points so that external systems can be integrated easily in future. These extensibility points can be stored procedures, scripts, performance counters, external logging and many more. You can consider this scenario as writing extension points or custom routines to Dynamics AX or Oracle EBS.

I know about ASP.Net filters but I don't foresee it a flexible way to provide extension points to external users. It requires modifications in code and break the Open For Extension/Close For Modification principal.

I would appreciate if someone points me to some good and relevant articles or give some suggestions.

Thanks in advance.

mardi 29 septembre 2015

Include Class in Parent Based on Child Class

I have a child controller class that extends a base controller class. In the child I have defined a static namespace string that points to the model class I want to use when calling functions in the base class. Right now, I have to use call_user_func to call the function on the correct model class. The code looks something like this:

Child Class

class RolesController extends Controller
{
    const RESOURCE_NAME = 'roles';
    const MODEL = 'Role';
}

Parent Class

class Controller extends BaseController
{

    private $model;

    public function __construct()
    {
        $this->model = 'App\\Models\\' . static::MODEL;
    }

    public function getAll(Request $request)
    {
        $objects = call_user_func([$this->model, 'getAll'], [
            Model::GET_OPTION_FORMAT => true
        ]);

        return Response::success([
            static::RESOURCE_NAME => $objects
        ]);
    }
}

I can't help but think that this design pattern is incorrect. Is there a better way to accomplish what I am trying to do without having to rely on call_user_func? I can not find a similar question as I am struggling to find the words to describe this problem. If anyone could point me in the right direction it would be greatly appreciated.

C++ Header and Source file design implementation

I have a few queries regarding the design principle of laying out a C++ header and source files: I have recently taken over a project in which the previous programmer used to have this, which is particularly annoying because I read somewhere that we shouldn't include a .cpp file in a .hpp file (The preprocessor will just copies and pastes the .cpp file into a .hpp)

Q1. Including a .cpp file in a .hpp file is bad? why?


Due to the problem above, I am facing many "multiple declaration" errors when I load my program in eclipse, even though i added the header guards in all the .hpp files.

Q2. Should i be including the header guards in the .cpp files as well? I tried the later too but to no avail. Any suggestions on this?

Q3. If 2 or more of my .cpp files need the same header files to be used what is the best way to include all those header files? Should i create a new header file say h1.hpp, include all the header files I need in those 2 or more .cpp files and later include in this header file in those .cpp files(s)?

Is it an efficient approach ?

Use the Builder Pattern to create mutable objects?

According to the book Design Patterns du Gang of Four,

The Builder Pattern separates the construction of a complex object from its representation so that the same construction process can create different representations.

In general the Builder pattern solves the issue with large number of optional parameters and inconsistent state by providing a way to build the object step-by-step and provide a method that will actually return the final Object.

With the builder pattern we go to have a build method to generate an object witch is immutable.

My Question:

Can I use the builder pattern keeping setters methods in the Class of the generate object, allowing the possibility to mutate the built object ?

If I go to produce mutable objects, I shouldn't use the builder pattern ?

The use of ApplicationException

I'd like to know if the use of ApplicationException is recommended in my case. For example, in a service class I want to validate some data before save it in the database. The error messages are returned as a ApplicationException, for example:

public void update(string name, string email)
{
    if (string.IsNullOrEmpty(name))
        throw new ApplicationException("Type your name");

    if (string.IsNullOrEmpty(email))
        throw new ApplicationException("Type your e-mail");

    if (isValidEmail(email))
        throw new ApplicationException("Invalid e-mail");

    //Save in the database
}

Then I would catch those exception later in a centralized routine. There are a better design than that?

PS: I know that there is better solutions for validating a form, this is just a example and concerns only in the use of ApplicationException to return error messages.

Write a program that prints a trapezoid in Programming in C

Hey guys I am struggling with my program. It should print a trapezoid like this:

ccc

cccc

ccccc

cccccc

This is what i came up with:

int main(){
 int n,m,row,column;
 char c;
 printf("Enter a character: ");
 scanf("%c",&c);

 printf("Enter number of rows\n");
 scanf("%d",&n);

 printf("Enter number of columns\n");
 scanf("%d",&m);

 for ( row = 1 ; row <= n ; row++ )
 {
     for( column = 1 ; column <= m ; column++ ){
             printf("%c",c);
     }
     printf("\n");


 }
 return 0;

}

This above prints this: c = c

n= 4

m=3

ccc

ccc

ccc

ccc

Please help, I have no clue anymore i am frustrated Thank you very much

JavaScript function that return with different types (Array vs NodeList)

I wrote a JavaScript function that will return a "list" of elements that has Id that start with some value:

function getElementsWithIdPrefix(prefix){
    if (document.querySelectorAll){
        return document.querySelectorAll('*[id^="' + prefix + '"]');
    } else {
        // none modern browsers support
        var elements = document.getElementsByTagName('*');
        var relevantElements = [];
        for (var i = 0; i < elements.length; i++){
            if (element.id && element.id.indexOf(prefix) !== -1){
                relevantElements.push(element);
            }
        }
        return relevantElements;
    }
}

As you can see my function will return different types depends on browser support for document.querySelectorAll and I have two question regarding this:

  1. Is this bad? I mean - In JavaScript typing system does it consider as a code smell or bad practice?
  2. How can I create Node objects for each Element by my self and construct a new NodeList containing these elements to return?

REST API merging data from other REST API

I'm developing a REST API using asp.net MVC. I'm using an application database that contains some movie data. In the table movie there is column with a key that is an id that can be used when calling another REST API to get additional information about the movie. This extra information shouldn't be saved in the application database.

I want to implement a GET movie/id (not same id as the external REST API) for my API. When calling this I want to get the movie information from my database but also merge the movie information from the other REST API.

I need advice on design, which is the proper way to do this? My plan was to use repository pattern to access the data from my database. But where should I request the external information and merge it to my model that is sent to the client? Should this be in the controller, the model, the repository that fetches data from the database? Also should i just use System.Net.WebClient to get the external information?

Thanks

Java extending - best refactoring pattern

I know that I broke open-close principe, but previous architecture does not require such functionality. That's a story:

I have one abstract activity that extends CordovaActivity(from XWalk library), and have two concrete activities that extend it - both with its own scope of logic, a lot of that logic has calls to protected methods of activity class. And now we have problems with crosswalk on some custom emulators, I haven't even access to them. The most problem is CordovaActvities from XWalk and from cordova have almost the same api, but without any general interface, so code for both abstract activities will be almost the same, but parent class should be different. So, is there some elegant way to do this without blind copy-paste, but without core refactoring of my classes?

I was thinking about some kind of dependency injection for my business logic resolver using empty fragments - they allow me to use most of activity-related methods. Or move most generic UI features also to fragments.

But I believe that there should be some easier way just to change parent classes and few methods signatures?

ConcreteLogicActivity1 extends BaseActivity
ConcreteLogicActivity2 extends BaseActivity

BaseActivity extends XWalkActivity

Now I need to make

XWalkBaseActivity extends XWalkActivity
CordovaBaseActivity extends CordovaActivity

then I'll have Logic1 derived from XWalk and Cordova, and Logic2 too. But it will be primitive copy-paste with a lot of the same code.

Scala: What pattern should I use to create a common abstraction for Int, Double and String?

I need to refactor my whole system and I would like suggestions on how to deal with a problem with types.

I have this situation: I'm using PMML (basically an XML with a data schema specification) and HBase (a columnar storage that keeps no data type schema). I need to match the two while manipulating the values in my system. So I need to have an abstraction to handle all the possible data types that could be part of my system. Right now I have Int, Double and String.

For every type I need to be able to define a parser (for HBase), a writer and a set of operations defined as high order functions ((T,T)=>T).

Right now I tried to do that with a trait MyValue[T] that was extended by MyValueInt extends MyValue[Int] or MyValueDouble extends MyValue[Double]. I could define a list of operations like List[(MyValue,MyValue)=>MyValue] but I had to match it everytime with every case and created a lot of other problems with the type system.

What I need is a good abstraction to model the fact that these values can be only Int, Double and Strings, to create lists of these values and to be able to treat these values with a generic logic until I need to extract the real value and apply it to an operation.

Building a Composite from list - C#

I have an abstract base class,

Public absctact class BaseItem
{
  public BaseItem ParentItem { get; set; }

  // Some other Methods
}

I have some classes implementing this abstract class, the problem is I have to create a Composite class from a input list. Say I have a list of int's coming in a particular order, a list of length 5. I have to iterate this list and create a composite object of BaseItem which will go 5 level deep. In the first iteration create a concrete type of BaseItem, this will be the first item. In the next iteration create a concrete class and set this as the parentItem of the first item and so on and so forth. The resulting object of BaseItem type will be 5 level deep with the last parents parentItem as null.

Can someone help me with implementing this logic.

Best way to define constant in asp.net

Which of below 2 method is better to declare constant/config driven variables in asp.net from coding standing perspective, from architecture perspective.

Type1-

class Constants
{
    public static string ConnectionString
    {
        get
        {
            //Get the connection string value from web.config
            if (ConfigurationManager.AppSettings["ConnectionString"] != null)
            {
                return ConfigurationManager.AppSettings["ConnectionString"];
            }
            else
            {
                return string.Empty;
            }
        }
    }
}

Type 2-

class Constants
{
    public static string ConnectionString = ConfigurationManager.AppSettings["ConnectionString"] != null ?
                                                ConfigurationManager.AppSettings["ConnectionString"] : string.Empty;
}

Is there any better way to ?

How do I test this class?

So I have this class I'm testing and it is a helper that pulls stuff out of an XML class. The whole thing is kind of a Russian Doll where you have to dig through several levels to get the right thing you need. Problem is that this class calls many of it's own methods which makes it pretty hard to test without a bunch of redundancy. This is to say that I don't want to retest any of those "low hanging fruit" methods that retrieve objects from shallow locations if I can avoid it. I smell an opportunity for a re-factor here but I'm unsure what it should be. Note that there are often 6 and 7 levels to our "Russian Doll". My intuition says that I should maybe refactor the class under test to a hierarchy of classes, roughly one for each level in our "Russian Doll". Then maybe I could test one at a time without redundancy.

Questions: What are the patterns I should be looking at for this? Is there an approach for doing this which is Composition rather than Inheritance based?

How to implement the template view pattern with a table?

at the moment I'm trying to understand the template view pattern using PHP.

I understood it generally. I'm able to display a single information. Two questions:

  • How to implement it when I want to display a table from a database?
  • How to implement the content that should be displayed on all pages?

    Unfortunately everything I found is about template engines that I don't want to use at the moment.

    Thank you!

Lazy and cheap initialization pattern

When one decides to use lazy initialization, he usually has to pay for it.

class Loafer
{
    private VeryExpensiveField field;
    private VeryExpensiveField LazyInitField()
    {
        field = new VeryExpensiveField();
        // I wanna then remove null check from accessor, but how?
        return field;
    }
    property Field { get { return field ?? LazyInitField(); } }
}

Basically, he has to check every time if his backing field has null/nil value. What if he could escape from this practice? When you successfully initialize the field, you can rid of this check, right?

Unfortunately, majority of production languages can not allow you to modify their functions in runtime, especially add or remove single instructions from the function body though it would be helpful if used carefully. However, in C#, you can use events mechanism to imitate such behavior with consequent lack of performance, because null-checks just move onto lower level, but do not disappear completely. Some languages, e.g. LISP and Prolog, allow you to modify their code easily, but they are hardly can be treated as production languages.

In native languages like Delphi and C/C++ it would be better to write two functions, safe and rapid version, and switch to rapid after initialization. You can even allow compiler or IDE to do this for you automatically.

And what common approaches are exist to develop such functionality?

lundi 28 septembre 2015

Java method that returns logical operators

Question first, then backstory, as to not make the question seem completly idiotic if it is infact not possible..

QUESTION: Is there any way to write a method that returns || or && or < or > depending on which implemented subclass is calling the method

I´m currently learning Java and taking a few courses at uni to that extent.

So in an assignment in a course concerning objective-based design patterns and discrete structures we are to write a program that simulates a logical proposition and examines it for the quality of tautologi. I.e if the expression is true for all possible inputs.

i have made a simple binarytree implementation and the program works, but the design part of the course calls for us to use such design patterns as "Composite" and "Template method" all very fashionable words, sure you´ve all heard of e´m.

i have a Template method pattern in my toString insothat the

abstract Class BinaryConnector extends Expression{
protected Expression a,b
toString(){return a + getConnective() + b;  }
abstract String getConnective();
}

wich in for example

Class Or extends BinaryConnective{
//omissions
public String getConnective(){return "||";}

i would like to do the same for the actual comparison aswell.

i suppose there are many ways of juryrigging such a solution, such as a switch-statement in my abstract class. But just elegant solutions please.. im hoping for something like" just parse the getConnective()" or similar:)

or scold me for making you read so much..

MVC layer level listener interface design (Should listener be generic or not)

I came across this design, So I am not quite sure which way to lean towards. Any help would be much appreciated

I have three levels
a) Dialog
b) Controller
c) View

The Dialog creates the Controller and the view object. The Dialog passes down the view to the controller on the constructors argument.

Some of this design is existing, so the code base is already messed up, but regardless, this is my question

Say if I have a Listener interface.

Interface DoSomthing{
int doSomthing();
}

The existing flow is like below Dialog implements the listener and adds it to the controller. The controller implements the listener,(again no implementation change from the dialog) and adds it to the view. The view notifies the controller and then the controller notifies the Dialog and the dialog performs the action as needed.

So the Dialog creates the controller and implements the above interface and adds it to the controller.

Should the controller implement the same interface again or should it be a different interface.

As of now the implementation detail are the same, but I think since we look this as a layer.

Should I have it like this
a) View Listener
b) Controller Listener

And make the Dialog implement the Controller listener and the Controller implement the view listener.

Like this

Interface DoSomthingContollerListener{
int doSomthingController();
}

Interface DoSomthingViewListener{
int doSomthingView();
}

Or just have a generic listener in both the view and controller and implement them differently.

The problem I had having them as a generic listener is,I think since we use an MVC(though the above does not follow MVC at all) type design the interface should be for each level.

Am I wrong?

Better way to build javascript modules?

Can I get a little advice on my js modules? I'm good with js, but not quite guru status :) Am I refactoring my modules right?

I've been using the js module pattern like this (rough example, I'm just worried about the structure):

sloppy way?

/* Module Code */
var MapModule = (function ($) {
    var $_address;
    var $_mapContainer;

    function loadApi() {
        // do something. maybe load an API?
    }

    function someInternalMethod() {
        // do other things
    }

    var pub = {};
    pub.setAddress = function (address) {
        $_address = address;
    };
    pub.getAddress = function () {
        return $_address;
    };
    pub.initialize = function () {
        loadApi();
    }
})(jQuery);

// usage
MapModule.initialize();

But that usage seems a little sloppy. I like constructors.

I refactored some modules like this:

Better way?

(function ($) {
    this.MapModule = function () {
        var $_address;
        var $_mapSelector;
        var $_mapContainer;
        function loadApi() {
            // do something. maybe load an API?
        }
        function someInternalMethod() {
            $_mapContainer = $($_mapSelector);
            // do stuff with the jQ object.
        }

        var pub = {};
        pub.setAddress = function (address) {
            $_address = address;
        };
        pub.getAddress = function () {
            return $_address;
        };
        pub.initialize = function (selector) {
            $_mapSelector = selector;
            loadApi();
        }
    }
})(jQuery);

var map = new MapModule();
map.initialize('#mapcontainer');

That usage seems a lot cleaner to me, and it works just fine, but am I going about it properly?

Taking it another step

Say this module does some stuff with a div that wraps Google Maps and jQuery functionality: Any tips on turning that into a jQ plugin so I can use it with a signature like var map = $('mapcontainer').mapModule();

Thanks!

Are there Out of Process Cache design patterns?

Are there design patterns and best practices for out of process caches with an always on website?

That seems like a common enough situation that folks should not be reinventing the wheel.

  • Cache Warmup
  • Maintaining Cache Consistency with persistent data store
  • Recovery from a empty cache
  • Versioning of cached items as new code is deployed

Move cells with pattern search and copy

I would like to achieve following in VBA

Input Workbook1 
Index   Value 
 1       a
 2       a
 3       b
 4       c
 5       a
 6       b
 7       a
 8       c

Output Workbook2

I would like to have output in following format so that I can generate graph with same X axis

Index   Value 1 Value 2     Value 3
1        a      
2        a      
3                b  
4                             c 
5        a      
6                b  
7        a      
8                             c

SingleTon Objective C foolproof

How to make sure the singleton class never creates more than instance even though if we call

[[Class alloc]init] 

Even if its called it should return the existing object not a new object.

Programming Pattern - Single Data Structure - Multiple Methods

I have a single data structure that holds a relatively small amount of objects (ca. 1500) and several methods that are acting on it. Is there a programming pattern to iterate the methods over the data instead of writing significantly more boilerplate code?

Load particular methods from module. Design patterns

I've recently started to use RequireJS, which enables me to organize my code in a nice way. So, define and require became my best friends. But now I see one problem, which I do not know how to solve in terms of RequireJS, or in terms of some particular Design Pattern. So, imagine, I have a really huge module containing zillions of methods. I define it like so:

define(function(BIG_MODULE){
    return {
        property_0: "value_0",
        property_1: "value_1",
        ....
        property_zillion: "value_zillion",
        method_0: function(){...},
        ...
        method_zillion: function(){...}
    }
});

Please, do not ask me, why I have such a huge module - it's just an abstraction. And, so, the question now is - if it is possible to import or require not the entire module, but some of its properties and methods? Lets say I somehow assigned my module to some local instance and if I investigate the internals of this instance, then I can see, that it contains only some particular properties and methods. Is it possible?

Software Class Design Review Automation

I am looking for software design review tool that can make suggestions based on principles of software design patterns i.e Re-usability, Use of Abstraction, Un-necessary looping & conditional logics.

I tried SonarQube but I feel I need much more than just static code analysis that looks at entire project as a whole and finds opportunities that a human developer vision can never spot.

dimanche 27 septembre 2015

Can I consume a node js server and asp.net web service simultinously?

I am new to Node.js, but I've been developing with .NET for a while, lately I've been reading about Node.js and its advantages and I think it's a great way to mantain code and also it encourages code reusability. However I have quite a dilemma here.

I know that I can now create a web application just with node js and javascript because now there are drivers to connect directly to different DB systems. However I don't know if that would be a good approach due to the fact that this is a new technology and I also want to take advantages of all the great .NET features but don't want to leave .NET aside.

So I created an image that is similar to what I want, please let me know if you see anything wrong with this, and if you have any recommendations you're most welcome to do so, thanks.

1- enter image description here

UML Diagram of a Factory Design Pattern

I have a system where I tried to applu Factory Design Pattern. You can see the UML diagram of my system from this image:

enter image description here

However, when I compare my system with this UML diagram, I got confused about whether my system conveys the Factory Design pattern. I think I don't have a Creator class mentioned in the given link.

Any ideas or comments on whether my system conveys to the Factory Design Pattern?

Different methods needs different attributes in one object

i have the following szenario:

I have a given webservice (this is only a example, the real one is more complex but same problem.) The serivce has three methods and all three methods have a person as parameter and need other things from it. (Cant change the entity or methods.)

Entity (Person) (Have only a default construtor):

private String name;
private int age;
private Address address;
private List<String> hobbies;
private List<Person> friends;

Method1 needs name and age
Method2 needs address name and age
Method3 needs all

I need to fill the object from my own objects. I need to write a "converter" what is the best practise for it?

My solutions:

  • Builder Pattern with builds for three methods.
  • Set all attributes and send unhandled overhead (bad solution in my eyes)

Thank you for help

How to create a pattern Lock app

I am new to android,In my app I just need to add a screen like pattern lock, what exactly i want to do is, no need to create/ set a pattern.Just design a screen with 9 dots, and when user draw some pattern and i need to get those pattern value.For design I used PatternView but how can I get the user drawer pattern? I already google on this, but I found there they setting the pattern lock, I don't want that.I just want is when I draw something on PatternView it just return the value like,suppose like if I draw a pattern like 2365 dots it will return an integer value like 2365.

Thanks in advance.

Sinatra API feature toggle

The gist

Is it possible to bake feature-toggle-like functionality into a Sinatra application?

A bit about feature toggles, just in-case ;)

Back story

I've set up a modular Sinatra project, and I tend to implement a GET/POST/PUT/DELETE endpoint for all my resources; it makes it easier to test the app and manipulate the data while in development.

Problem

When I go into production I don't want the unneeded endpoints to exist (e.g DELETE '/users').

Question

Can I annotate the methods with some kind of a :development flag, or maybe intercept the request in a before block? Would you do this using a helper? I'm not sure if I'm heading down the right path here, I'm probably over complicating it(?)

How would one go about this?

If you've done something like this it would be great if you can share your findings with the nation.

samedi 26 septembre 2015

Stategy pattern for game

Hi I should use strategy pattern to write code of this game. I create Country class and Character Interface. But i'm little confused i don't know where should i add abilities?

player first has to select a country for his country, which could be: Latveria, Ecotopia,Dinotopia. After selecting the country, player has to assign a class for his/her character by selecting one of the following: King,Queen,Troll and Knight. Depending on its class a character can have different abilities: a Knight can handle any
kind of weapon easily, which includesBow and Arrow, Swords, Knifes and Axes. King doesn't use any weapon, he can make strategy. Queen uses speacial Magic. Troll uses Knifes and Axes. All types of characters can fight using its specific abilities. Besides, all can ride horse and swim.

Maximizing / Minimizing bar on android

I'm trying to make my MainActivity divided on 3 parts. One listview on top, another listview on bottom and one little bar in the middle with 2 buttons, one will make the bar go directly to the top "hidding" the first list (and maximizing the other one) and vice versa if the user clicks on the second button. My question is: The propper approach to this is to make a custom view with and animate it manually or there is a easier way to do it?

Abstract Factory Pattern Error with C++ [duplicate]

This question is an exact duplicate of:

I have a program where user enters the operations of a plane. User can select as many operations (holding, straight, landing etc.) as s/he wants. User can calculate the necessary fuel intake with operation 5.

I have applied to the Abstract Factory Design Pattern to the system as follows:

FlightModeInterface.h

class FlightModeInterface{

protected:
float time, fuel_rate, start, end, pace, distance;
float total;

public:
    enum FLIGHT_MODES{
        HOLDING,
        RAISING,
        LANDING,
        STRAIGHT
    };

    FlightModeInterface();

    virtual ~FlightModeInterface(){ }

    virtual float calcFuel(float, float, float,
              float, float, float) = 0;

    static FlightModeInterface* createFactory(FLIGHT_MODES);
};

Holding.h

#include "FlightModeInterface.h"

class Holding: public FlightModeInterface{
public:

    Holding()
            :FlightModeInterface(){ };
    virtual ~Holding(){};

    virtual float calcFuel(float, float, float,
              float, float, float){
        total = (time * fuel_rate * 60);
        return total;
    }
};

Landing.h

#include "FlightModeInterface.h"

class Landing: public FlightModeInterface{
public:

    Landing()
            :FlightModeInterface(){ };

    virtual ~Landing(){};

    virtual float calcFuel (float, float, float,
              float, float, float){
        if(start > end && pace != 0 ){
            float landing_time = (start - end)/pace;
            total =  landing_time * fuel_rate;
            return total;
        }else{
            return 0;
        }
    }
};

Raising.h

#include "FlightModeInterface.h"

class Raising: public FlightModeInterface{
public:

    Raising()
            :FlightModeInterface(){ };

    virtual ~Raising(){};

    virtual float calcFuel (float, float, float,
              float, float, float){

        if(start < end && pace != 0 ){
            float rising_time = (end - start)/pace;
            total = rising_time * fuel_rate;
            return total;
        }else{
            return 0;
        }
    }
};

Straight.h

#include "FlightModeInterface.h"

class Straight: public FlightModeInterface{
public:

    Straight()
            :FlightModeInterface(){ };

    virtual ~Straight(){};

    virtual float calcFuel (float, float, float,
              float, float, float){
        if(distance != 0 || pace != 0 ){
            float straight_time = distance/pace;
            total = straight_time * fuel_rate;
            return total;
        }else{
            return 0;
        }
    }
};

FlightModeFactory.cpp

#include "FlightModeInterface.h"
#include "Holding.h"
#include "Landing.h"
#include "Raising.h"
#include "Straight.h"

class FlightModeFactory{
protected:
    float time, fuel_rate, start, end, pace, distance;
    float total;
public:
    static FlightModeInterface* createFactory(FlightModeInterface::FLIGHT_MODES mode){
        switch (mode) {
            case FlightModeInterface::HOLDING:
                return new Holding();
            case FlightModeInterface::LANDING:
                return new Landing();
            case FlightModeInterface::RAISING:
                return new Raising();
            case FlightModeInterface::STRAIGHT:
                return new Straight();
        }
        throw "invalid flight mode.";

    }
};

CalculateFuel.cpp

#include <iostream>
#include <stdio.h>
#include "FlightModeInterface.h"

using namespace std;


int main(){
    char op = 's';
    float time=0, fuel_rate=0, start=0, end=0, pace=0, distance=0;
    float total = 0;
    FlightModeInterface *factory;

    while(op != 'x') {

        float hold_result, raise_result, land_result, str_result;

        cout << "Please select an operation: " << endl;
        cout << "1 ---> Holding flight" << endl;
        cout << "2 ---> Raising" << endl;
        cout << "3 ---> Landing " << endl;
        cout << "4 ---> Straight " << endl;
        cout << "5 ---> Calculate total fuel consumption" << endl;
        cout << "x ---> Exit " << endl;

        cin >> op;

        switch(op){
        case '1':
            cout << "Holding time (minutes): ";
            cin >> time;
            cout << "Fuel rate (kg/sec): ";
            cin >> fuel_rate;

            factory = FlightModeInterface::createFactory(FlightModeInterface::HOLDING);

            hold_result = factory -> calcFuel(time, fuel_rate, 0, 0, 0, 0);

            total += hold_result;
            break;
        case '2':
            cout << "Enter starting altitude of raising (meters): ";
            cin >> start;
            cout << "Enter ending altitude of raising (meters):";
            cin >> end;
            cout << "Enter raising pace (meter/sec): ";
            cin >> pace;
            cout << "Fuel rate (kg/sec): ";
            cin >> fuel_rate;

            factory = FlightModeInterface::createFactory(FlightModeInterface::RAISING);

            raise_result = factory -> calcFuel(0, fuel_rate, start, end, pace, 0);

            total += raise_result;
            break;
        case '3':
            cout << "Enter starting altitude of landing (meters): ";
            cin >> start;
            cout << "Enter ending altitude of landing (meters):  ";
            cin >> end;
            cout << "Enter landing pace (meter/sec):  ";
            cin >> pace;
            cout << "Fuel rate (kg/sec):  ";
            cin >> fuel_rate;

            factory = FlightModeInterface::createFactory(FlightModeInterface::LANDING);

            land_result = factory -> calcFuel(0, fuel_rate, start, end, pace, 0);

            total += land_result;
            break;
        case '4':
            cout << "Enter distance for straight flight (meters): ";
            cin >> distance;
            cout << "Enter flight pace (meter/sec): ";
            cin >> pace;
            cout << "Fuel rate (kg/sec): ";
            cin >> fuel_rate;

            factory = FlightModeInterface::createFactory(FlightModeInterface::STRAIGHT);

            str_result = factory -> calcFuel(0, fuel_rate, 0, 0, pace, distance);

            total += str_result;
            break;
        case '5':
            cout <<"Total fuel requirement: "<< total << " kg"<< endl;
            total = 0;
            break;
        case 'x':
            return 0;
        default:
            continue;
        }
    }
    return 0;

}

When I run CalculateFuel.cpp, I encounter this error:

Undefined symbols for architecture x86_64:
  "FlightModeInterface::createFactory(FlightModeInterface::FLIGHT_MODES)", referenced from:
      _main in CalculateFuel.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Any ideas on how to solve this?

Grep three patterns in multiple files

I need to grep AND three patterns in multiple files , I found I way to grep AND two patterns in multiple file {grep -E 'pattern1.*pattern2' *} for example ,I have two files

  1. File1 contain

    1 ,2 ,3

    4 ,5

  2. File2 contain

    1,2,3

    4

I need to grep the file the contain 1 and 3 and 5

Applying Abstract Factory Design Pattern in C++

I have a program where user enters the operations of a plane. User can select as many operations (holding, straight, landing etc.) as s/he wants. User can calculate the necessary fuel intake with operation 5.

I have decided to apply Abstract Factory Design Pattern to my code. Here is the current version of the code without pattern is applied:

#include <iostream>
#include <stdio.h>
using namespace std;

class FlyingMode {

   protected:

    float time, fuel_rate, start, end, pace, distance;
    float total;

   public:
      FlyingMode(float _time=0, float _fuel_rate=0, float _start=0,
              float _end=0, float _pace=0, float _distance=0){

         time = _time;
         fuel_rate = _fuel_rate;
         start = _start;
         end = _end;
         pace = _pace;
         distance = _distance;
         total = 0;
     }

      virtual ~FlyingMode() {}

      virtual float calcFuel(){
         return 0;
      }
};

class Holding: public FlyingMode{

   public:
      Holding(float _time=0, float _fuel_rate=0, float _start=0,
              float _end=0, float _pace=0, float _distance=0)
              :FlyingMode(_time, _fuel_rate, _start, _end, _pace, _distance) { }

      float calcFuel(){
         total = (time * fuel_rate * 60);
         return total;
      }
};

class Raising: public FlyingMode{

   public:
      Raising(float _time=0, float _fuel_rate=0, float _start=0,
              float _end=0, float _pace=0, float _distance=0)
              :FlyingMode(_time, _fuel_rate, _start, _end, _pace, _distance) { }

      float calcFuel (){
          if(start < end && pace != 0 ){
              float rising_time = (end - start)/pace;
              total = rising_time * fuel_rate;
              return total;
          }else{
              return 0;
          }
      }
};

class Landing: public FlyingMode{

   public:
      Landing(float _time=0, float _fuel_rate=0, float _start=0,
              float _end=0, float _pace=0, float _distance=0)
              :FlyingMode(_time, _fuel_rate, _start, _end, _pace, _distance) { }

      float calcFuel (){

          if(start > end && pace != 0 ){
              float landing_time = (start - end)/pace;
              total =  landing_time * fuel_rate;
              return total;
          }else{
              return 0;
          }

      }
};

class Straight: public FlyingMode{

   public:
      Straight(float _time=0, float _fuel_rate=0, float _start=0,
              float _end=0, float _pace=0, float _distance=0)
              :FlyingMode(_time, _fuel_rate, _start, _end, _pace, _distance) { }

      float calcFuel (){

          if(distance != 0 || pace != 0 ){
              float straight_time = distance/pace;
              total = straight_time * fuel_rate;
              return total;
          }else{
              return 0;
          }
      }
};

// Main function for the program
int main( ){

    char op = 's';
    float time=0, fuel_rate=0, start=0, end=0, pace=0, distance=0;
    float total = 0;

    while(op != 'x') {
        FlyingMode *mode;
        Holding hold;
        Raising raise;
        Landing land;
        Straight straight;

        float hold_result, raise_result, land_result, str_result;

        cout << "Please select an operation: " << endl;
        cout << "1 ---> Holding flight" << endl;
        cout << "2 ---> Raising" << endl;
        cout << "3 ---> Landing " << endl;
        cout << "4 ---> Straight " << endl;
        cout << "5 ---> Calculate total fuel consumption" << endl;
        cout << "x ---> Exit " << endl;

        cin >> op;

        switch(op){
        case '1':
            cout << "Holding time (minutes): ";
            cin >> time;
            cout << "Fuel rate (kg/sec): ";
            cin >> fuel_rate;

            //call holding fuel
            hold = Holding(time, fuel_rate, 0, 0, 0, 0);
            mode = &hold;

            hold_result = mode -> calcFuel();
            total += hold_result;
            break;
        case '2':
            cout << "Enter starting altitude of raising (meters): ";
            cin >> start;
            cout << "Enter ending altitude of raising (meters):";
            cin >> end;
            cout << "Enter raising pace (meter/sec): ";
            cin >> pace;
            cout << "Fuel rate (kg/sec): ";
            cin >> fuel_rate;

            raise = Raising(0, fuel_rate, start, end, pace, 0);
            //call raising fuel
            mode = &raise;

            raise_result = mode -> calcFuel();
            total += raise_result;
            break;
        case '3':
            cout << "Enter starting altitude of landing (meters): ";
            cin >> start;
            cout << "Enter ending altitude of landing (meters):  ";
            cin >> end;
            cout << "Enter landing pace (meter/sec):  ";
            cin >> pace;
            cout << "Fuel rate (kg/sec):  ";
            cin >> fuel_rate;

            land = Landing(0, fuel_rate, start, end, pace, 0);
            //call landing fuel
            mode = &land;
            land_result = mode
                    -> calcFuel();
            total += land_result;
            break;
        case '4':
            cout << "Enter distance for straight flight (meters): ";
            cin >> distance;
            cout << "Enter flight pace (meter/sec): ";
            cin >> pace;
            cout << "Fuel rate (kg/sec): ";
            cin >> fuel_rate;

            straight = Straight(0, fuel_rate, 0, 0, pace, distance);
            //call straight fuel
            mode = &straight;

            str_result = mode -> calcFuel();
            total += str_result;
            break;
        case '5':
            cout <<"Total fuel requirement: "<< total << " kg"<< endl;
            total = 0;
            break;
        case 'x':
            return 0;
        default:
            continue;
        }
    }
    return 0;
}

I'm a bit confused for the application of the Abstract Factory Design. So far I have created these classes:

FlightModeInterface.h

class FlightModeInterface{

protected:
float time, fuel_rate, start, end, pace, distance;
float total;

public:
    enum FLIGHT_MODES{
        HOLDING,
        RAISING,
        LANDING,
        STRAIGHT
    };

    FlightModeInterface(float, float, float,
              float, float, float);

    virtual ~FlightModeInterface(){ }

    virtual float calcFuel() = 0;

    static FlightModeInterface* createFactory(FLIGHT_MODES);
};

Holding.h

class Holding: public FlightModeInterface{
public:

    Holding(float _time=0, float _fuel_rate=0, float _start=0,
            float _end=0, float _pace=0, float _distance=0)
            :FlightModeInterface(_time, _fuel_rate, _start, _end, _pace, _distance){ };

    virtual float calcFuel(){
        total = (time * fuel_rate * 60);
        return total;
    }
};

Landing.h

class Landing: public FlightModeInterface{

    public:

        Landing(float _time=0, float _fuel_rate=0, float _start=0,
                float _end=0, float _pace=0, float _distance=0)
                :FlightModeInterface(_time, _fuel_rate, _start, _end, _pace, _distance){ };

        virtual float calcFuel (){
            if(start > end && pace != 0 ){
                float landing_time = (start - end)/pace;
                total =  landing_time * fuel_rate;
                return total;
            }else{
                return 0;
            }
        }
    };

Raising.h

class Raising: public FlightModeInterface{
public:

    Raising(float _time=0, float _fuel_rate=0, float _start=0,
            float _end=0, float _pace=0, float _distance=0)
            :FlightModeInterface(_time, _fuel_rate, _start, _end, _pace, _distance){ };

    virtual float calcFuel (){

        if(start < end && pace != 0 ){
            float rising_time = (end - start)/pace;
            total = rising_time * fuel_rate;
            return total;
        }else{
            return 0;
        }
    }
};

Straight.h

class Straight: public FlightModeInterface{
public:

    Straight(float _time=0, float _fuel_rate=0, float _start=0,
            float _end=0, float _pace=0, float _distance=0)
            :FlightModeInterface(_time, _fuel_rate, _start, _end, _pace, _distance){ };

    virtual float calcFuel (){
        if(distance != 0 || pace != 0 ){
            float straight_time = distance/pace;
            total = straight_time * fuel_rate;
            return total;
        }else{
            return 0;
        }
    }
};

FlightModeFactory.cpp

class FlightModeFactory{
public:
    static FlightModeInterface* createFactory(FlightModeInterface::FLIGHT_MODES mode){

        if(mode == FlightModeInterface::FLIGHT_MODES::HOLDING){
            //HOW TO FILL???
        }
        else if(mode == FlightModeInterface::FLIGHT_MODES::LANDING){

        }
        else if(mode == FlightModeInterface::FLIGHT_MODES::RAISING){

        }else if(mode == FlightModeInterface::FLIGHT_MODES::STRAIGHT){

        }

    }
};

As you can see, I got confused with how to fill the if-else statements in FlightModeFactory.cpp. Any ideas on how to continue to Factory Design Pattern from this point? Is it correct to fill the calcFuel methods in Holding.h, Landing.h etc.?

Which design pattern to use for making Pizza

I want to make a small application which will return me a pizza based on the inputs given. I want to make a medium size pizza with different inputs 1. like white dough or brown dough 2. cheese toppings of different types, say white or brown cheese 3. different toppings of onions or tomato or mushrooms

So how do we decide which pattern to choose here, Builder or Decorator? I feel we can use builder pattern to make pizza first and then one we can use decorator pattern and decorate the pizza based on the different toppings we choose.Am I correct in this understanding? As I understand, decorator pattern is used to decorate any already existing object. To create this existing object, we would use builder pattern first.

Java singleton pattern - updates to instantiated variable

Looking to figure something out about the singleton pattern.

If I implement a singleton pattern like the below, what could I do so that other classes could update and see updates to fields someString and someInt?

From what I read about the Singleton pattern, immutability was not one of the prerequisites. So technically could I have setter methods for the fields and change them and have these changes visible to other classes? For example if I have another two classes implementing Runnable and printing Foo's fields every few seconds. I tried this and what happened was that each class sees its own updates only and none of the other classes'.

//generic Singleton implementation
public class Foo {

private static Foo instance;
private String someString;
private int someInt;

private Foo(){
    someString = "a";
    someNum = "1";
}

public static Foo getInstance(){
    if(instance == null){
        instance = new Foo();
    }
    return instance;
}

Java real time scenario interview for experienced

i need interview questions on java collections,multithreading, design patterrns on real time scenario.

Thanks

C++ singleton Pattern _ Implementation and memory managenet

my code below is not comiling for the singleton pattern

(error LNK2019: unresolved external symbol "private: __thiscall Singleton::Singleton(void)" (??0Singleton@@AAE@XZ) referenced in function "public: static class Singleton * __cdecl Singleton::returnOneInstance(void)" (?returnOneInstance@Singleton@@SAPAV1@XZ))

can anyone help? i also want to know how one must manage the memory? thanks

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;

class Singleton
{
private:
    Singleton();
    Singleton(const Singleton& sing);
    void operator=(const Singleton& sing);
    static Singleton* singleton;
    /*The 'instance' field holds the reference of the one and only instance.
      It is stored in a static variable because its scope has to be the class itself and not a particular instance.
    */
public:
    static Singleton* returnOneInstance();
    void printme() const;
};

Singleton* Singleton::singleton=NULL;
Singleton* Singleton::returnOneInstance(){
    if (!singleton){
        singleton=new Singleton;
    }
    return singleton;
};

void Singleton::printme()const {
    cout << "I'm the Singleton" << endl;
}

int main()

{
    Singleton* m=Singleton::returnOneInstance();
    m->printme();

    system("PAUSE");
    return 0;
}

Java: What is the design pattern name of utility + interface?

Lets consider the following code:

Files.walkFileTree(Path start, FileVisitor<? super Path> visitor)

Here utility is walkFileTree method of Files class. In order to work with this utility we must provide some object that implements FileVisitor interface and this object will be used by this utility. I mean that all the logic of walking file tree is in utility and and the object we provide is used just to handle special events - previsit, postvisit etc. Is this a design pattern? If yes, what is its name?

vendredi 25 septembre 2015

I would like to know if the next class model is correct according to some design patterns

The model pretends to represent a Watch and it suppose to make all by its own, like increase the value of a watchhand, I have to apply two design patters here but I'm not sure I use them correctly.

I tried to use the template method in the abstract classs called WatchHandTemplate where I pretend implements the method getTime(), this method will use the abstract method getValue so it will be ( I guess ) an implementation of the template method.

On the other hand I think that could be interesentig having a IncreaseI that will represent de stategy method, the idea is that as the watch always has the minor watchhand so this one needs a timer because for example the firs one could be in seconds but it also could be in minutes so the timer would help to control the real time it supposed to wait before it increase.

I know this is kind of hard but I really appreciate your help! I need to know if it's fine or how could I use these design patter in my model!

PS: Sorry about my writing I don't speak english I do my best! Thanks A lot!

Ps: As I'm new here I can't post images so HERE it's the link to the image that contains the model

http://ift.tt/1KEJVna

Angular Tree Design: One single controller for whole tree, or one controller per tree node?

Newby AngularJS design question. When I say "controller" I am referring to all the usual components too, like directives, templates, and other things that usually go together.

Need to create a user "workspace" with folders and objects in each folder. Users can create/delete/rename folders and their child objects. There could be maybe 50 folders max but maybe 100 objects in each folder.

Naturally I want to implement a recursive controllers idea like mentioned for this question Is it possible to make a Tree View with Angular?

  • Would there be a performance issue with a recursive controller setup or would it be better to use one controller for the whole tree?
    • What is some good sample code using a single tree controller setup?
  • In general, does AngularJS handle recursive patterns well or is it an anti-pattern for ng?

How to check the type of an object without using instance of or getClass()

Example situation: I have a television abstract superclass. Two subclasses inherit from it. Both of these two subclasses have factory methods to create their own remotes. Remote is a superclass and it has two subclasses. The remotes are able to change their respective Television's channel(in this case, a samsung remote should work with any samsung TV).

The remote classes have a changeChannel method take in a television and a channel. My question is, is there a way that I can keep this hierarchy with the methods and parameters that it currently has and not have to use conditional logic for a remote to be able to only change the channel of its own brand of television. I have provided the code below.

import java.util.*;

public abstract class Television{
    private int channel;

    public abstract Remote makeRemote();

    public int getChannel(){
        return channel;
    }

    public void setChannel(int c){
        channel=c;  
    }
}

import java.util.*;


public class SamsungTelevision extends Television{
    private int channel;

    public Remote makeRemote(){
        return new SamsungRemote();
    }   

}

import java.util.*;


public class SonyTelevision extends Television{
    private int channel;

    public Remote makeRemote(){
        return new SonyRemote();
    }

}

import java.util.*;


public abstract class Remote{

    public abstract void changeChannel(Television t,int channel);
}

import java.util.*;


public class SamsungRemote extends Remote{

    public void changeChannel(Television t,int channel){
        t.setChannel(channel);
        System.out.println("Samsung: Channel has been switched");
    }

}

import java.util.*;


public class SonyRemote extends Remote{

    public void changeChannel(Television t,int channel){
        t.setChannel(channel);
        System.out.println("Sony: Channel has been switched");
    }
}

import java.util.*;


public class Driver{
    public static void main(String[] args){
        Television t = new SamsungTelevision();
        Television t1 = new SonyTelevision();
        Remote r=t.makeRemote();
        r.changeChannel(t,35);
        System.out.println("Samsung current channel: " + t.getChannel());
        r.changeChannel(t1,37);
        System.out.println("Sony current channel: " + t1.getChannel());
    }
}

Making a pattern in python

I do not know how to use loops in python and need help to make this pattern:

*
**
***
**** 
***** 

This is what I have tried:

for x in range(0, 5):
  print ("*")    

And the result is:

*
*
*
*
*

c++ Using this pointer in constructors with std::list

I found this code somewhere, and I have found several people asking questions about why their implementation wasn't working, and every single fix is essentially the same code I've written myself, but there is a runtime error and I am not sure why. I am using VS2013, and haven't checked if any other IDEs work.

The error is:

    Unhandled exception at 0x010D9B46 in ConceptTest.exe: 
    0xC0000005: Access violation reading location 0x00000000.

Here is some code:

    class GameObject
    {
    public:
       GameObject();
       ~GameObject();

       static std::list<GameObject*> dead;
       static std::list<GameObject*> active;

   protected:
       std::list<GameObject*>::iterator it;
    };

    std::list<GameObject*> GameObject::active;
    std::list<GameObject*> GameObject::dead;

    GameObject::GameObject()
    {
       active.push_front(this);
    }

The error doesn't occur if I create a function and add the "this" pointer to the list within that function, it only happens within the constructor and my question is: why?

for example this works:

    void GameObject::Create()
    {
          active.push_front(this);
    }

P.S. I think this pattern has a name (at least it seems similar to the Singleton pattern) and I would like to know if anybody knows it.

What's this Lambda configuration "pattern" called?

Im seeing this pattern in many different Nuget-packages where you pass in a lambda expression, this is an example from TopShelf, does this configuration pattern has a name? I really like it and want to read more about it.

public class Program
{
    public static void Main()
    {
        HostFactory.Run(x =>                                 //1
        {
            x.Service<TownCrier>(s =>                        //2
            {
               s.ConstructUsing(name=> new TownCrier());     //3
               s.WhenStarted(tc => tc.Start());              //4
               s.WhenStopped(tc => tc.Stop());               //5
            });
            x.RunAsLocalSystem();                            //6

            x.SetDescription("Sample Topshelf Host");        //7
            x.SetDisplayName("Stuff");                       //8
            x.SetServiceName("Stuff");                       //9
        });                                                  //10
    }
}

This is how the HostFactory.Run method looks

public static TopshelfExitCode Run(Action<HostConfigurator> configureCallback)
{
    try
    {
        return New(configureCallback)
            .Run();
    }
    catch (Exception ex)
    {
        HostLogger.Get(typeof(HostFactory))
                  .Error("The service terminated abnormally", ex);
        HostLogger.Shutdown();

        return TopshelfExitCode.AbnormalExit;
    }
}

Converting from service-locator to dependency injection

I'm the process of cleaning up some code. I have decided to do this because it is very likely that new features will be requested in the near future and the code is hard to grok (not only because it uses a dependency container as a service locator).

To a fair extent, I understand why SL is terrible for dependency management and I've declared all dependencies of a method in the operation's signature even before I knew what OOP is.

When working with frameworks like AngularJS, you get dependency injection for free. This is not the case with my current project. The only way I can think of instantiating the application "the right way" is by service-locating everything in the main method. Please point me in the right direction toward a more elegant implementation of dependency injection.

This is my idea:

sub main()
    container = new Dic
    container->set(A, lazyNew(foo/bar/A)
    container->set(B, lazyNew(A))
    container->set(App, lazyNew(App), depends-on:[ A, B])
    // more configuration code
    app = container->get(App)
    app.main()

The flaw here is that I'm still using the container as a service locator. The only benefit is that the dependency graph is "resolved automatically" (tedious configuration and declaration of dependencies for every instance). Another pro is that instantiation happens in one place. Please help me understand how to take this to the next level of awesome.

How to block this bot requests with htaccess

How to block bot requets from Facebook via htaccess?, like:

/?c=f0xuaki
/?e=kapz4if
/?e=n7cwkdp
etc.

Print screen: http://ift.tt/1QCPuaq

I have more than 1k visits at day from Facebook :/

Thank you!

Is it bad to use interface and then check for implementation type?

Consider the following scenario:

I want to design a discount calculator which gets me the discount that can be applied to an order. There are two types of order: Online and In-Store. Based on type of the order and total amount of the order, a discount calculator calculates the discount.

I programmed to demonstrate the scenario in C# but the problem is language independent. In the below code, DiscountCalculator class calculates the discount by examining the actual type of input parameter.

I feel checking the actual type of IOrder argument in GetDiscount method is code smell; because I hid the implementation details behind the interface IOrder, then I somehow bring out of the box what was meant to be hidden.

    interface IOrder
    {
        int GetTotalPrice();
    }

    class InStoreOrder : IOrder
    {
        public int GetTotalPrice() { // returns the price of order }
    }

    class OnlineOrder : IOrder
    {
        public int GetTotalPrice() { // returns the price of order }
    }

    class DiscountCalculator
    {
        public int GetDiscount(IOrder order)
        {
            Type orderType = order.GetType();
            if (orderType == typeof(OnlineOrder))
            {
                if (order.GetTotalPrice() < 100)
                    return 2;
                else
                    return 5;
            }
            if (orderType == typeof(InStoreOrder))
            {
                if (order.GetTotalPrice() < 100)
                    return 3;
                else
                    return 6;
            }
            else
                throw new Exception("Unknown order type:" + orderType.Name);
        }
    }

Any idea?

Pyqt and general python, can this be considered a correct approach for coding?

I have a dialog window containing check-boxes, when each of them is checked a particular class needs to be instantiated and a run a a task on a separated thread (one for each check box). I have 14 check-boxes to check the .isChecked() property and is comprehensible checking the returned Boolean for each of them is not efficient and requires a lot more coding.

Hence I decided to get all the children items corresponding to check-box element, get just those that are checked, appending their names to list and loop through them matching their name to d dictionary which key is the name of the check box and the value is the corresponding class to instantiate.

EXAMPLE:

# class dictionary 

    self.summary_runnables = {'dupStreetCheckBox': [DupStreetDesc(),0],
                              'notStreetEsuCheckBox': [StreetsNoEsuDesc(),1],
                              'notType3CheckBox': [Type3Desc(False),2],
                              'incFootPathCheckBox': [Type3Desc(True),2],
                              'dupEsuRefCheckBox': [DupEsuRef(True),3],
                              'notEsuStreetCheckBox': [NoLinkEsuStreets(),4],
                              'invCrossRefCheckBox': [InvalidCrossReferences()],
                              'startEndCheckBox': [CheckStartEnd(tol=10),8],
                              'tinyEsuCheckBox': [CheckTinyEsus("esu",1)],
                              'notMaintReinsCheckBox': [CheckMaintReins()],
                              'asdStartEndCheckBox': [CheckAsdCoords()],
                              'notMaintPolysCheckBox': [MaintNoPoly(),16],
                              'notPolysMaintCheckBox': [PolyNoMaint()],
                              'tinyPolysCheckBox': [CheckTinyEsus("rd_poly",1)]}


# looping through list

    self.long_task = QThreadPool(None).globalInstance()
    self.long_task.setMaxThreadCount(1)
    for check_box_name in self.check_boxes_names:
        run_class = self.summary_runnables[check_box_name]
        # some signals I emit from my runnable
        run_class[0].signals.result.connect(self.log_progress)
        # running the task on a thread
        self.long_task.start(run_class[0])

Now, I used this approach before and it has always worked fine without using multiprocessing. In this case it works good to some extent, I can run the tasks the first time but if I try to run for the second time I get the following Python Error :

self.long_task.start(run_class[0])
RuntimeError: wrapped C/C++ object of type DupStreetDesc has been deleted

I tried to use run_class[0].setAutoDelete(False) before running them in the loop but pyQt crashes with a minidump error (I am running the code in QGIS) and I the programs exists with few chances to understand what has happened.

On the other hand, if I run my classes separately, checking with an if else statement each check-box, then it works fine, I can run the tasks again and the C++ classes are not deleted, but it isn't a nice coding approach, at least from my very little experience.

Is there anyone else out there who can advise a different approach in order to make this run smoothly without using too many lines of code? Or knows whether there is a more efficient pattern to handle this problem, which I think must be quite common?

Meaning of the XML pattern

can someone please explain me the meaning of this pattern with a example of a valid data argument.

Thank you in advance.

<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:pattern value="[A-Z]{4}\d{2}-\d{4}"/></xsd:restriction>
</xsd:simpleType>

How to implement Watcher Service for any Java object and this watcher service's threads will maintain/compare state of objects

In a system, I have many in-memory objects processing data. And I have to monitor all required objects. And if these objects crossing their thresholds user must notify for this incident. So I am thinking for creating a WatcherService for this. And any required objects must have to register for this. Here is the skeleton of my thinking.

class Foo {
    private Integer a;
    private String b;
    private Long c;
    private List<ASD> asds;

    //setter and getter
}

class Bar {
    private Integer aa;
    private Integer ab;
    private Float cc;

    //setter and getter
}

class WatchThread<T> implements Runnable, IWatchThread { // Actually IWatchThread extends Runnable
    private final T t;

    private final Set<String> paramsToWatch;

    private Boolean isRunning = false; 

    public WatchThread(T t, Set<String> paramsToWatch) {
        this.t = t;
        this.paramsToWatch = paramsToWatch;
    }

    public void run() {
        while(isRunning) {
            //Do some comparsion work by Reflection !!??!!
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }   
        }
    }
}

class WatcherService {

    private static final Map<Object, IWatchThread> watchThreads = new HashMap<>();  

    public static <T> void registerForWatch(T t, Object keyToMaintain, Set<String> paramsToWatch) {
        IWatchThread watchThread = new WatchThread<T>(objectValue, paramsToWatch);
        watchThread.setIsRunning = true;
        watchThread.start();
        watchThreads.put(keyToMaintain, watchThread);
    }

    public static unregister(Object keyToMaintain) {
        IWatchThread watchThread = watchThreads.get(keyToMaintain);
        watchThread.setIsRunning(false);
        watchThreads.remove(keyToMaintain);
    }
}

class GlobalService {
    private static Map<String, Foo> foos = new HashMap<>();
    private static Map<String, Bar> bars = new HashMap<>();

    public static void loadObjects(List<Foo> foos, List<Bar> bars) {

        //Parameters that required for watch, so by reflection a thread can access objects
        Set<String> paramsToWatchForFoo = new HashSet<>();
        paramsToWatchForFoo.add("a");
        paramsToWatchForFoo.add("b");
        paramsToWatchForFoo.add("c");

        for(Foo foo : foos) {
            //do some other stuff
            WatcherService.registerForWatch(foo, paramsToWatchForFoo);      
        }

        Set<String> paramsToWatchForBar = new HashSet<>();
        paramsToWatchForBar.add("aa");
        paramsToWatchForBar.add("cc");

        for(Bar bar : bars) {
            //do some other stuff
            WatcherService.registerForWatch(bar, paramsToWatchForBar);      
        }
    }
}

As you can see, I don't want to touch Foo and Bar. And watcher thread in back they do their work without interruption. Is this correct way to implement this? Or any other way to achieve this, required your valuable suggestion.

jeudi 24 septembre 2015

Accessing hibernate objects in a servlet from a DAO

I have created a DAO like this: This is based from: Hibernate: CRUD generic DAO

public class Dao{
    SessionFactory sessionFactory;
    // initialise session factory
    public User save(User o){
        return (User) sessionFactory.getCurrentSession().save(o);
    }

    public User get(Long id){
        return (User) sessionFactory.getCurrentSession().get(User.class, id);
    }

    public User void saveOrUpdate(User o){
                    sessionFactory.getCurrentSession().saveOrUpdate(o);
    }

Now, this is all fine, if my sessionFactory is in the DAO or in other classes. But my problem is calling SessionFactory from the servletContextListener: Here is my code in the listener:

public void contextInitialized(ServletContextEvent event)  {
    StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
    try {
        sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        event.getServletContext().setAttribute("factory", sessionFactory);
    } catch(Exception e) {
        e.printStackTrace();
        StandardServiceRegistryBuilder.destroy( registry );
    }
}

How would I call SessionFactory from the DAO in this case?

How to manage ble events across an ios app?

My iOS app receives temperature/etc data from another device, a peripheral. I can receive events at any time, but want to be able to navigate to other screens while the temperature samples are being collected and not lose any samples. I don't want to be tied to the view controller that implements CBCentralManagerDelegate methods. I've broken this out as a singleton class that inherits from NSObject, MyDevice.

I'm trying to figure out how to manage all the events coming in and have new screens be able to subscribe and unsubscribe from these events all the time as a user moves throughout the app. Does it make sense for this class to keep the overall @property (strong, nonatomic) CBCentralManager * and implement CBCentralManagerDelegate? How is this commonly managed?

Assembler vs Entity Translator and Entities vs DTOs

I was hoping that someone could explain the exact difference between an Assembler and Entity Translator.

Martin Fowler describes the Assembler as a sort of Mapper(?) which converts DTOs into Domain objects and vice versa.

When you're working with a remote interface, such as Remote Facade (388), each call to it is expensive. As a result you need to reduce the number of calls, and that means that you need to transfer more data with each call. One way to do this is to use lots of parameters. However, this is often awkward to program - indeed, it's often impossible with languages such as Java that return only a single value.

The solution is to create a Data Transfer Object that can hold all the data for the call. It needs to be serializable to go across the connection. Usually an assembler is used on the server side to transfer data between the DTO and any domain objects.

However, this description sounds very similar to the Entity Translator.

"Implement an entity translator that transforms message data types to business types for requests and reverses the transformation for responses.

The entity translator is an object that is tightly coupled to message data types and business entities, while providing loose coupling between the consumers of the types. In other words, components of an application use the translator to transform data types and the translator has no knowledge about operations provided by the application. This behavior provides the ability to change data types on either end of the interaction without requiring changes to the other end. The only component that needs to be updated is the translator itself"

So this is a little bit confusing.

The reason why I'm asking this question is because I'm currently building out a client library which will allow me to retrieve/send data through remote REST API; however as I map this response data into my DTOs I had considered creating an additional anti-corruption(?) layer which will then map those DTOs into my Domain Models.

Basically, I would like to distribute these libraries via composer as a prepackaged module but still have the flexibility to swap them out should I find something better.

Another question I'd like to ask is how to differentiate between Entities + DTOs since Entity is a term which is often brought up whenever I discuss Data Mappers(which is how I'm currently structuring my client libraries). Although I just referred to them as DTOs; the term "Entity" is often used to describe the type of objects you would either pass into or retrieve via the Data Mapper.

I suppose it's possible that I've been using Active Record pattern for far too long but the two of them basically just look like Anemic Domain Models me - ie: just getters and setters.

How do I properly distinguish between the two?

What OO pattern can I use to assemble a PDF with data?

Question:

I am looking for a good pattern to structure my code to produce a PDF document.

What I have

  • PDF API (methods & functions that take HTML and CSS and turn them into PDF)
  • User Input

Example Starting Code

class DesignPDF
{
    protected $pdf;
    protected function createPDF($title)
    {
        $this->pdf = new PDF_API();
        $this->pdf->SetTitle($title);
    }
}    

class Product_A_DesignPDF extends DesignPDF
{       
    public function showPdf($inputData)
    {
        parent::createPDF("Product_A");

        $design = new \DesignProcessor();
        $outputData = $design->process($inputData);

        $html = "<html><body>hi, your data is $outputData</body></html>";

        //PDF API - injects HTML into the PDF instance
        $this->pdf->AddNewPage();            
        $this->pdf->writeHTMLCell($html);
        $this->pdf->Output("screen");
    }
}

//TO call:
$designPdf = new Product_A_DesignPDF();
$inputData = sanitize($_POST)
$designPdf->showPdf($inputData);    //shows PDF on screen

What I don't like is that my PDF_API (outside library) is a dependence of my DesignPDF class. I do not immediately know how to get rid of that dependency. I can inject it of course, but I have a feeling there is a whole lot of a better way to (re)structure my code.

Birds, bees and abstract classes

Newbie me is currently stuck at this seemingly simple problem. Let's say I want to write some code about a bunch of animals procreating happily everafter. Obviously, they'd all need a mate() method, so I could define an abstract class like this:

class FemaleAnimal {
public:
    virtual FemaleAnimal mate(const MaleAnimal& a) const = 0;
    virtual MaleAnimal mate(const MaleAnimal& a) const = 0;
}

And derive all the different species:

class FemaleBird : public FemaleAnimal {
public:
    FemaleBird mate (const MaleBird& b) const;
    MaleBird mate (const MaleBird& b) const;
}

class FemaleBee: public FemaleAnimal {
public:
    FemaleBee mate (const MaleBee& b) const;
    MaleBee mate (const MaleBee& b) const;
}

with males implemented likewise. In main(), I want two vectors

males = vector<MaleAnimal>
females = vector<FemaleAnimal>

each of which might contain both birds and bees, and is filled at run time. The species at each index match, so if males[i] is a bee, then females[i] is also a bee, so I can do

vector<FemaleAnimal> femaleOffspring;
vector<MaleAnimal> maleOffspring;
for (int i=0; i<males.size(); ++i){
    femaleOffspring.push_back( females[i].mate(males[i]) );
    maleOffspring.push_back( females[i].mate(males[i]) );
}    

Now, obviously I want the mate() method in the derived classes to implement the one in the base class, but then I'd have to define mate() for animals in general, such as

FemaleBee::mate(const MaleAnimal& a) const;

But bees don't mate with birds. How would I achieve that kind of specialization? Is there some special design pattern for this? I've tried to look into things like covariance, but that was more confusing than helping.

Bonus question: How do I capture the case when males[i] and females[i] are of different species at runtime?

WCF Service Dependency Injection and Static Factory

I have a service that needs to return a code each time method GetNext() is called. For that, I have several code providers implementing an interface. The same code provider should be used between ServiceHost opening and closing, and so for each service call. I would like to avoid creating one instance of the code provider at each call.

I already looked at several posts, in particular dependency injection for WCF services (mostly Mark Seemann's answers), where solutions using IInstanceProvider and ServiceHostFactory allow to pass parameters during service construction. Perhaps I did not fully understood what was happening there, as I have no extended knowledge of WCF. I ended up implementing a static factory and using it in the service implementation as follows:

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single,
                 InstanceContextMode = InstanceContextMode.PerCall)]
public class CodeService : ICodeService
{
    public string GetNext()
    {
        return CodeProviderFactory.GetCodeProvider().GetNextCode();
    }
}

If needed, I could extend this by passing the type of code required to the factory, getting it from configuration DB or file, but that is not the point. Is this the best way to have one single instance of the code provider, and if not, what would be the correct (i.e. more elegant, performant and maintainable) solution? Also is the concern of having a single instance of the code provider legitimate?

SQL Server Compare data and replaced together

I have two string as below

 ***ABCABCABCABCABC***
 BBBTTTTTTTTTTTTTTTCCC

I want to replace * position only from below string

So results could be

 BBBABCABCABCABCABCCCC
 BBBTTTTTTTTTTTTTTTCCC

Is there any way to have elegant solution to using SQL Server function?

I already did it using below.

 DECLARE @Value1=PATINDEX('%[A,C,G,T]%', '***ABCABCABCABCABC***')
 Select SUBSTRING('BBBTTTTTTTTTTTTTTTBBB', 0, @Value1)
 ....

But this is required many if eles .

I want to know is there any simple way to replace it or not.

Thank you!

Does anyone use plain old 3 tier architecture?

So I've been learning about architectural styles and patterns. From what I can see, when it comes to 3-tier architecture, most people are using a pattern (such as MVC for example). But my question is, does anyone just use a plain old 3-tiered, bi-directional architecture without any patterns? Is that practiced or even acceptable in industry?

mercredi 23 septembre 2015

Getting data to outside from libwebsockets interface

I have made a simple libwebsockets server according to this link: http://ift.tt/WluCya. The name of the server module is WebsocketInterface.

Outside this server interface, in the same application, I have a class DataHandler, which needs to read some user-submitted information from the WebsocketInterface to control itself.

Inside the WebsocketInterface I can read the user input from void* in in the block case LWS_CALLBACK_RECEIVE: and it works fine.

My question is that what could be a proper and effective way to deliver this data to the class DataHandler?

My current solution is to use a singleton class, let's call it WebsocketMessenger. This class is included and instantiated by both modules, WebsocketInteface and DataHandler class. The WebsocketMessenger has a buffer where the WebsocketInterface writes the user input and where the DataHandler can read it from.

This singleton-based solution works in the way I want it to. However, I'm curious if there are other design patterns applicable to this situation. What would be your solution?

Variable privacy in Javascript's behaviour delegation pattern

Since my last question, I've been studying Javascript's prototype model and trying to get rid of the OOP vision I inherited from other languages (pun slightly intended).

I went back to basics and read Crookford's Javascript: The Good Parts, along with You Don't Know JS material and decided to stick with the so called behaviour delegation.

Restructuring my previous example implementing behaviour delegation and namespacing, I wrote:

var GAME = {};

(function(namespace) {
    var Warrior = {};

    Warrior.init = function(weapon) {
        this.setWeapon(weapon);
    };

    Warrior.getWeapon = function() {
      return this.weapon;
    };

    Warrior.setWeapon = function(value) {
      this.weapon = value || "Bare hands";
    };

    namespace.Warrior = namespace.Warrior || Warrior;
})(GAME);

(function(namespace) {
    var Archer = Object.create(namespace.Warrior);

    Archer.init = function(accuracy) {
        this.setWeapon("Bow");
        this.setAccuracy(accuracy);
    };

    Archer.getAccuracy = function() {
        return this.accuracy;
    };

    Archer.setAccuracy = function(value) {
      this.accuracy = value;
    };

    namespace.Archer = namespace.Archer || Archer;
})(GAME);

So, everytime I copy a new Archer object:

var archer1 = Object.create(GAME.Archer);

only this object will be created, conserving memory.

But what if I don't want to expose "accuracy" attribute? The attribute would only increase by calling a "training()" method or something similar. I tried to use var accuracy inside the anonymous function, but it turns into kind of static variable, all instances of Archer would share the same value.

The question: Is there any way to set a variable as private while still keeping behaviour-delegation/prototypal pattern?

I do know of functional pattern as well, Here I succesfully achieved variable privacy, at the cost of memory. By going functional, every new "archer" instance generates a new "Warrior" and then a new "Archer". Even considering that Chrome and Firefox have different optmizations, testings on both report that the Delegation/Prototypal pattern is more efficient:

http://ift.tt/1MqejFH

If I go with the pure-object delegation pattern, should I just forget the classic encapsulation concept and accept the free changing nature of properties?

Python OOP Factory Pattern

I am still learning OOP Design Pattern and everything I have read so far says that Factory Patterns are commonly used. I am still trying to learn this pattern. For my program I am creating an Abstract Factory called "person" and my factory called "personFactory" should let you create different types of people (Users, Customers, Plumbers, etc...). With my current code I am getting this error:

AttributeError: 'module' object has no attribute 'createUser'

This is my code:

person.py

import abc

class person:
    __metaclass__ = abc.ABCMeta
    fName = ""
    mName = ""
    lName = ""
    address = ""
    city = ""
    state = ""
    zipcode = ""
    email = ""
    phone = ""
    dob = None

    @abc.abstractmethod
    def __init__(self,fName=None,mName=None,lName=None,address=None,city=None,state=None,zipcode=None,email=None,phone=None,dob=None):
        self.fName = fName
        self.mName = mName
        self.lName = lName
        self.address = address
        self.city = city
        self.state = state
        self.zipcode = zipcode
        self.email = email
        self.phone = phone
        self.dob = dob

personFactory.py

from person import person

class personFactory(person):

    def createUser(self):
        uName = ""
        password = ""
        role = ""
        def __init__(self,uName,password,role):
            self.uName = uName
            self.password = password
            self.role = role
        def login(uName,password):
            if(uName == self.uName and password == self.password):
                return "Logged In"
            else:
                return "Did not log in"
        def logout():
            return "Logout"

    def createCustomer(self):
        items = []
        balace = 0
        def __init__(self,balance):
            self.balance = balance
        def AddToCart(item):
            self.items.append(item)
            print("Item added")
        def Order(items):
            totalprice = 0
            for item in items:
                totalprice =+ item.price
            return totalprice
        def Pay(payment):
            self.balance =- payment
            return self.balance

main.py

import personFactory

class main():

    user1 = personFactory.createUser()
    user1.fName = "John"
    user1.lName = "Smith"
    user1.uName = "jSmith"
    user1.password = "Jamestown"

    customer1 = personFactory.createCustomer()
    customer1.fName = "George"
    customer1.lName = "Washington"
    customer1.balance = 100

main()

I'm not sure why I cannot call createUser. What am I doing wrong? Any help would be greatly appreciated!

Create a object with depenencies that have to be configured

I am creating a client using GuzzleHttp 5.3. I want use the same Config object to configure the Guzzle Client. So, the creation of Guzzle Client depends of the object Config.

For example:

$config = new Config([
    'user' => 'github',
    'password' => '1234',
    'base_url' => 'http://ift.tt/1Ptwlr5'
]);

new GithubClient($config, new \GuzzleHttp\Client());

And the constructor:

public function __construct(Config $config)
{
    $this->authData = [
        'uname'     => $config->getUser(),
        'upassword' => $config->getPassword(),
    ];

    $this->config       = $config;
    $this->httpClient   = new \GuzzleHttp\Client(['base_url' => $config->getBaseUrl());
    // I have to setup default headers, too.
}

But, I have to inject the Guzzle Client because I have to do unit tests.

One option is to inject a Guzzle Client configured as my client requires it. But the build process is a little cumbersome (set base_url, default header). The user must to know using Guzzle, I do not like this.

Other option is to create a new object (GithubClientFactory for example) to create my client.

$client = GithubClientFactory::make($config);

So, I hide the Guzzle dependency and the setup process. But the user always have to use the client factory.

Then, Is there a better (pattern) design to this problem?