mardi 31 mai 2016

Background Recurring Jobs overuse red flags

I encountered a design practice in LOB (Line-of-Business) application where many scheduled Jobs are created.

We know clear-cut scenarios where Jobs are good fit - like sending e-mail notifications, but in this particular case, many parts of business logic is implemented to run in various intervals. In most cases, some internal data processing is done and outcome is saved back to the database, then some other Job picks it up, and so on.

In isolation each job kind of make sense – for example the processing is time consuming etc., but at one point I started to think:

  • How many Jobs we can have until it gets out of hand,
  • What could be unintended consequences of overusing this design,
  • Is something fundamental missing in overall design or architecture?

Question is :

When Jobs could be considered inappropriate, are there any red flags to look for? Also, what architectures are there that might addresse this sheduled job approach?

Decorating a method in Ruby

I have method that takes as a parameter an array of integer numbers, and I would like to use the decorator pattern to validate first if each of the numbers in the array is in a specified range.

I've seen decorator in ruby that extend class or include modules, but this seems a little excesive to me, is there a way to just decorate a method without relaying on a class or module ?

What is the best way to calculate values over time from incoming stream

Running a C# .net app that receives data every 30 seconds from 100 clients and then stores data in a database. The data is for two parameters for each client. I need to determine the total for each parameter, for each client per hour and make decisions based on the results. The decisions algorithm would be making decisions for the last hour worth of data in a sliding window fashion. My initial thinking is to keep a dictionary of those 100 clients with key being client IP, and value being a running total. However 1) if my app restarts half way through the hour or at minute 59, I lose all those warm running totals. 2) if more clients start sending data, dictionary will consume more memory, 3) if in the future the 2 parameters become 100, the dictionary grows even bigger 4) making the running total value always reflect one-hour worth of recent data is not straightforward.

Is there any different approaches I should consider? best-practice? design patterns?

Thanks.

Is this good aproach? Sensors in Observer DP

I am developing small simulation app and I've been wondering if it's good idea to use observer design pattern in my program. The idea is that there is a house with a couple of rooms, each room has a couple of sensors. Temperature, motion, smoke etc. Will this work? Is this a good use of the observer pattern? The whole app would work like this: you can add/remove a sensor in the building, e.g. temperature sensor would change the temperature, motion sensor would have possibility to spot motion. Thanks for any feedback

Proxy Design Pattern- tutorialspoint.com example

http://ift.tt/1lLFDpn

Hi,

I am looking to understand proxy design pattern in java using the example in the link above. In main method I don't understand the difference between:

  //image will be loaded from disk

  image.display(); 
  System.out.println("");

  //image will not be loaded from disk

  image.display();  

Is this a typo? How can the same 2 image.display() methods give different outputs?

Thanks a lot!

Machine learning, Threading, design pattern recommendation [on hold]

I am creating a project that uses a few machine learning algorithms. More to the point I'm working with a data set where I plan to run several algorithms on it, let's call each run a job.

After a job runs with some measuring functions I will evaluate the result. Also since at one point I would like to write a simple gui for this project where pushing a simple RUN button I will be able to run all my algorithms at once and present my result in this gui. Here each algorithm probably should run on his own thread.

To sum it up I need to design a system where I can start several tests in the same time. ( As far as I'm concerned it's not a problem if they don't finish in the same time ).

I'm fairly new to design patterns and I'm not sure what solution is the best in this situation.

I did check out a few patterns and I have a feeling I should be using the Builder design pattern, but I'm not sure how to implement the multi threading functionality in to it. And also I'm not sure that I used the Builder pattern correctly. I'm working in Java.

Simplistic example of my system with two interfaces:

public interface Tester{
public MyAlgorithm  runTest();
public void evaluateTest();
}

    public interface MyAlgorithm{
    public void implementAlgorithm();
    }

    public class Algorithm_1 implements MyAlgorithm(){
    @Override
    public void implementAlgorithm(){// implementation of algorithm nr. 1
    }

    public class Test1 implements Tester{
    @Override
    public MyAlgorithm runTest(){ return new Algorithm_1();}
    @Override
    public void evaluateTest(){//test evaluation code will be same for all alg.
    }
    }

Am I on the right track? Also how could I implement multi threaeding in this design?

How to handle nested dynamics objects in PHP?

I have a foreach that instances several kind of classes and this must be nested. They all extends of the same Abstract class.

<?php
$A1 = class A extends Parent { $type = 1 }
$A2 = class A extends Parent { $type = 2 }
$B = class B extends Parent {}
$A3 = class A extends Parent { $type = 2 }
$C = class C extends Parent {}

// foreach ([$A1, $A2, $B, $A3, $C])

But $A1 can not be nested, $A2 can only be nested by $A1, $B can be nested by $A1 and $A2 but should be nested by $A2 because it's the previous object that can nest it, $A3 should be nested to $A1, etc.

I don't need to handle any specific case but all the cases.

How should I handle this nesting? I was thinking about defining a function in the class that does the foreach, or maybe in the Parent class, that have all this cases defined inside.

What is MVC(Model, view and Controller) and how does it work?

I have a hard time understanding what MVC really is and especially how it works.

whats the purpose of MVC?

how does the flow in the pattern work?

what componets are used and how do They work?

Whats the advantages and disadvantages with MVC?

Please do a simplified explanation in detail, I am very new to coding.

Whats the difference between an interface and a pattern?

i have a hard time knowing when something is an interface or a pattern. For example what are observer - observerable and what are MVC?

Best way for communication between directives

Copied from here. May be, I can get more proper answer here!

There seem to be quite a few ways of communicating between directives. Say you have nested directives, where the inner directives must communicate something to the outer (e.g. it's been chosen by the user).

<outer>
  <inner></inner>
  <inner></inner>
</outer>

So far I have 5 ways of doing this

require: parent directive

The inner directive can require the outer directive, which can expose some method on its controller. So in the inner definition

require: '^outer',
link: function(scope, iElement, iAttrs, outerController) {
   // This can be passed to ng-click in the template
   $scope.chosen = function() {
     outerController.chosen(something);
   }
}

And in the outer directive's controller:

controller: function($scope) {
   this.chosen = function(something) {
   }
}

$emit event

The inner directive can $emit an event, which the outer directive can respond to, via $on. So in the inner directive's controller:

controller: function($scope) {
  $scope.chosen = function() {
    $scope.$emit('inner::chosen', something);
  }
}

and in the outer directives controller:

controller: function($scope) {
  $scope.$on('inner::chosen, function(e, data) {
  }
}

Execute expression in parent scope, via &

The item can bind to an expression in the parent scope, and execute it at an appropriate point. The HTML would be like:

<outer>
  <inner inner-choose="functionOnOuter(item)"></inner>
  <inner inner-choose="functionOnOuter(item)"></inner>
</outer>

So the inner controller has an 'innerChoose' function it can call

scope: {
  'innerChoose': '&'
},
controller: function() {
  $scope.click = function() {
    $scope.innerChoose({item:something});
  }
}

which would call (in this case) the 'functionOnOuter' function on the outer directive's scope:

controller: function($scope) {
  $scope.functionOnOuter = function(item) {
  }
}

Scope inheritance on non-isolated scope

Given that these are nested controllers, scope inheritance can be at work, and the inner directive can just call any functions in the scope chain, as long as it doesn't have an isolated scope). So in the inner directive:

// scope: anything but a hash {}
controller: function() {
  $scope.click = function() {
    $scope.functionOnOuter(something);
  }
}

And in the outer directive:

controller: function($scope) {
  $scope.functionOnOuter = function(item) {
  }
}

By service injected into both inner and outer

A service can be injected into both directives, so they can have direct access to the same object, or call functions to notify the service, and maybe even register themselves to be notified, in a pub/sub system. This doesn't require the directives to be nested.

Question: What are any potential drawbacks and advantages of each over the others?

Is it possible use regex for image recognition (computer vision)

Is it possible to transform an image into a textual code using regex? For instance can regular expressions be used for recognizing patterns or counting objects, or reading text (OCR)?

How can I polymorphically structure a database?

This might be a stupid question but I have very little experience. I have encountered an issue where I am working with a Excel spreadsheet for a small factory.

It has a huge list of products that are grouped into families.

analogy: Corolla, Avensis, Landcruiser = Toyota

Furthermore the products have a list of tasks associated with them.

Corolla: Step 1 Step 2 Step 3...

All products share tasks in the first few stages even across different families. But some occur at a different stage during production What may be step 6 in productX is step 5 in productY. But productX and productY share 1-5. (And this is true across the board.

I have three questions. Is it possible to polymorphically structure a database? Common tasks can be placed in the base class and get more specific (common for OO).

If it is not can you create a central database of unordered tasks and give some sort of priority to each database of a product and they give the tasks some order.

Final question is has anyone encountered such a problem? I have a feeling there has to be a design pattern to this. It feels like a solution is just beyond my grasp.

Transform Specification in plain SQL

How can I transform specification (Specification pattern) in plain SQL? Without any ORM.

Benifits from using Mediator pattern with Command pattern

I've seen some production code where Mediator pattern is used with Command pattern.

To be concret, I will provide an example, that I have seen in some course.

public class Mediator {
    List<Light> lights = new ArrayList<>();

    public void register(Light light) {
        lights.add(light);
    }

    public void turnOnAllLights() {
        lights.stream()
                .filter(light -> !light.isOn())
                .forEach(Light::toggle);
    }
}


public class TurnAllLightsCommand implements Command{
    private final Mediator mediator;

    public TurnAllLightsCommand(Mediator mediator) {
        this.mediator = mediator;
    }

    @Override
    public void execute() {
        mediator.turnOnAllLights();
    }
}

So, what benifits do we get from using Mediator here?

My point of view is the following:

  1. Commands are decoupled from each and do know nothing about colleagues, but it is achivebale without mediator (by just creating an invoker class, that takes Command for execution).
  2. In each command we get a new mediator object, and in command execution we just delegate the work to mediator.
  3. For each new command, that provides a specific operation, we should create a new Mediator implementation, or add new methods to an existing implementation.
  4. Being a client we can directly access both turnOnAllLights.execute() and mediator.turnOnAllLights(). I find it a bit confusing.

Am I missing something?

Code architecture of service interface and service impl classes spring

I found out that in an MVC pattern, there are mainly 4 classes; the controller, the service, the service impl and repo.

Service is an interface and service impl implements service class and contains all the logical codes. The structure would be something like :-

Service interface class

Service{

public void someMethod();

}

ServiceImpl class

 ServiceImpl implements Service{
  public void someMethod(){
   //do something

   }    
 }

But when we want to access the service impl codes from controller, we call the method of service class as :-

@Autowired 
Service service;

Object obj =  service.someMethod();

How does the controller execute code of ServiceImpl class

Can an Abstract Factory be responsible for "creating or finding an existing" item?

My Ruby code has a Concrete Factory, which builds some complex objects:

author = Author::Factory.build(email: "john@example.com")

class Author
  class Factory < BaseFactory
    def self.build(email: nil)
      # ... Some data preparation and defaults
      Author.new(
        email: email
        # Map and assign more attributes
      )
    end
  end
end

Now, I've run into a situation where I either need to build a new one, or assign one from an existing collection. In database-terms: an UPSERT, or in ActiveRecord: find_or_create_by.

And I am not sure if this:

  1. Is a proper task for an Abstract Factory and
  2. If the proper way to implement this is by passing the collection, or to make the Factory itself responsible for fetching it.

Passing it in:

author = Author::Factory.build(email: "john@example.com", existing: authors)

class Author
  class Factory < BaseFactory
    def self.build(email: nil)
      author = existing.find {|author| author.email == email }
      # If not found, prepare and build a new one, like above.
    end
  end
end

Letting the Factory find it:

author = Author::Factory.build(email: "john@example.com")

class Author
  class Factory < BaseFactory
    def self.build(email: nil)
      author = Author.find_in_existing_with(email: email)
      # If not found, prepare and build a new one, like above.
    end
  end
end

So: Should a Factory every be responsible for finding-or-building?

And if so, must the Factory be responsible for fetching the items that it must match against, or should the caller pass them along?

Guid me please..Please how can i create web api and mvc solution seperatly?

I need a help..Basically i'm new to the .net application.Here am trying to develop an application for Accounting Purpose.Am totally confused that how can I use the design pattern..MVC is preferring. I have to use this app both in Desktop and as a mobile app.App should be more secure.So please guide me how to design the project can you please suggest any examples?

1.WebApi + MVC is good option i think but for this,should i create 2 solution for both api and mvc? 2. should it work smart phone as well as desktop?

Database-PostgreeSql

Application will have two parts – Part I – Accessible to the client through the web page Part II – Back-end accessible only to us (Company) where all the processing is carried out Perform the initial setup once the client is registered – create the account in the accounting software and create the chart of accounts 1.Review and process documents 2. Accounting – the entries will be passed in the application and will be exported to the accounting software

lundi 30 mai 2016

Can this (below) be considered a facade (scructural design pattern)?

function BankOperationChecker() {
    //This is the facade
    this.applyFor = function(facadeMethods) {
        for (var method in facadeMethods) {
            facadeMethods[method]();
        }
    }
}

function BankClient(name, amount) {
    this.name = name;
    this.amount = amount;
    this.bankOperations = new BankOperationChecker();
}

var client = new BankClient("Davi Vieira", 2000);
var checkMethods = {
    cleanBackground: function() {
        console.log('The background of this client is clean.');
    },
    canGetCredit: function() {
        if (client.amount > 1000) {
            console.log('Can get credit!');
        } else {
            console.log('Cannot get credit!');
        }
    }
}

client.bankOperations.applyFor(checkMethods);

What do you think? Facade for entrance is just one... but is that right? Is there any specific rules about creating a facade?

Design considerations for high volume search

I am working to come up with solution for following problem scenario: Say, an organization offers General & specialized deals for its customers. General deals apply to ALL customer but specialized deals only for those who meet defined criteria (e.g.; customer of Gold loyalty class, customer with age between 18-26 etc.). Now requirement is that when a customer logs onto organization's portal, he/she is offered the deals that are applicable specifically to him (so general + specialized ones of which Customer meets conditions). Trouble is there are hundreds of possible deals & few million of customer. So, for each specific customer - it will mean searching through hundred of deals and applying various match criteria logic. Imagine situation when there can be hundreds of concurrent users. System is web-based with possibility of mainframe data store, application logic. What solution do you suggest to handle such huge volume of search logic to be executed? Possible options that I see: (1) On mainframe, have a batch application do the heavy processing of identifying what deals apply to which customer and store the deal-id, customer-id as a result in RDBMS. This might mean, that if on an average 4 deals apply and there are 2 million customer then there will be roughly 8 million rows of data. This will however, make life easy for web-portal to search applicable deals with just specifying the customer-id. Of course, Some performance tuning will be required to speed-up response time for the (single) query. But on high level, it will work. (2) Web-portal application might check eligibility of all deals for entered customer-id, one after the another. This will mean, that if there are X nr of deals then for each customer login, application will (a) Get all relevant customer details from database A, (b) Match retrieved customer details with X nr of deals criteria, to identify the matching ones that can finally be shown to customer. This approach however will mean execution of tens of complex queries on different databases, which ultimately will slow-down response time for the customer.

Do you see other options and better solution approach?! Please suggest if there is any known design patter/ approach to handle such problems.

Thanks, GG

RESTful API best practices

I'm an Android Developer and also have some knowledge of RESTful API development. Currently I'm building an API using Dot Net Web API. Everything's working fine but I'm still concerned with the design. The core concern for me now is what exactly should be the Metadata of the response like what other helpful elements I can add apart from 'Response Code' and 'Response Message'. Second concern for me is that should the request be asynchronous or the query or both. And the last concern is what technique should I use to make a stateful communication like JWT or Basic Authentication, etc.

iOS - Swift: Confused about the design pattern using protocol in a single viewcontroller app?

I've been working with swift for 2 years. But till now i'm still confuse about using Protocol, as its defination, protocol is a blueprint of methods, properties?

But be practical, why don't i pass one instance through classes or using global variables instead of using protocol?

For example i can do this:

Global variable:

var vc:UIViewController!

class vc:UIViewController
{
 var cc:ExClass!
 func viewDidLoad() {
  vc = self
  cc = ExClass()
  cc.anymethod()
 }
 func methodToCall() {
   print("hello")
 }
}
class ExClass() {
  func anymethod() {
     vc.methodToCall()
  }
}

Or i simply can pass the instance of UIViewController to ExClass, so ExClass can access to any properties, methods in UIViewController

I've tried to switch to use protocol.

However in example, if i have only 1 UIViewController like this, in this controller some parent views (one UIView for main screen, one UIView for setting), in each parent view has it own custom gesture, typer or some classes ...

And in these classes, i need to access to all the methods from parent views, and UIViewController also.

So, to get my app works, i have to pass the delegate through multiple levels classes, like from UIViewController to parent views, In custom gesture, i have delegate of UIViewController and its parent view also, in the other classes i have the same number of delegates .

It so complex and become a mess! And i really don't know about memory usage, of these design patterns, i want my app use the less memory as it can.

So what is a good design pattern or purpose of using protocol / delegate in this case?

Column level entitlement implementation by Design pattern

I want to implement column level entitlement by using design patterns. In our application will have to restrict user to query specific column only.

for example.

Table : employee

id number(10,0), fname varchar2(100), lname varchar2(100), address varchar2(100), age number(10,0),


Users: U1,U2

I want to give access/entitlement of [id,fname,age] columns to user U1 and [id,lname,address] columns to user U2.

which design patter i will use to implement it.

Which design pattern to use (Active and passive methods)?

I have a player which can feed a dog or chop a tree.

Below are the classes I have written:

public class Dog {

    private int health;

    public void feed(Food food){
        health = health + food.getNutritionalValue();
    }
}

public class Player{

    public void feed(Dog dog, Food food) {
        dog.feed(food);
    }

Player and Dog both have methods that are "active".

Player feeds the dog and dog starts eating the food (I am not really sure if it is good to couple methods in this way).

On the other hand, I have tree. And player is able to chop the tree.

public class Player{

public void chop(Tree tree) {
        //At this point I am not sure
    }

I am not sure if I would use getters and setters of Tree class to interact with the Tree.

Or if I should write an own method for this because the tree gets chopped so it is nothing really active I would call.

So, in the end, there would be two or more kinds of implementations but the two I am thinking of are:

tree.setAmountofWood = x

or

tree.gettingChopped(Damage int)

I think I should make an own method for this chopping-process.

Or is there any design principle I should follow?

Decorator Pattern design

I'm pretty new with patterns and I'm studying Decorator Pattern for a program I have to write.

Studying online, I found an example of a Decorator Pattern (it is Java pseudo-code):

class Solution1
{
    static interface Component 
    { 
        void doStuff(); 
    }

    static class MyComponent implements Component 
    {
        public void doStuff()
        {
            // ...
        }
    }

    static class ComponentDecorator implements Component  // This is the Decorator pattern.
    { 
        private final Component component;

        public ComponentDecorator(Component component) 
        {
            this.component = component;
        }

        public void doStuff()
        {
            this.component.doStuff();
        }
    }

    static class ComponentDecorator1 extends ComponentDecorator 
    {
        public ComponentDecorator1(Component component) 
        {
            super(component);
        }

        private void doExtraStuff1()
        {
            // ...
        }

        public void doStuff()
        {
            super.doStuff();
            doExtraStuff1();
        }
    }

    static class ComponentDecorator2 extends ComponentDecorator 
    {
        public ComponentDecorator2(Component component) 
        {
            super(component);
        }

        private void doExtraStuff2()
        {
            // ...
        }

        public void doStuff()
        {
            super.doStuff();
            doExtraStuff2();
        }
    }

    public static void main(String[] args)
    {
        MyComponent         c   = new MyComponent();
        ComponentDecorator1 cd1 = new ComponentDecorator1(c);
        ComponentDecorator2 cd2 = new ComponentDecorator2(cd1);

        cd2.doStuff(); // Executes Component.doStuff, ComponentDecorator1.doExtraStuff1, ComponentDecorator2.doExtraStuff2
    }
};

When I analyzed the example, I realized that in the past I made a very similar pattern but in different way:

import java.util.*;

class Solution2
{
    static interface Component 
    { 
        void doStuff(); 
    }

    static class MyComponent implements Component 
    {
        public void doStuff()
        {
            // ...
        }
    }

    static class ComponentDecorator implements Component  // This is NOT the Decorator pattern!
    { 
        private final List<Component> components = new ArrayList<Component>();

        public ComponentDecorator() 
        {
        }

        public void addComponent(Component component)
        {
            this.components.add(component);
        }

        public void removeComponent(Component component) // Can Decorator do this?
        {
            // ...
        }

        public void doStuff()
        {
            for(Component c : this.components) c.doStuff();
        }
    }

    static class ComponentDecorator1 implements Component 
    {
        public ComponentDecorator1() 
        {
        }

        private void doExtraStuff1()
        {
            // ...
        }

        public void doStuff()
        {
            doExtraStuff1();
        }
    }

    static class ComponentDecorator2 implements Component 
    {
        public ComponentDecorator2() 
        {
        }

        private void doExtraStuff2()
        {
            // ...
        }

        public void doStuff()
        {
            doExtraStuff2();
        }
    }

    public static void main(String[] args)
    {
        ComponentDecorator cd  = new ComponentDecorator();
        cd.addComponent(new MyComponent());
        cd.addComponent(new ComponentDecorator1());
        cd.addComponent(new ComponentDecorator2());

        cd.doStuff(); // Executes MyComponent.doStuff, ComponentDecorator1.doExtraStuff1, ComponentDecorator2.doExtraStuff2
    }
}

In my opinion, the second example can be used in same situations where a Decorator Pattern can be used, but it's more flexible (you may, by example, remove or reorder the components in the list), so my questions:

  • Is solution 1 (correct Decorator Pattern) better than solution 2? Why?
  • Is it possible to add functions for removing instances in solution 1?
  • Is it possible to add functions for reordering instances in solution 1?

dimanche 29 mai 2016

regex with previous regex in java [on hold]

how can using previous regular expression in next regular expression in java

String Identifier = "^(\\w(\\w|\\d))*$"

String term = "^({Identifier}|\\d)$";

thanks

iOS better approach for sending in-app exceptions, crashes, network request data and display data

I need to add to an existing iOS app the capability to send three different type of statistics by issuing GET requests to a web-server, and I would like to know the best approach to satisfy all of these requirements:

  • error statistic: send this GET request anytime there is an exception or app crash.

  • screen load statistic: this GET request has one parameter in the query string that expresses the amount of time taken (in ms) from when the user initiated a request that show the screen to the point where the screen has finished drawing.

  • network statistic: send this GET request anytime there is a network request in the app. This request has one parameter in the query string that expresses the amount of time taken (in ms) for the complete request.

For the network statistic my own idea is generating a NSMutableArray somewhere used to store any Stat instances. To grab the amount of time taken for each network complete request I thought I can simply create an instance of networkStatistic before each network request, and using closure of the complete block of the network request to refer to the same instance and determine the amount of time taken from its creation. Finally, the instance can be pushed in the array and consume any instance inside it with ease.

About screen statistics, I thought about the following method valid only when the user interacts with the Navigation: I create an instance of screenStatistic in each viewWillAppear of each VC, and use viewDidAppear to grab the previously created instance and set the amount of time taken from its creation (similarly to the previous method). After I can add it into the Stat Array and the job is done. How can I solve the problem in the other cases, for example when the user click to a button that fetches new data from the server which is used to update the screen?

About error statistics, I really have no idea how I can catch app crashes. About exceptions, can you confirm that network errors are not considered exception, but errors that have to be displayed to the user (like an alert box)?

Thank you all, and sorry for being a bit verbose.

How to Create Pin Pattern Password using xamarin form?

I am trying to create a pin pattern password screen. I was wondering what is the best way to develop this using Xamarin forms. I have looked into the documentation , but did not help me. Can this be done using one of the Gesture event? Any pointers highly appreciated.

enter image description here

What's the best practice for implementing a 'semi-virtual' method?

I know there can't exist a 'semi-virtual' method, however, I've run into a design related issue.

Let's say I have a base class called WebPage. This class has a method called UpdatePage(). But because this method exists within an abstract WebPage object, the UpdatePage() method is virtual, and should be implemented by a user who is deriving a concrete class from WebPage.

But let's say that when the UpdatePage() method is called, it would be ideal that it timestamps some class data member regarding the last update time.

I'm in a position where I want some default implementation from a method (i.e. do a timestamp), but I also want the implementation to be custom to the concrete class derived from the base class WebPage.

I know I could come up with some technique to solve this issue. For example, I could make UpdatePage() non-virtual, and have it contain two methods: a timeStamp() method which is non-virtual, and a updateImplementation() method which is pure-virtual. This way when a user calls UpdatePage(), there would exist default and custom behavior.

But again, if there exists some design pattern/rule for this, I'd like to not reinvent the wheel.

Thanks!

How to fake a library (GDI to Xamarin.Forms) across namespaces and platforms such as reusing Color struct

Im attempting to reuse legacy Windows GDI code in Xamarin without modifying the legacy GDI code (except using #if). In this specific case I need to use Color from Xamrin.Forms wrapped in my own color struct. I get the error cannot convert as posted in the question header above.

This is the legacy code that is not to be modified (or very little)

#if WINDOWS
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Windows.Forms;
#else //if Xamarin
using FakeGDI;  //cannot specify 'using Xamarin.Forms;' in legacy class

#endif
namespace LegacyCode
{
    public class MyClass
    {
        public MyClass ()
        {
            Color x = Color.Yellow;  //must not change legacy code
        }
    }
}

This is the code to adapt the legacy GDI calls to Xamarin.Forms

using System;
//cannot specify 'using Xamarin.Forms;' I want to fully qualify Xamarin.Forms as shown below 'Xamarin.Forms.Color.Yellow;'

namespace FakeGDI
{
    public struct Color
    {

        public static Color Yellow 
        {
            get { 
                return Xamarin.Forms.Color.Yellow;
                ;}
        }
    }
}

The solution I'm looking for is to get this to compile and use the Xamarin.Forms Color struct via my Color struct indirectly.

What is needed to allow this type of conversion?

Thanks

Can we make a Singleton class by making private getInstance method and public getter setter methods?

Doesn't Singleton class just means enforcing of presence of a single instance of a class always? If that is the case, unlike the norm, can't we have getter-setter methods in it with private getInstance method? In short, is below class an example of Singleton class? Why / Why not:-

public class MySingletonClass {
private MySingletonClass mySingletonClass;
private String name;
private MySingletonClass(){

}
private MySingletonClass getSingletonClassReference(){
    if(mySingletonClass==null){
        mySingletonClass = new MySingletonClass();
    }
    return mySingletonClass;
}

public static String getName() {
    return getSingletonClassReference().name;
}

public static setName(String name) {
    getSingletonClassReference().name = name;
}}

Using the Revealing Module Pattern, why is this object changed?

Given the following code:

var House = function(x, y) {
    var _posX;
    var _posY;

    function init(x,y) {
        _posX = x;
        _posY = y;
    }

    // Auto init
    init(x, y);


    // Public
    return {
        posX: _posX,
        posY: _posY,

        setPosition: function(x, y) {
            _posX = x;
            _posY = y;
        }
    };
};

If I create a new House object:

var house = new House(3,4);

And use the setPosition method to change the position:

house.setPosition(100,50);

I expected that the house position would still be 3,4.. But it however changed (which is actually what I want, but I don't understand how this is possible?) I dont'understand it since Javascript already returned the position which is 3,4 and I would expect it to be like that all the time, even if I change the position using the set method.

Bonus question: is there a proper way to do the init rather than placing it, ugly in the middle of the code?

Role of Invoker class in Command pattern

let's assume that we have command pattern implemented in this way

I am a bit confused about the role of Invoker here. From my point of view:

  1. If we do need history (or any kind of action before command execution), then there is a sense in making this class. But then it breaks Single responsibility principle, yeah? Now it's not only a delegate, it also stores history there.
  2. If we don't need history, I don't see a goal of creating this invoker, that simply performs delegating. Is the only reason for it is just a assumption, that we would need some kind of logic before/after command execution in the future?

Or am I missing something?

Cannot implicitly convert type `Xamarin.Forms.Color' to `FakeGDI.Color' with special coding considerations

Im attempting to reuse legacy Windows GDI code in Xamarin without modifying the legacy GDI code (except using #if). In this specific case I need to use Color from Xamrin.Forms wrapped in my own color struct. I get the error cannot convert as posted in the question header above.

This is the legacy code that is not to be modified (or very little)

#if WINDOWS
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Windows.Forms;
#else //if Xamarin
using FakeGDI;  //cannot specify 'using Xamarin.Forms;' in legacy class

#endif
namespace LegacyCode
{
    public class MyClass
    {
        public MyClass ()
        {
            Color x = Color.Yellow;  //must not change legacy code
        }
    }
}

This is the code to adapt the legacy GDI calls to Xamarin.Forms

using System;
//cannot specify 'using Xamarin.Forms;' I want to fully qualify Xamarin.Forms as shown below 'Xamarin.Forms.Color.Yellow;'

namespace FakeGDI
{
    public struct Color
    {

        public static Color Yellow 
        {
            get { 
                return Xamarin.Forms.Color.Yellow;
                ;}
        }
    }
}

The solution I'm looking for is to get this to compile and use the Xamarin.Forms Color struct via my Color struct indirectly.

What is needed to allow this type of conversion?

Thanks Anna

Setting default argument for an extended class

I am making an application that involves create/retrieve/update/delete operations.

So for the add and edit method I want to re-use core components that are the same in both functions. So I made a shared abstract class and then my add and edit classes extend the shared so they each have the same core but can still have differences.

I instantiate these objects/Fragments by using the newInstance method, which is where I usually pass in arguments, set them into the Bundle, and then read them back in the onCreateView methods.

However I need to be able to pull in arguments to the shared class, but I can't because it's abstract, and when I instantiate the objects, I am instantiating Edit and Add objects, which means only the child classes can have arguments.

What's the accepted practice for getting around this?

public abstract class SharedStuffDialogFragment extends DialogFragment {
    protected MyObject mMyObject; //I'd like to be able to init. this

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.shared_layout, container, false);

        //do a bunch of other stuff here, sharable attributes
        initOtherThings(savedInstanceState);
        return contentView;
    }

    protected abstract void initOtherThings(Bundle savedInstanceState);


}

And then for example, the add class:

public class AddDialogFragment extends SharedStuffDialogFragment {
    private static final String ARGUMENT_OBJECT = "argument_object";
    private MyObject mMyObject;

    public static AddDialogFragment newInstance(MyObject object) {
        Bundle args = new Bundle();
        args.putParcelable(ARGUMENT_OBJECT, object); //would really rather set this to shared
        AddDialogFragment fragment = new AddDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initOtherThings(Bundle savedInstanceState) {
        mMyObject = getArguments().getParcelable(ARGUMENT_OBJECT);
        //do stuff unique to add operations
    }

}

Cloud architecture pattern for multiple simple api clients (200-500m api calls/day)?

I have to write an api-client system that connects to multiple api-servers, does a job and disconnects. It does two simple things, but needs to do it at scale (ie: aiming for 200-500m outbound API client calls per day):

(1) Simple client connects to an API-server (http/rest), sends a query, receives a response (text based), saves the response for later, and moves on to the next server/query.

Once responses start coming in, a separate process will:

(2) parse the text in the responses and add them to a large file/queue for reporting

I currently have a test system in C#, running 20 console applications on a machine, with 20 threaded clients in each console application carrying out the work. I need to be able to scale this up on demand. What is the best approach to do this? ... I am sure a solid pattern exists to this simple problem?

My thoughts so far are:

-> design a management system that depending on the volume of API-servers to be queried in a given hour, orchestrates the provisioning of virtual machines (not trying to redesign the wheel - will hook into any existing framework like chef/puppet etc if suitable)

-> have a central system for collection of data from the api-clients (perhaps a node instance passing the data off to RabbitMQ for later pickup/processing)

-> have a separate management system that orchestrates the text parsing of data received from the API clients.

-> As project is network latency bound, I believe development language is not really relevant so long as it has good network support.

My main questions then are around:

(1) What would be a most appropriate language/framework to implement this in to enable a lean/cost-effective system? ... ie: no point in spinning up multiple Windows VMs for example if they have a bigger footprint/overhead/cost than doing the same thing in linux? (so in this case I could use the mono framework - get the benefit of C# that my team knows, but the lower cost of linux VMs...)

(2) Is my thinking about having to spin multiple VMs up to do this correct (albeit small VMs running X client applications each)?

(3) Another approach I thought of is to write the clients in Javascript - the reason being that the bottleneck for the api-client is network and api-server response time, not client-side, so it might be well suited to async work? .... in this case I could have one Node server running 100x more api-clients than I could ever get in even a bunch of micro-windows VMs ?

(4) Finally, am I reinventing the wheel? ... is there anything out there on Amazon or Azure already that I can plug into that would provide a ready framework for what I need?

All comments and suggestions and guidance most welcome.

Many thanks.

samedi 28 mai 2016

Add an object in the deph "level" of an object composition with collections

I'm learning java and starting to try to do things in the right way...

I don't know if the Title is right, please advice me if it's not clear, english is not my mother language. I have a too large amount of code to post it. So i made this "simplify" version for evidence my doubt.I think it's more clear. If is not enough clear please tell me.

  • The context: I have a object A who have a collections of B object, and B have a collection of C objects, and C... a collection of D. I need to put the D object in this "composition"(?) of objects. The object D have the information about in which C object should be put in. every C object is assigned to a B object according his id.
  • The problem:How to know in A to whish B object pass the D object.
  • The "solution": make a method to filter the D object according his id and return the B object id.

This is the scheme of my solution:

    public class Test2 {
    public static void test (String args[]){
        A a = new A();
        //... filling the A,B,C data..
        //... done...
        //.. now the cake:
        public String newD = "C=45,D=67,more info...."; // 45 is the C id, 67 is the D id.
        D dude = new D(newD);
        // so i need to put this friend in the C object...
        a.addSomeDude(dude); // looks easy...
    }

}
class A{ // I have 3 B's in my collection = B_1, B_2, B_3. And i can have more...
    private List<B> Blist;
    private String id;
    // blah blah
    public void addSomeDude(D dude){ //... ok, i have some problems... i don't know where to put this dude
        String Bid = SaveTheday.whoGoesWhere(dude.getId()); //oh! you save the day SavetheDay, what a suitable name!
        for(B bDude : Blist)
            if(bDude.getId() ==Bid ){
                bDude.addSomeDude(dude);
            }

    }
    //some things...
}
class B{ // I have some C's in my collections...
    private List<C> Clist;
    private String id;
    //blah blah blah
    public void addSomeDude(D dude){ //... i know where to put this dude, i just get the C id from the dude...
        for(C cGuy : Clist)
            if(dude.getCid() == cGuy.getId()){
                cGuy.addSomeDude(dude);
            }
    }
}
class C{ // I i have some D dudes...
    private List<D> Dlist;
    private String id;
    //yes, more things...
    public void addSomeDude(D dude){
        D objectDude = new D(dude.getCId());
        Dlist.add(objectDude);
    }

}
class D{
    private  String id;
    private String cId;
    //...some things and getters
}
class SaveTheday{
    //...well, maybe i can do the job...
    public static String whoGoesWhere(String id){
        String [] B_1 = {"1","2","3","4","5","6"}; // these are C ids...
        String [] B_2 = {"11","22","33","44","55"};
        String [] B_3 = {"12","45","55","66","77"};
        for( String i : B_1)
            if (i.equals(id))
                return "B_1";
        for( String i : B_2)
            if (i.equals(id))
                return "B_2";
        for( String i : B_3)
            if (i.equals(id))
                return "B_3";
        return null;
    }
}

This eventually works, but I'm starting to thinks it's a very not friendly OO principles solution. Why?

  1. What if i need to add a new C id? yes, add it to the comparison method, but, what about the "open to expansion, no to modification" principle?
  2. And if i need to add a new B, unknown number of B's?
  3. Where the hell put the whoGoesWhere method, i think i did a good job encapsulating the comparison (i can change it without affect the others classes) but, where to put it? is in the right place?
  4. i feel out there should be a better solution to this problem, more flexible, expansible and maintainable solution.

So, can you guys tell me what I'm missing? there's some pattern what I'm not seeing? I hope a expressed myself right, if not, please tell me to add more details.

Merging data received in a web service request (design-related, not looking for code)

Assume I have a class called Vehicle that is saved to a datastore using whatever framework. Vehicle has some set of properties, and based on the user's permissions, I want the user to be able to set some of these properties and not others.

Is there/are there any established patterns for this type of use case? Let me give a better example:

I make a PUT request to a web service to update an record. The service decides based on my permissions, it can only trust certain properties of the record and not others.

The straight-forward implementation I can think of is to have the service take my copy of the record, overwrite whichever fields it doesn't trust from me (by overwriting them with whatever it already has), and then continue with saving/updating the record.

Any suggestions?

Design for Graphic Rendering in Java with Unspecified update reasons (Hierarchical)

I'm working for graphic rendering part of my program, and got into several severe problems with my previous design.

So, I want to ask how to design structures of renderers and models. Or is there specific design pattern to handle this case?

Currently I have hierarchical implementations of

  • Renderers (Graphics)
  • Models (Data to Render, Receive Updates)

I accepted hierarchy since rendered contents can be classified, and should be managed separately.

There are several limiting conditions:

  1. Rendering is done on rendering loop.
  2. There could be many types of renderers and models, and the design should not be aware of them.
  3. There could be various reasons to update models.
    1. Update reasons should not be specified in the design itself, since various reasons can be added.
    2. Models are aware of possible update reasons for itself.
  4. Renderers have Render Passes and Render Helpers.
    1. Types of Render Passes are dependent to the Classes(groups) of renderers.
    2. Render Helpers should be provided, and each renderer should be able to use different version of it.

EDIT: Source to explain current situation.

Renderer:

public interface IRenderer<Settings, Pass, Model, Helper> {
    public void initialize(Settings settings);
    public void preRender(Settings settings, Helper info);
    public void renderPass(Model model, Pass pass, Helper info);
    public void postRender(Settings settings, Helper info);
}

Model:

public interface IModel<Settings, UpdateInfo> {
    public void initialize(Settings settings);
    public void update(Settings settings, UpdateInfo update);
}

Tcp Ip server in .Net

I was recently at a job interview where I was asked this question(More or less as I don't remember the full question. This is the out of the top of my head):

You need to make a simple tcp server that can be accessed through puTTy (or any other client for that matter).

Once you are in, you need to write:

login < username > (Doesn't matter what username).

once you are logged in you have 3 operations you can do:

  • showDevices - will return a list of devices (Currently we have lamp and an airconditioner) - we can write mock objects. Let's assume they have a number Id.

  • Switch < deviceId > < on|off > - sets the device on or off.

  • SetValue < deviceId > < double > - set's the device's ranged value (Air condition tempature)

Important things:

  • Separation - Separate the logic and communication layer. We work with a telenat server now but we will want to switch to an http server in the future. The process should be easy.

  • Extensibility- We currently have 4 operations (login, showDevices, Switch, SetValue) - write the server so it would be very easy for other programmers to add another operation. The code should be self-explanatory

The assignment could have been written in any language. I tried writing it in C# until I was stuck and couldn't continue. I had the tcp server running but could not really think of the full solution.

  • How do I best seperate between the communication and the logic layer?

  • Is there some sort of design pattern I should implement for adding commands easier? (I looked at the command design pattern and I couldn't figuere out if it was meant for this kind of situation)

Anything that can actually direct me in the right track will be appreciated.

Thanks!

Separate logic from logging via template method pattern

May I use this template method pattern for separate logic from logging and exception handling or it is "bad practice"?

For example I have this code:

public abstract class Parent {
    private final Logger log = LoggerFactory.getLogger(getClass());

public void eat() {
    try {
        doEat();
    } catch (SomeException1 e) {
        log.debug("some text");
        throw new CustomException1();
    }
}

protected abstract void doEat();

public void sleep() {
    try {
        doSleep();
    } catch (SomeException2 e) {
        log.debug("some text");
        throw new CustomException2();
    }
}

protected abstract void doSleep();
}

And my child class:

public class Child extends Parent {
@Override
protected void doEat() {
    //some logic
}

@Override
protected void doSleep() {
    //some logic
}}

I would not have different implementations of methods doEat() and doSleep().

I want to know whether it's worth it and is it 'bad practice' or not.

Should the Repository pattern manipulate an object before passing it to the consumer/service layer?

The current solution I am working with is structured with a single Core layer that is connecting to the database whenever it needs to retrieve data.

I suggested to a few colleagues that we create a DAL layer and move all of the database logic into it's own project and call it

Application.DataAccess

This layer will use Entity Framework and the repository pattern as an abstraction between Application.Core and Application.DataAccess (The Repository implementation will sit within Application.DataAccess).

I plan to to consume the repository in a service layer.

public class JobService
{
   private IJobRepository _jobRepository;

   public JobService(IJobRepository repository) 
   {
      _jobRepository = repository;
   }

   public IEnumerable<Job> GetJobs() 
   {
      List<Jobs_AllJobs> allJobs = _jobRepository.GetAllJobs();
      List<Job> result = new List<Job>();

      foreach(job in allJobs) 
      {
        result.Add(new Jobs() { Title = job.Title, OtherEntity = "Internal to the service"; });
      }          

      return result;
  }
}

Job Repository:

public class JobRepository : IRepository<Jobs_AllJobs>
{
     DBContext _jobContext;

     public List<Jobs_AllJobs> GetJobs() 
     {
         return _jobContext.Jobs_AllJobs.ToList();
     }
}

This is where it gets slightly heated between us.

I believe that the JobRepository should return a list of the database entity Jobs_AllJobs rather than manipulate the database entity and construct a new List of Job (This should be handled in the service layer). My colleagues believe that the manipulation should be done at the Repository level and that the JobRepository should pass back a List<Job> or IEnumerable<Job> rather than the database entity.

From my understanding the Repository pattern is meant abstract away the internal database implementation (Entity Framework/nHibernate/File System) and solely perform a CRUD operation upon database (Create, Retrieve, Update or Delete) and that the JobService should perform the manipulation and construct a new object and pass that back down to the consumer.

Which way would be correct? And which way follows the repository pattern the best?

How to organize Rails app where each customer has it's own specific gem list?

I'm creating an architecture of the app and trying to find the best one. Few words about it:

  • Box solution (each app installed on customer's machine)
  • There is a Main app and gems to extend it (private)
  • Main app has default list of gem
  • Other functionality extending by adding additional gems by request (our gems)

But some customers no need full functionality, so we don't need to include all gems to it's Gemfile.

What is the best way to organize it? What do you think about this way? Maybe you can offer more effective way?

Design pattern for bi directional data format conversion

I work on a project that will deal with different data formats.

for example, suppose i have the following data formats:

formatA, formatB, formatC, ...

with the following classes.

formatA:

public class dataFormatA {

    private String data;

    public dataFormatA(String data) {
        this.data = data;
        // convertData(this.data);
    }

    public dataFormatB convertToDataFormatB() {
        return new dataFormatB(data);
    }

    public dataFormatC convertToDataFormatC() {
        return new dataFormatC(data);
    }

}

formatB:

public class dataFormatB {

    private String data;

    public dataFormatB(String data) {
        this.data = data;
        // convertData(this.data);
    }

    public dataFormatA convertToDataFormatA() {
        return new dataFormatA(data);
    }

    public dataFormatC convertToDataFormatC() {
        return new dataFormatC(data);
    }

}

formatC:

public class dataFormatC {

    private String data;

    public dataFormatC(String data) {
        this.data = data;
        // convertData(this.data);
    }

    public dataFormatA convertToDataFormatA() {
        return new dataFormatA(data);
    }

    public dataFormatB convertToDataFormatB() {
        return new dataFormatB(data);
    }
}

What is the best design pattern to make? currently, each class has a method to convert its data type to the rest of data formats classes. But this is not a good design as it violat the open close principle

vendredi 27 mai 2016

Would this work for reverse image search?

Hello I've worked on a PHP code which takes two images and does the following:

scale them down to 200x200px

add a grey filter and a contrast which is equal to 50

imagefilter($im, IMG_FILTER_GRAYSCALE);
imagefilter($im, IMG_FILTER_CONTRAST, 50);

then I have two loops which scans the entire image X-Y pixel by pixel and saves the HTML color code to an array. Then compares the first array to the array of the second image.

Then at the end get the percentage of the similar HTML codes at the same X-Y angle. I tried this on three images and compared them with my own profile picture (which has quite a dark tone, I'm not sure if this is why I get such a high percentage which I will show soon)

  • Me vs Picture of Bill Gates: 14% similar
  • Me vs Picture of friend with a dark tone: 66%
  • Me vs Me: 89%

So I won but my friend was dangerously close because we both have a dark background. Now I'm wondering, what's a more accurate way of doing this without e.g pattern recognition?

Besides reverse image search I also want to take two exact same pictures of the same person but on different social medias e.g Instagram + Kik and make sure it's the same person. A friend suggesting putting them both into MD5sum but this won't work because of scaling, styling, filters etc.

I'm new to image manipulation and recognition etc, If anyone is knowledgeable within this subject or has any advice, research-paper or algorithm to look up it would be appreciated! :)

Does programming to an interface help get rid of globals?

Or is my interface the new "global"? I'm trying to find a way to get rid of statements like:

function someFunction()
{
    global $var1, $var3, $var4;
    //these are eventually assigned instantiated classes from an include
    ....
}

So far I am only coming up with interfaces. I am thinking my code will only be a little looser, maybe a lot. But if I really wanted to loosely couple after implementing an interface (or extending a class), couldn't I always create another level of abstraction between the interface and the inheriting classes with another abstract class or interface?

How can I start to get rid of globals other than rewriting an entire project?

Designing an API client

I need to design and implement a client for a couple of APIs. I went searching for posts, comments and suggestions on how to build it but I couldn't find much.

I decided to use the Google API client and the Twilio API client as a reference and design guide.

Is this a good approach? Can you recommend materials I can read?

My language of choice for this project is Python and the website APIs I need to make requests to are: - Green Button - Solar City - Locus Energy - and similar

Anti-if purposes: How to check nulls?

I recently heard of the anti-if campaign and the efforts of some OOP gurus to write code without ifs, but using polymorphism instead. I just don't get how that should work, I mean, how it should ALWAYS work.

I already use polymorphism (didn't know about anti-if campaign), so, I was curious about "bad" and "dangerous" ifs and I went to see my code (Java/Swift/Objective-C) to see where I use if most, and it looks like these are the cases:

  1. Check of null values. This is the most common situation where I ever use ifs. If a value could possibly be null, I have to manage it in a correct way. To use it, instead I have to check that it's not null. I don't see how polymorphism could compensate this without ifs.
  2. Check for right values. I'll do an example here: Let's suppose that I have a login/signup application. I want to check that user did actually write a password, or that it's longer than 5 characters. How could it possibly be done without if/switches? Again, it's not about the type but about the value.
  3. (optional) check errors. Optional because it's similar to point 2 about right values. If I get either a value or an error (passed as params) in a block/closure, how can I handle the error object if I just can't check if it's null or isn't?

If you know more about this campaign, please answer in scope of that. I'm asking this to understand their purposes and how effectively it could be done what they say.

So, I know not using ifs at all may not be the smartest idea ever, but just asking if and how it could effectively be done in an OOP program.

Configuration for command line / server application in java

I am developing a larger project at the moment that is supposed to run cross-platform and even on systems without graphical user interface / command line only. It requires lots of configuration and my current approach (properties file) is getting messy.

I have thought about some kind of web panel similar to the "web server" feature of h2 database, where you are able to connect to "localhost:1234" and have a *.jsp user interface. But writing my own HTTP server seems overkill to me. Also, I have no idea about jsp in general.

Maybe a bit more about the input my app gets: User data + password(encrypted), interval settings, datetime settings, data templates, ...

What is a good configuration system to use here?

What's wrong when to nested classes needed to create an object using decorator pattern?

Recently I try actively to use basic design patterns. But I end up these types of objects creation in my factories

$aStandardField = new Viewable(new Translatable(new Errorable(new Validatable(new Viewable(new FormField())))));

the $aStandardField is an object that if it has a value , it's value is validatable and if there is an Error , the error id will be registered there, and the error is viewable on the top of the field .... . This code looks smelly to me. So the question is how can I keep my classes small while keeping the core (FormField in the above example) untouched ,using the decorator pattern?

Design pattern for a implementation of multiple strategies based on different inputs

There is a design pattern that I can apply to this kind of scenario?

I have processes classes that implements BaseProcess class: BaseProcess has a CreateProcess(BaseObject o) method and BaseObject has two childs or many.

 ProcessClassA : BaseProcess
 ProcessClassB : BaseProcess

 ObjectA : BaseObject 
 ObjectB : BaseObject 

I want to be able to have a class Process that can have multiples ProcessClasses like in this case 2 classes but that can have more in the future like 3 classes or more and that process. And I want to use the class like this:

Process.Process(BaseObject o) and send specific object and let the Process class call the specific class such as ProcessClassA if I send ObjectA. The problems is I dont want to use if inside process becuse I will need to one that class when I add ProcessClassC

Example:

ObjectA exampleObj = new ObjectA  

Process p = new Process(List<BaseProcess>{ProcessClassA ,ProcessClassB }) //Something like this but dont need to be in the contructor or be a list could be //something else but that allows not to violate Open Close principle.

p.Process(exampleObj) => ProcessClassA.Process(exampleObj)  

E-commerce > Improving adding to cart experience

I'm in the process of building a webshop and i'm trying to optimize user experience piece by piece.

In most webshops when you add an item to the cart the shop a) reloads the screen and adds the item b) uses ajax to add item and wait for response of the server.

I'm thinking about this: When the user adds an item, the user immidiatly gets a response on screen ( item xx is added to cart + nice subtle animation ), without waiting for a server response. To me this would give the user a more fluid shopping experience.

But what about an error? Well, if the server response is an error, i could present that information to the user. Since errors should not happen often (if it did, the code needs to be improved), i think this is an acceptable trade-off.

What do you think? Are there problems i'm not aware off?

Is it best practice to design Spring Application in such a way that we need to create same context multiple times?

I am going to start a new project using Spring framework. As I dont have much experience in Spring I need your help to sort out few confusions.

Lets look at use case

My application uses Spring integration framework. The core functionality of my app is,

  1. I need to poll multiple directories from file system,
  2. read the files(csv mostly),
  3. process some operations on them and insert them to database.

Currently I have set up spring integration flow for it. Which has inbound-chaneell-adapter for polling and then file traverse through the channels and at the end inserted into database.

My concerns are

  1. Number of directories application supposed to poll will be decided at runtime. Hence I need to create inbound-chanell-adapter at runtime (as one chanell adapter can poll only one directory at once) and cant define them statically in my spring context xml (As I dont know the how many I need).

  2. Each directory has certain properties which should be applied to the file while processing.(While going through the integration flow)

  3. So right now what I am doing is I am loading new ClassPathXmlApplicationContext("/applicationContext.xml"); for each directory. And cache the required properties in that newly created context. And use them at the time of processing (in <int:service-activator>).

Drawbacks of current design

  1. Separate context is created for each directory.
  2. Unnecessary beans are duplicated. (Database session factories and like)

So is there any way to design the application in such a way that context will not be duplicated. And still I can use properties of each directory throughout the integration flow at the same time???

Thanks in advance.

is this a decorator pattern (PHP)?

I was watching a Lynda.com PHP Design Patterns tutorial when the tutor presented this solution to a challenge:

index.php:

include_once 'decorator.php';

$object = new Decorator();
$object->sentence = "This is a sample sentence that we're going to   manipulate in the Decorator.";

// This should output: this is a sample sentence that we're going to     manipulate in the decorator.
echo $object->lower();

// This should output: THIS IS A SAMPLE SENTENCE THAT WE'RE GOING TO     MANIPULATE IN THE DECORATOR.
echo $object->uppercase();

decorator.php:

class Decorator
{
        public $sentence = '';

    public function lower()
{
    return strtolower($this->sentence);
}

public function uppercase()
{
    return strtoupper($this->sentence);
}

Why is this a decorator pattern? All I see is the instantiation of an object and accessing two of the objects methods.

powershell replace data in files sub directory (ok) only if line begins with some specific string (ko)

it s ok to replace a string in all files sub directory with this :

initial in line : 02#APPLICATION/PDF;name="P31F9B000A00001.pdf"* replace by : # P31F9B000A00001 can be anything

with this pattern :

$array = @("D:\cebi")
$myRegExp1 = [regex]"#APPLICATION/PDF;name=""(.*).pdf""\*"
$myRegToReplace1 = "#"
$myRegExp2 = [regex]"\*ClasseAutomatique\*2016\*"
$myRegToReplace2 = "*ClasseAutomatique*2016*Faux*"
foreach ($element in $array) {
    Get-ChildItem $element  -Recurse -Include "*.DAT" | foreach-object {Copy-Item $_.fullname ($_.fullname+".bak") -recurse } 
    gci $element -r -include "*.DAT"| foreach-object { $a = $_.fullname; ( get-content $a ) |  foreach-object { $_ -replace $myRegExp1,$myRegToReplace1 -replace $myRegExp2,$myRegToReplace2  }  | set-content $a } 

}

But now, i would like do replace a string only for the lines begins by a specific string in bold, it can be anything

i want to replace string "ClasseAutomatique" by "ok_man" only if line begins by "02#APPLICATION/PDF;name=" intial string :

02#APPLICATION.PDF;name="P31F9B000A00001.pdf"-anything_data.2016.##_ClasseAutomatique_2016__##P31F9B000A00001****.pdf 01#APPLICATION.PDF;name="**P31F9B123D02651.pdf"-anything_data.2016.##_ClasseAutomatique_2016__##**P31CKB000D00002****.pdf

Result would be :

02#APPLICATION.PDF;name="P31F9B000A00001.pdf"-anything_data.2016.##_ok_man_2016__##P31F9B000A00001.pdf 01#APPLICATION.PDF;name="P31F9B123D02651.pdf"-anything_data.2016.##_ClasseAutomatique_2016__##P31CKB000D00002.pdf

i try this :

$myRegExp3 = [regex]"^(02#APPLICATION/PDF;name=(.).pdf)-(.).2016.##_(ClasseAutomatique)_2016__##(.*).pdf"

$myRegToReplace3 = "$1-$2.2016.##_ok_man_2016__##$4.pdf"

but nothing

Referencing several models from one model class- Bad practice?

I want to obtain all notifications for current user with this code:

current_user.follows.each do |follow|
    follow.followable.open_notifications.each do |notification|
        if !notification.reads.include?(current_user)
            @open_notifications += notification 
        end
    end
end

So far I had this code in my controller however I know this kind of logic should be place in model class. After moving code:

OpenNotification Controller:

OpenNotification.fetch_unread(current_user) 

OpenNotification Model:

def self.fetch_unread(user)
    @open_notifications = []
    user.follows.each do |follow|
        follow.followable.open_notifications.each do |notification|
            if !notification.reads.include?(user)
                @open_notifications += notification 
            end
        end
    end
    @open_notifications
end

EDIT:

Classes involved:

  • User
  • Follow - who(user) follows what(followable)
  • Followable(polymorphic - may be User, Event or a Place)
  • OpenNotification - stores information about the change of followable object
  • Read - who read which notification (user_id and open_notification_id)

User:

has_many :follows, class_name: 'Follow',
                 source: :user

has_many :follows_as_fallowable, 
                class_name: 'Follow',
                as: :followable

has_many :followers, through: :follows_as_fallowable,
                   source: :user

Event:

has_many :follows, as: :followable
has_many :followers, through: :follows,
                         source: :user

has_many :open_notifications, as: :followable  

OpenNotification:

belongs_to :followable, polymorphic: true
has_many :reads

Reads:

belongs_to :user
belongs_to :open_notification


My question is if it is a good practice to refer to multiple classes from the class responsible for one particular resource?
If this is not a good practice, how the code should be refactored?

Design base class for derived classes with functions having different signatures

class B {
public:
    virtual void foo(?);
}
class D1 : public B {
public:
    void foo(T1*);
}
class D2 : public B {
public:
    void foo(T2*);
}

B* b1 = new D1();
B* b2 = new D2();

T1 and T2 may not be related.

How do I design the classes such that called b1 and b2 call the correct foo with correct type?

Can use upto c++14.

Passing around parsed arguments makes no fun

I use arparse in Python to parse arguments from the command line:

def main():
    parser = argparse.ArgumentParser(usage=usage)
    parser.add_argument('-v', '--verbose', dest='verbose', action='store_true')
    parser.add_argument(...)
    args = parser.parse_args()

I use object args only in few places of the code.

There are three methods and the call stack looks like this

def first_level(args):
    second_level()

def second_level():
    third_level()

def third_level():
    ### here I want to add some logging if args.verbose is True

I want to add some logging to third_level().

I don't like to change the signature of the method second_level().

How can I make the arg object available in third_lelvel()?

I could store arg as global variable, but I was told to not use global variables in a developer training some years ago ....

What is common way to handle this?

jeudi 26 mai 2016

is it true "new operator considered harmful"? [on hold]

is it true "new operator considered harmful" ? I read this here

I read this Question but it's limited to Javascript , looking ans for java or other OOP language like PHP , python

Handle network requests/responses in a UI independent manner (and cancellable)

I have an app that is composed of 2 list fragments and 1 simple fragment with a layout view.
First list fragment shows a list of ~20 items.
Each item when clicked results in a network call that brings from a server ~70 items (max) that are displayed in another list in the second list fragment.
Once the user clicks in the list item data specific to that item are fetched from network and displayed in the last fragment.
So basically the first list is "broken" down to data. But the items in the second list are not more than ~70.

Design:
I have used volley queue for the network calls and functionality-wise it works fine and I display the data I need fine.
I have added a listener to the volley request and from my listener I update my adapter(s)

Problem:
Due to the fact that on click of the first fragment as I move to the second I start these backend calls and as I go to the third these calls are queued (I can see it in the logs), if I go to the third fragment the calls for the rest of the items are kept on firing and same if I go back to first.
Due to the fact that I get the responses for these requests from the Volley within the adapters and the actual fragment might not be "relevant" anymore, how can I design this better?

Android design pattern to manage UI elements

The answer to this question would be a design-pattern, to be used in development of Android applications, that simplifies the way user interface elements are managed such that many such elements can be managed centrally even though acted upon from various places in the application.

Given a small application without too many states, managing UI elements in the activity life cycle methods is fine. If the application grows and can change states based on processes outside the main thread, the number of places where changes are being made increases. This makes the application less maintainable (having state changing code in many places). I seek a design pattern that makes it more clear what happens to the UI in the various states.

I realize that persistence tools such as SQLiteDatabase andSharedPreferences are available, which might be part of the design pattern, but central control, where the state of the app can be maintained, along with control over what the user sees and what the user is able to do is the goal.

ValueObject pattern in django models

Currently I want to use the Value Object Pattern in my django project. I have a class Price like this:

class Price(object):
    def __init__(self, value, currency):
       self.value = value
       self.currency = currency

And now I want to use this class in a normal model. The question is simple, how should I use it in the model? What type of field?

My most important requirement is, that I can access the price directly on an instance of the model. So that I could write something like this:

item.price.in(Currency.EURO)

So I don't need to call some methods to invoke for example deserialization, if I store the price as JSON in the database.

Thanks for your help!

Design pattern for doing a sequence of operations on an I/O based object

I find myself frequently writing code that follows the following sequence:

  1. Attempt to open an I/O based resource (i.e. from a database and/or file). This could potentially fail.
  2. If successful, perform a series of operations via the object.
    • These operations change based on user input. For example: filter data, do calculation A, do calculation B, write the results somewhere.
    • Each of these operations could potentially fail and return with an error message. If a failure occurs at any time, the sequence should abort.
    • Some operations must be done before others: writing results cannot occur before calculations, for example.
  3. Close the resource.

Is there a design pattern that would work well for a flow like this? When I try to wrap the above sequence into a class, the immediate problems I always run into are:

  • How do deal with opening the resource. Ideally I would like to open it during class construction, but that gets messy if there is an error. Otherwise, I have to pass in a reference to the resource in the constructor, followed by an Open() method.
  • How to make the flow of operations flexible to a user of the object, but not burdening them with the need remember to call a bunch of intermediate methods and/or a lot of error checking.

Design Patterns for PowerShell Cmdlets (in C#)

Working on a PowerShell Module in C# and something occurred to that seems logical but I can't find any other info to confirm or correct my assumptions.

Say I have one Cmdlet looks something like this

[Cmdlet(VerbsCommon.Get, CmdletHelpers.Noun, SupportsShouldProcess = true)]
[CmdletBinding]
public class GetSomething : PSCmdlet
{
    protected override void ProcessRecord() 
    { 
        var SomeCustomObject = new SomeCustomClass()
        WriteObject(SomeCustomObject); 
    }
}

Then say I have another Cmdlet which accepts a SomeCustomObject as a Parameter.

[Cmdlet(VerbsData.Import, CmdletHelpers.Noun)]
[CmdletBinding]
public class ImportSomething : PSCmdlet
{

    [Parameter(Mandatory = true, ValueFromPipeline = true)]
    public SomeCustomClass SomeCustomObject { get; set; }

    protected override void ProcessRecord()
    {
        // Do Something with SomeCustomObject
        // Return modified SomeCustomObject
        WriteObject(SomeCustomObject);
    }
}

So I would assume that a PowerShell Cmdlet that takes in a particular parameter should usually not modify the parameter and instead create a copy if changes need to be made to that parameter. However I can't find any definitive opinions on this.

In other words if I change my ProcessRecord above to

protected override void ProcessRecord()
{
    SomeCustomObject.ChangeSomething();
    WriteObject(SomeCustomObject);
}

If I have some PowerShell calls:

$SCO = Get-Something
$NewSCO = $SCO | Import-Something

$NewSCO AND $SCO BOTH would have been modified to the same state which seems bad, i.e. we'd always want the items upstream in the pipeline to retain their state so to speak so if later on we want to go back it always retains its original values when it was previously down stream of the Cmdlet that created it.

So instead (Assuming SomeCustomClass has a Copy Constructor) this should be the better design pattern.

protected override void ProcessRecord()
{
    var NewSomeCustomObject = new SomeCustomClass(SomeCustomObject);
    NewSomeCustomObject.ChangeSomething();
    WriteObject(NewSomeCustomObject);
} 

Am I completely off here?

Would there ever be a GOOD reason ESPECIALLY in the pipeline to modify a parameter object upstream of the current Cmdlet?

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

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

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

example of storing the collection

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

let uri: string = 'connection_string';

export let db: Db;

export let usrCollection: Collection;

export let bookCollection: Collection;

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

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

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

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

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

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

Java interface function with extra parameter

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

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

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

public interface Animal{
    public void shout();
}

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

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

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

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

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

Thanks

Entity framework update with business model

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

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

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

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

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

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

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

        }
    }

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

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

mercredi 25 mai 2016

Best design pattern for switching between hardware interfaces

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

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

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

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

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

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

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


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

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

 protected:
    int _commAddress;
    int _statusPort;        

};


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

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

protected:
    int _baudRate;
    int _numChannels;

};


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


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


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


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


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

    ~CameraSystem() { 
        delete _frameGrabber;
    }

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

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

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

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

private:
    FrameGrabber* _frameGrabber;

};


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

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


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

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

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

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

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

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

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

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

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

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

Refactoring a large class into smaller classes

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

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

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

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

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

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

Any input would be much appreciated.

Javascript Facade method grouping

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

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

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

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

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

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

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

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

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