samedi 31 décembre 2016

Using context without any static reference

I am trying to access application resources, (string resources to be specific) from a Singleton class. Being Singleton, this class cannot hold any reference to Context objects (to prevent memory leak). While I was looking for other implementations on the net, I came across this two implementation:

  1. Create a static context in Application class and use it across the app.
  2. Pass context as a parameter to the method that requires it.

I don't want to use the fist one as it also uses a static reference to Context object. I understand that it's ok to have it statically in the Application class of android, but still it looks like a hack.

The second implementation is useless since i don't have any instance of context which I can pass to the someOtherMethod of the singleton.

So I came up with following implementation where I make my Singleton abstract to override its context requiring methods (for ex. getString(int resId) in the code below) when I initialize the singleton instance.

I am curious to know if this can lead to any memory leaks now?

Where am I confused with this approach:

--> The reference to context in the Overridden getString is final. I am not sure if that can cause a memory leak or not.

    public abstract class SingletonClass{

    .
    .
    .

    private static SingletonClass sInstance;

    private SingletonClass(Context paramContext) {
        // constructor code
    }

    public static SingletonClass getInstance(final Context context) {
        if (sInstance == null) {
            sInstance = new SingletonClass(context){
                @Override
                public String getString(int resId) {
                    return context.getString(resId);
                }
            };
        }
        return sInstance;
    }

    public abstract String getString(int resId);

    .
    .
    .

    private void someOtherMethod(){
        //uses above getString()
    }

    }

C++ Repeated do-if-do pattern

I currently have code of the following form:

Do1(A);
if (B != null) Do1(B);

Do2(A, true);
if (B != null) Do2(B, true);

Do3(A);
if (B != null) Do3(B);

So several times, I execute something for object A, and if B is specified, I also do it for B. This means my entire code is duplicated and I would like to change that but I can't come up with a good way to improve this pattern.

The only idea I had so far was something like

auto doBoth = [&A,&B](function<void(const T&)> f) {
  f(A);
  if (B != null) f(B);
};

doBoth(&Do1);
auto do2_bind = [](const T& obj) {Do2(obj, true);};
doBoth(do2_bind);
doBoth(&Do3);

but I feel like that would greatly reduce readability and make it harder for someone to understand my code, as there is this quite abstract lambda function and a lot of lambdas in general.

Javascript Modules and Design Patterns

I have some questions about the way you can create modules in JS. This is the syntax I found:

var Westeros;
    (function (Westeros) {
        (function (Structures) {
            var Castle = (function () {
                function Castle(name) {
                    this.name = name;
                }
                Castle .prototype.build = function() {
                    console.log("Castle " + this.name)
                };
                return Castle;
            })();
            Structures.Castle = Castle;
        })(Westeros.Structures || (Westeros.Structures = {}) );
        var Structures = Westeros.Structures;
    })(Westeros || (Westeros = {}) );

    var winterfell = new Westeros.Structures.Castle("Winterfell");
    winterfell.build();

I took this code form Mastering Javascript Design Patterns. However I've tried to find an answer why you need this line: var Structures = Westeros.Structures. If you omit this line the code works as expected. Is there any explanation fro this? Maybe to "reveal" the class?

Thx!

Why, the default context in a function that hooked to an object is not itself

While going through Javascript basics, I learnt that this will always be the object which is before the period operator, but

          var ob = {
              x:"",
              setx: function(){
                x = "got u"
                // in this function this is nothing but ob
              }

          }  
         ob.setx();
         console.log(ob.x); // this is giving me still ""
         console.log(x); // getting here as 'got u'

this in setx should have context of object ob, but why it's accessing the global space instead of accessing it's own x.

If I use setx as shown below it works

               setx : function(){
                 this.x = "got u"
               }

Why we have to use this keyword, even though 'getx' context is bind to the ob Object

Am I missing any basics?

Is there any design pattern where we can share data(should be private to the parent) between child functions? Such that we can reuse the child functions as we go.

best design for retrieving os dependent beans

I'm developing a module to configure network interfaces (changing ip and hostname). Because the operations are OS dependent, there are os dependent beans for this purpose (like NetworkConfigLinuxImpl) and a factory which based on the OS creates the proper bean.These beans should execute some Commands on operating system with a processDao which (again) has implementation for every Operating System ( like processDaoLinuxIml) and again a factory to create the proper dao (which would be called in NetworkConfig Bean that already the OS type been evaluated to instantiate that). This does not seem to be a good design and has redundancy: Two factories (ProcessDaoFactory, NetworkConfigFactory) are creating os dependent beans based on a same logic. Any better idea?

Does U-SQL support extracting files based on date of creation in ADLS

We know U-SQL supports directory and filename pattern matching while extracting the files. What I wanted to know does it support pattern matching based on date of creation of the file in ADLS (without implementing custom extractors).

Say a folder contains files created across months (filenames don't have date as part of the filename), is there a way to pull only files of a particular month.

Thanks

vendredi 30 décembre 2016

Dropwizard abstract resource design

I think this is a more generic java question, but I'll explain what I'm trying to do and hopefully someone can point me the right way;

I'm trying to create a generic abstract class that all my resources can extend from.

The abstract class has basic CRUD implementations for the standard stuff

@Produces("application/vnd.api+json")
@Consumes("application/vnd.api+json")
public abstract class AbstractResource {

    static final Logger LOGGER = LoggerFactory.getLogger(AbstractResource.class);

    AbstractRepository repository;

    AbstractResource(AbstractRepository repository) {
        this.repository = repository;
    }

    @GET
    public Response getAll(@Auth User user, @QueryParam("query") String query) {
        String result = query != null ? repository.getByQuery(query) : repository.getAll();
        return Response.status(Response.Status.OK).entity(result).build();
    }

    @GET
    @Path("/{id}")
    public Response getById(@Auth User user, @PathParam("id") String id) {
        String result = repository.getById(id);
        return Response.status(Response.Status.OK).entity(result).build();
    }

    @POST
    public Response save(@Auth User user, String payload) {
        String result = repository.save(payload);
        return Response.status(Response.Status.OK).entity(result).build();
    }

    @PATCH
    @Path("/{id}")
    public Response update(@Auth User user, @PathParam("id") String id, String payload) {
        String result = repository.update(payload);
        return Response.status(Response.Status.OK).entity(result).build();
    }

    @DELETE
    @Path("/{id}")
    public Response delete(@Auth User user, @PathParam("id") String id) {
        repository.delete(id);
        return Response.status(Response.Status.NO_CONTENT).build();
    }

}

I can use this without a problem simply doing

@Path("/movies")
public class MovieResource extends AbstractResource {
    public MovieResource(MovieRepository repository) {
        super(repository);
    }
}

and I can now access all the methods and override as required.

Where I run into problems is when I need to overload a method. Take the first getAll method from the abstract class as example, I want to change the parameters in only the Movie.class

@Path("/movies")
public class MovieResource extends AbstractResource {

    public MovieResource(MovieRepository repository) {
        super(repository);
    }

    @GET
    public Response getAll(@Auth User user, @QueryParam("query") String query, @QueryParam("limit") String limit, @QueryParam("page") String page) {
        String result = repository.getPaginated(limit, page);
        return Response.status(Response.Status.OK).entity(result).build();
    }

}

So the getAll method has a different set of parameters in just the Movie.class. This causes Jersey to blow up with

[[FATAL] A resource model has ambiguous (sub-)resource method for HTTP method GET and input mime-types as defined by"@Consumes" and "@Produces" annotations at Java methods public javax.ws.rs.core.Response space.cuttlefish.domain.resources.MovieResource.getAll(space.cuttlefish.domain.model.User,java.lang.String,java.lang.String,java.lang.String) and public javax.ws.rs.core.Response space.cuttlefish.domain.resources.AbstractResource.getAll(space.cuttlefish.domain.model.User,java.lang.String) at matching regular expression /movies. These two methods produces and consumes exactly the same mime-types and therefore their invocation as a resource methods will always fail.; source='org.glassfish.jersey.server.model.RuntimeResource@6a1ef65c']

Because the original getAll method of the abstract already has the @GET annotation.

So, how do I go about solving this?

Do I remove all the annotations from the abstract class, and then have to override and re-add the annotations in each resource? That just seems messy and prone to error... There must be a better solution here?

Is there something blindingly obvious I've just overlooked?

Would love some help!

Change variable type in Java code

I need to change a type of ID variable (represents ID of the database entry) from int to String because of the move from SQL database to NoSQL and the id is now a UUID represented as a String. In IntelliJ I can do "Type Migration" - it's pretty good, but it does not obviously fix all the issues and uses of that variable (there is int to String conversions, things like that). It's a lot of changes that are very error prone.

Is there a design pattern or a design technique that might be helpful in this situation besides going and changing all affected code by hand? I thought about converting UUID into a number, but it's 128 bits and won't fit into any primitive in Java, so I'd still need to change the type in the end. Maybe there is a mapping of some sort I can do or an adapter?

A bit of background: it's a desktop application that receives JSON messages from the API. The id of an entry used to be an int, but we are changing the API and now it's a String. I was working on updating the API controller part of the desktop application as I ran into this problem.

Here is the JSON: this output is produced by the normalizr node module from RethinkDB.

{
 "entities":{  
      "contacts":{  
         "8df9e9fb-df15-4070-b8fe-a6255526034d":{  
            "firstName":"<redacted>",
            "id":"8df9e9fb-df15-4070-b8fe-a6255526034d",
            "lastName":"<redacted>",
            "phoneNumber":"<redacted>"
         },
         "434d9b5f-c845-45f3-8c2a-65a0d5851410":{  
            "firstName":"<redacted>",
            "id":"434d9b5f-c845-45f3-8c2a-65a0d5851410",
            "lastName":"<redacted>",
            "phoneNumber":"<redacted>"
         },

      }
}

Dependency Injection with database models

I have been using a ORM/ODM (morphia) for managing my models, but I'm running into an issue:

The constructor of a model is only called upon creation of the object (new MyObject(dep1, dep2)), and is not called upon being loaded from db (db.get(id)).

How does one inject non-serializable dependencies into an ORM-managed object?

I've been injecting dependencies directly into any methods that require it ie.

public void doSomething(UserDAO userDAO) { ... }

But this quickly leads to ugly code. Is there a better way?

How to avoid passing a context down a bunch of method calls?

suppose I have a problem that, intuitively, is best solved using recursion.

I'm also trying to use dependency injection to make code testeable:

class Foo {

    Bar bar;

    Foo(Bar bar) {
        this.bar = bar;
    }

    ResultType doFoo() {
        ...stuff...
        bar.doBar();
    }

}

class Bar {

    Baz baz;

    Bar(Baz baz) {
        this.baz = baz;
    }

    ResultType doBar() {
        ...stuff...
        baz.doBaz();
    }
}

class Baz {

    Foo foo;

    Baz(Foo foo) {
        this.foo;
    }

    ResultType doBaz() {
        if (foo is needed) {
            foo.doFoo(smaller problem)
        } else {
            ...stuf...
        }
    }
}

Now, if Baz wan't dependant on Foo, you could just do something like:

Foo foo = new Foo(new Bar(new Baz()));

Baz can take any Foo, so it is no problem if it just gets the one at the top, thus forming a loop. (The JVM can take care of loops IIRC). Only Baz can determine if it needs Foo.

What is the cleanest way to get a Foo into Baz in a way that is testeable?

Is adding a Foo parameter to doBaz() my only option? (Implying that Foo needs to pass "this" to doBar, which then passes it to doBaz, etc... or is there a better way?)

How to prevent inheritance from breaking all dependencies in OOP manner without instanceof or typecasting?

We are billing all seats in an airplane. Initially we had a discount per seat. Assume we had a class Discount, and a seat-billing and audit code depended on it.

class Discount {

    private int discountId; // unique key stored in database

    public int getDiscountId() {
        return discountId;
    }

    public List<Seat> getListOfSeatsWithDiscount() {

    }

    public int getDiscountPercentPerSeat() { return 10; }

}

class SeatBill {
    public void billPerSeat() {
        for (each seat object) {
            // fetch discountObject from database.
            Discount d;
            // get list of seats with discounts, and for each of such seats
            seatObject.totalCost = seatObject.totalCost * (100 - d.getDiscountPercentPerSeat())/100;
        }
    }
}

Then we have an audit class which cares about discounted seats.

class Audit {

    public void audit(Discount id) {
        // fetch discount object from database given discount id.
        for (seat in d.getListOfSeatsWithDiscount()) {
            // log all the seats.
        }
    }
}

Now airplane management decides to add another discount -> monthly discount for holiday season. Thus we created an abstract class Discount and created DiscountPerSeat and DiscountPerMonth.

abstract class Discount {
    private int discountId; // unique key stored in database

    public int getDiscountId() {
        return discountId;
    }
}

class DiscountPerSeat extends Discount {


    public List<Seat> getListOfSeatsWithDiscount() {

    }

    // returns 10% discount on each seat reserved.
    public int getDiscountPercentPerSeat() { return 10; }

}

class DiscountPerMonth extends Discount {

    public boolean checkIfMonthIsValid(int month) {
        return month == 12;
    }

    // returns 10% discount on monthly bill
    public int getDiscountPercentPerMonth() { return 10; } 
}

The monthly bill code will now change.

class MonthlyBill {

    public int monthlyBillPerPersonOrCompany(int id) {
        int totalCostPerEntity = gettotalCost(id);
        // fetch discount object from database
        // apply discount if 'current month' is december'
        totalCostPerEntity = totalCostPerEntity * (100 - (disCountPerMonth.getDiscountPercentPerMonth()))/100
    }
}

Now my question is:

  1. Audit class is broken because getListOfSeatsWithDiscount is moved into its subclasss of abstract method discount. How to fix it without typecaseting/instanceof ?

  2. SeatBill class is broken, since abstract class Discount does not support getDiscountPercentPerSeat. How to fix this without typecasting / instanceof ?

  3. MonthlyBill will fetch discount object from database. Once again how to resolve this issue in an OOP way without relying on instance of ?

Basically a whole lot of dependencies are broken in code base because code relies on specific methods of subclasses such as getListOfSeats or getValidMonth etc which cannot be abstracted to the base class.

Please let me know a common solution / design pattern to such refactoring.

Create levels of a game containing many elements in javafx

I've got a Pane in which i would put a lot of Objects like Dirt,Blocks containing ImageView..I've thought about creating an ArrayList containing some of these elements and placing them randomly/or not with a loop. But I think something more efficient could do this. Have you got any idea ? (Maybe the use of a design pattern could be interesting ?) Thanks for the future help !

What are the drawbacks of combining Singleton pattern with the Facade pattern?

I am developing an android library, the structure of this library is such that there is a main class(called Myservice) that makes use of a couple of other classes to expose certain functionality to developers. As I understand it this is the Facade pattern. Myservice class looks like this

public class Myservice
{
    private RequestManager requestManager;
    private DBManager dbManager;
    private SecurityManager securityManager;

public Myservice(Context context)
{
    requestManager = new RequestManager();
    dbManager = new DBManager(context);
    securityManager = new SecurityManager();
}

public void initializeSecurity(SecurityConfig securityConfig)
{ //init security}

public Service deliverService(String param)
{
    ....
}   

}

Now, I want the developer that consumes this Myservice class to be able to create only one instance of the class only. This can be achieved using the singleton pattern However, I have read that using the singleton pattern can cause problems down the road with testing and other issues and also there is the issue of instantiating a singleton with arguments. I want to know if there is a better way of achieving the singleton effect or if I should really be worried about the issues that come with singletons in this scenario.

Design a object oriented extensive toy application

I have to design a toy application which can which can perform two task (for now but can change later): 1. dance 2. sing and it can dance and sing together also. The toy runs on cell which is rechargeable (again for now : the changing aspect ) and the cell remaining charging percent has to be tracked. It should reflect x% cell left during toy performing actions.

Toy can dance for 5 minute (for now) for full charge. Toy can sing for 10 minute (for now) for full charge cell.

How to design this toy (in terms of interface and classes etc.)so that it should be extensible for future enhancement? It must follow SOLID principle. Which design pattern will be suitable for this toy application? Please provide some idea on this.

How to get rid of instanceof check when using inheritance?

Assume we have a class Animal, with subclasses as cat, eagle

Now I have a method:

public void process(Animal animal) {

   if (animal instanceof Cat) {
     if (!animal.meow()) {
        throw exception("cat does not meow");
     } else {
      animal.feedFish();
     }
   }

   if (animal instanceof eagle) {
      if (!animal.fly()) {
         throw exception("eagle does not fly");
      } else {
        animal.checkMaxFlightAltitude();
      }
   }
}

Here cat has 2 methods meow and feedfish which are completely different than eagle's methods fly and checkmaxflight

Most design patterns revolve around assumptions that subclasses have a common method like Shape draw() inherited by circle draw and square draw

  1. Is there some way to do validations on subclasses, such as cat and eagle without instanceof check ?

  2. Any good design pattern ( assuming subclasses dont share a method in base class ? )

Design pattern for microservice's client

I am using spring-cloud to build client of microservice that would call a specific service depending on the params I will receive in my rest controller method.

I am using Java switch instruction like that :

    switch(param)
      case param1:
                 call service1;
      case param2:
                 call service2;

etc...

I would like to know if there is a specific design pattern that will help me to code this functionnality more sweety.

Thanks.

(sorry for my bad english)

jeudi 29 décembre 2016

Best design to deal with subclasses of a database?

I have a class called a Plane.

class Plane {
   private int _planeId;      

   public int getModel() { }

   public int getNumberOfPassengers() {}
}

And I another class called PlaneService which depends on plane and adds some logic to it,

class PlaneService  {
   private Plane _plane;

   public PlaneService(Plane _plane) {
        this._plane = _plane;
   }

   public void validdatePlane(int planeId) {
       fetch plane from planeId from db.
       if ( plane.getNumberOfPassengers() is in range of {100 to 300} )
          plane is valid.
   }
}

But now a new requirement comes in: plane must be extended to support fighter jets. So new design looks like this:

   class Plane {
       private int _planeId;      

       public int getModel() { }
    }

    class PassengerPlane extends Plane {
       public int getNumberOfPassengers() {}
    }

    class FigherJet extends Plane {
      public boolean isCommissioned() {} 
   }

My question is how can I best design 'PlaneSvc'in OOP way ? Is there a good design pattern ?

Currently, my code looks like this:

class PlaneService  {
       private Plane _plane;

       public PlaneService(Plane _plane) {
            this._plane = _plane;
       }

       public void validdatePlane(int planeId) {
           fetch CommercialPlane from planeId from db.
           if (commericialPlaneObject != null) {
              if ( plane.getNumberOfPassengers() is in range of {100 to 300} )
                 plane is valid.
           } 
           fetch FighterPlaneObject from planeId from db.
            if (FighterPlaneObject != null) {
                if (fighterplane.isCommissioned()) {
                   return validPlane;
                } 
            }
       }
    }

I am sure there is some design pattern to deal with such a case. I need to understand a cleaner approach to if-else here.

Using Java Generics for Code Reuse in Interface Inheritance

I am trying to create a framework for state machines using object oriented techniques in Java. Every System can have one and only one State active at a time.

public interface State {}
public interface System { 
    State currentState();
}

Let's say I want to add a new type of system that should be updated regularly to check and change its state, called an UpdateableSystem. It can only have States that are of the type UpdateableState.

public interface UpdateableState extends State {
    /**
     * Check to see if the system should switch to a different state.
     * @returns new state of the system
     */
    UpdateableState update();
}

public interface UpdateableSystem extends System {
    @Override
    UpdateableState currentState();
    /** 
     * Runs update method of the current state, or otherwise updates the system.
     * @returns the current state of the system after the update
     */
    UpdateableState update();
}

I overrode the currentState method to only return only UpdateableState, not State, because the UpdateableSystem can only have states that are of the type UpdateableState, and the client using the UpdateableSystem will expect UpdateableStates.

To avoid overriding many methods many times as more subclasses are created, generics seem to be the solution. Here are the updated interfaces.

public interface System<SystemState extends State> {
    SystemState currentState();
}

and

public interface UpdateableState<SystemState extends UpdateableState<SystemState>> extends State {
    SystemState update();
}

public interface UpdateableSystem<SystemState extends UpdateableState<SystemState>> extends System<SystemState> {
    SystemState update();
}

Now, lets say I wanted to add another type, interface Context, that systems and states need to be aware of. Context should be able to be subtyped, and clients and ContextState subtypes should be able to use the full interface of that Context subtype.

public interface Context {}
public interface ContextState<SystemContext extends Context, SystemState extends ContextState<SystemContext, SystemState>> extends UpdateableState<SystemState> {
    SystemState updateWithContext(SystemContext context);
}
public interface ContextSystem<SystemContext extends Context, SystemState extends ContextState<SystemContext, SystemState>> extends UpdateableSystem<SystemState> {
    // Some methods here that require SystemContext type
}

Suddenly, those parameterized types turned into a whole ton of boilerplate, which is confusing and hard to maintain.

This would be an example with concrete implementations:

class CarContext implements Context {...}
interface CarState extends ContextState<CarContext, CarState> {...}
    class CarDrivingState implements CarState {}
    class CarIdleState implements CarState {}
class Car implements ContextSystem<CarContext, CarState> {...}

Each concrete CarState would be able to access the additional methods provided by the CarContext interface, because the method signatures inherited from ContextState would be parameterized by the CarContext type. So no explicit casting would be required on the context parameter of updateWithContext.

Ultimately, the issue is too much boilerplate when adding an additional type to parameterize, and I do not know of a design alternative that would achieve code reuse through inheritance, and also maintain a strong type system, avoiding explicit casting when possible. Any suggestions to improve this design?

What books should every programmer read [on hold]

Can you guys please suggest some good books?

Topics I want to read about:

  • OOP
  • Modern Javascript, ES6, SPA...
  • Enterprise Application Architecture
  • Design Patterns
  • Testing
  • Refactoring

Thank you!

Replacing capitalized and non-capitalized string with preg_replace

I'm working on a project where I have a string with content e.g. $content, and an array with words (with no capitals) e.g. $rewrites.

What I want to achieve, example case:

$content contains a string with the following text: 'Apples is the plural of apple, apples are delicious'.

$rewrites contains an array with the following data: 'apple', 'blueberry'.

Now I want to create a function that replaces all apple for something else, e.g. raspberry. But, in the string, there is Apples, which won't be replaced using preg_replace. Apples should be replaced with Raspberry (mention the capital R).

I tried different methods, and patterns but it won't work.

Currently I have the following code

foreach($rewrites as $rewrite){
      if(sp_match_string($rewrite->name, $content) && !in_array($rewrite->name, $spins) && $rewrite->name != $key){
        /* Replace the found parameter in the text */
        $content = str_replace($rewrite->name, $key, $content);

        /* Register the spin */
        $spins[] = $key;
      }
    }

function sp_match_string($needle, $haystack) {

 if (preg_match("/\b$needle\b/i", $haystack)) {
   return true;
 }
return false;

}

Functionality inside abstract decorator class instead of decorators

I'm currently reading the book Head First Design Patterns and in the Decorator chapter there is the following example:

Example diagram

In the book the CondimentDecorator class is described as an abstract decorator. Here is the code example:

public abstract class CondimentDecorator extends Beverage {
    public abstract String getDescription();
}

So basically inside is only an abstract method which forces all subclasses to override the getDescription() method from Beverage class.

And here is the code example of a Mocha class as the decorator.

public class Mocha extends CondimentDecorator {
    Beverage beverage;

    public Mocha(Beverage beverage) {
        this.beverage = beverage;
    }

    public String getDescription() {
        return beverage.getDescription() + ", Mocha";
    }

    public double cost() {
        return .20 + beverage.cost();
    }
}

The other decorators (Whip class, Soy class...) have exactly the same code, except for the hardcoded cost number (.20) and name (", Mocha").

We then use this decorator pattern by passing the previous object into the new decorator.

Beverage beverage = new DarkRoast();
beverage = new Mocha(beverage);
beverage = new Mocha(beverage);
beverage = new Whip(beverage);

My question is, why not simply move the duplicated functionality from decorators to abstract decorator? Here is how I refactored the example.

Abstract decorator:

public abstract class CondimentDecorator extends Beverage {
    private Beverage beverage;

    protected CondimentDecorator(Beverage previousBeverage) {
        this.beverage = previousBeverage;
    }

    @Override
    public String getDescription() {
        return beverage.getDescription() + ", " + getAdditionName();
    }

    @Override
    public double cost() {
        return beverage.cost() + getAdditionCost();
    }

    public abstract String getAdditionName();
    public abstract double getAdditionCost();
}

Decorator code:

public class Mocha extends CondimentDecorator {
    public Mocha(Beverage beverage) {
        super(beverage);
    }

    @Override
    public String getAdditionName() {
        return "Mocha";
    }

    @Override
    public double getAdditionCost() {
        return 0.20;
    }
}

Now for every new decorator I create I'm forced to provide the previous beverage object via constructor for the superclass constructor and I need to override methods which only return the unique values for the specific decorator.

Is this code OK? Or does it completely change the point of Decorator pattern if I have functionality in the abstract decorator?

Living Style Guide / Pattern Library for HTML, CSS and JavaScript Logic

Are there Pattern-Library / Living-Style-Guide -Tools that allow the integration of JavaScript widgets / plugins? Does that even make sense? I want my actual plugins to be integrated and stored inside the Patternlibrary and have the actual Website access it.

decorator vs interpreter pattern

I recently learned interpreter pattern. I found some similarities betweeen decorator and interpreter. They are in same group and have similar structure.

I look in this case: one nonTerminal behaviour and one terminal behaviour in interpreter. It seems very similar to decorator. There can be nonTerminal behaviour calling same nonTerminal beahviour and then calling terminal behaviour. This seems very similar to apply decorator over same decorator over objet.

Is decorator a specail case of interpreter?

Refactoring a function that returns different data types

I'm not sure what the most efficient way of doing this would be but I believe it's good practice to have a function that returns one data type, whether it be a boolean or string but in some situations I can see how difficult it would be to implement such a strict rule, for example the code below will return an object if a database record is found otherwise it will return false.

public function get()
{
   $record = $this->db->query('select id, first_name, last_name from users where id = :id', ['id' => 1]);

   if ($record) {
      return new User($record['id'], $record['first_name'], $record['last_name']);
   } else {
      return false;
   }
}

My question is what is the recommended best practice in this situation?

mercredi 28 décembre 2016

Extend inherited object structure from library

I created a base library/package containing the class Type and its childs ObjectType and PrimitiveType.

In addition to that, I have 3 different use cases for this type classes that logically belongs to other packages.

  1. Render a data type into a generated class (parameter or return type), e.g. toCode() => ?int = 3
  2. Render a data type into the documentation, e.g. toDoc() => int|null
  3. Convert a data type of the programming language to a database type, e.g. toDatabaseType() => TINYINT(1)

Of course I want to use the base package without dependencies to the "generator" or "ORM" package.

I also would like to use any combination of all 3 packages.

How would you implement this?

Duplicating the object hierarchy in every package will prevent a mixed usage.

A Decorator

Mixins etc. and AOP are not supported. And extending the class at runtime will lose any type safety.

I'm getting closer to the point thinking that a switch per package is the cleaner approach assuming that there will be "no" new Types in the future.

Builder Pattern with only one class

I'm learning the Builder Pattern. I have a question, Why don't using a class (ex: MyCoffe)instead of 2 class (ex: MyCoffe, BuilderClass). Thanks you for reading.

package Creational.Builder;

public class MyCoffe {

        private String name;
        private int id;

        public MyCoffe(){

        }

        public MyCoffe setName(String newName){
            this.name  = newName;
            return this;
        }

        public MyCoffe setId(int newId){
            this.id = newId;
            return this;
        }

        public MyCoffe build(){
            return this;
        }

        public String toString(){
            return name + "/" + id;
        }

        public static void main(String[] args){
            MyCoffe myCoffe = new MyCoffe().setName("HelloWorld").setId(9999);  
            System.out.println(myCoffe);

            System.out.println("Thanks for help!");
        }
}

How to associate data to the elements in a collection without modifying the elements?

usually, when I'm doing OpenGL programming, I have a Mesh class like this:

public class Mesh {

    // General 3D stuff
    List<Vector3f> vertices = new ArrayList<>();
    List<Vector3f> normals = new ArrayList<>();
    List<Vector2f> texCoords = new ArrayList<>();

    // OpenGL-specific stuff
    protected int vertices;
    protected boolean dirty;
    protected int vertexArrayID = -1;
    protected int vertexBufferID = -1;

    ...

}

However, the application I'm working on right now is much more general, and I'd like to keep the OpenGL-specific stuff separate from the OpenGL stuff. For example, someone might want to store the Mesh as an STL file and have it 3D-printed, or send it off to a Raytrace renderer to make it look nice. In that case, the OpenGL-specific data is useless.

In other words, this implementation of the Mesh class violates the single responsibility principle.

Now, one solution I can think of is the following:

public class Mesh {

    // General 3D stuff
    List<Vector3f> vertices = new ArrayList<>();
    List<Vector3f> normals = new ArrayList<>();
    List<Vector2f> texCoords = new ArrayList<>();
}

public class GlMesh extends Mesh implements GlDrawable {

    // OpenGL-specific stuff
    protected int vertices;
    protected boolean dirty;
    protected int vertexArrayID = -1;
    protected int vertexBufferID = -1;
}

However, now there are still OpenGL-specific objects in the datastructure that is output from the algorithm that generates it. The Mesh generator needs to know it should create a GlMesh rather than a Mesh, and thus knows about the OpenGL rendering module, something I'd really rather avoid.

Now, we can do something like this:

public class Mesh {

    // General 3D stuff
    List<Vector3f> vertices = new ArrayList<>();
    List<Vector3f> normals = new ArrayList<>();
    List<Vector2f> texCoords = new ArrayList<>();
}

public class GlMesh {

    // OpenGL-specific stuff
    protected int vertices;
    protected boolean dirty;
    protected int vertexArrayID = -1;
    protected int vertexBufferID = -1;
}

Map<Mesh, GlMesh> meshToGlMesh = (whatever)

However, now the rendering system has to do extensive bookkeeping to map the Mesh to the corresponding GlMesh, which is just asking for trouble.

Is there a good way to solve this that I'm missing?

Android MVP architecture - communication with repository and view

I'm learning Android MVP architecture given here. Based on the example I created my own simple app that just displays list with recyclerview with pull to refresh functionality.

When list is pulled I want first to clear the recyclerview and then reload the data again from the repository (with fake latency delay). But, when I clear the data inside RecyclerViewAdpater, all data inside repository are also being cleared and there is nothing to show. I just can't understand the reason.

Here's my activity that creates both Presenter and View (that is Fragment):

    protected void onCreate(Bundle savedInstanceState) {

            mainFragment = MainFragment.newInstance();

            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.contentFrame, mainFragment);
            transaction.commit();

            new MainPresenter(new MainDataRepository(), mainFragment);
    }

Here's my Fragment (MainFragment) - ATTENTION: updateList(null) - This is where it clears all data, including inside Repository:

    public MainFragment() {
    }

    public static MainFragment newInstance() {
        return new MainFragment();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //....

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                recyclerAdapter.updateList(null); // **This is where it clears all data, including inside Repository**

                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mPresenter.loadList(); // to reload the list
                    }
                }, 1500);
            }
        });

        //...
    }

    @Override
    public void onResume() {
        super.onResume();

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mPresenter.loadList();
            }
        }, 3000);
    }

    @Override
    public void setPresenter(MainContractor.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showList(List<String> mainDataList) {
        if(recyclerAdapter == null) {
            recyclerAdapter = new RecyclerAdapter(mainDataList);
            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            recyclerView.setAdapter(recyclerAdapter);
        }else{
            recyclerAdapter.updateList(mainDataList);
        }
    }

Here's my presenter (MainPresenter):

    public MainPresenter(MainDataRepository mainDataRepository, MainContractor.View view){
        mMainDataRepository = mainDataRepository;
        mMainContractorView = view;

        view.setPresenter(this);
    }

    @Override
    public void loadList() {
        ArrayList<String> strings = mMainDataRepository.getList();

        mMainContractorView.showList(strings);
    }

Here's my repository (MainDataRepository):

private ArrayList<String> repositoryList;

    public MainDataRepository() {
        createList();
    }

    private void createList() {
        if(repositoryList == null){
            repositoryList = new ArrayList<>();
        }

        for (int i = 1; i <= 10; i++) {
            repositoryList.add("Item " + i);
        }
    }

    public ArrayList<String> getList(){
        return repositoryList;
    }

And the last one, This is how I am updating recyclerview inside RecyclerAdapter:

public void updateList(List<String> newStrings){
        if(newStrings != null){
            stringsList = newStrings;
        }else{
            stringsList.clear();
        }
        notifyDataSetChanged();
    }

Why updateList mehod inside RecyclerAdapter also clears the data inside repository that is ArrayList<String> repositoryList?

finding the number of occurrence of a pattern within a cell in matlab?

i have a cell like this:

x = {'3D'
    'B4'
    'EF'
    'D8'
    'E7'
    '6C'
    '33'
    '37'} 

let's assume that the cell is 1000x1. i want to find the number of occurrence of pattern = [30;30;64;63] within this cell but as the order shown. in the other word it's first check x{1,1},x{2,1},x{3,1},x{4,1} then check x{2,1},x{3,1},x{4,1},x{5,1} and like this till the end of the cell and return the number of occurrence of it.

Here is my code but it didn't work!

while (size (pattern)< size(x))
    count = 0;
    for i=1:size(x)-length(pattern)+1
        if size(abs(x(i:i+size(pattern)-1)-x))==0
            count = count+1;
        end
    end
end

Thanks!

How does the strategy pattern differ from polymorphism?

In computer programming, the strategy pattern (also known as the policy pattern) is a behavioural software design pattern that enables an algorithm's behavior to be selected at runtime.

The strategy pattern...

  • Defines a family of algorithms.
  • Encapsulates each algorithm.
  • Makes the algorithms interchangeable within that family.

(source: Wikipedia)

In my case, I want to be able to inject different hashing algorithms into a service. C# has several hashing algorithms that derive from HashAlgorithm, such as:

  • MD5
  • SHA256Managed
  • RIPEMD160Managed

Given this hierarchy, this looks like the strategy pattern, but had I never heard of the strategy pattern, I might just say this was a classic example of polymorphism.

Whilst designing the code to solve my particular problem, I designed an interface based on the strategy pattern to inject different hashing algorithms:

public interface IHashStrategy
{
    Hash ComputeHash(byte[] data);
}

Usage

public class HashCreator : IHashCreator
{
    public Hash GetHash(IHashStrategy strategy, byte[] data)
    {
        return strategy.ComputeHash(data);
    }
}

Going back to my previous example, I could equally get rid of the interface altogether and just use HashAlgorithm:

public class HashCreator
{
    public Hash GetHash(HashAlgorithm algorithm, byte[] data)
    {
        return new Hash(algorithm.ComputeHash(data));
    }
}

Question 1: Is the strategy pattern different in any way from polymorphism, or is it because of polymorphism that the strategy pattern exists?

Question 2: Which is considered better practice here; abstract out the functionality I require into an interface (IHashStrategy) or use the base type (HashAlgorithm)?

Difference between using Cake pattern and functions in Scala - why is the Cake pattern useful?

I was wondering about the difference between using functions and Cake pattern for DI in Scala. I came up with the following understanding(s), I would like to know if this understanding is correct.

Let's imagine a dependency graph.

1) If we use functions as building blocks then the graph consists of functions as nodes and parameters as edges.

2) If we use traits as building blocks (as in Cake) then the graph consists of traits as nodes and abstract members as edges.

So what is the purpose of Cake pattern ? Why is 2 better than 1 ? It is course graining. Graph-1 can be simplified by grouping functions into traits and then we have a smaller, more understandable Graph-2.

Does this make sense ? I am trying to understand why the Cake pattern is useful. The grouping/clustering of related concepts is a form of compression and creates understanding (we need to hold less things in our head to get an understanding).

Here is a different comparison (between Cake vs package system):

Cake is similar to grouping related functions into packages but it goes beyond that because using name-spaces (packages/objects) causes dependencies to be hard-wired, Cake is replacing packages/objects with traits and imports with self type annotations/abstract members. The difference between packages and Cake pattern is that the actual implementation of a dependency can change using Cake while it CANNOT change when using packages.

I don't know if these analogies do make sense or not, if not please correct me, if yes, please reassure me. I am still trying to wrap my head around the Cake pattern and how to relate it to concepts that I already understand (functions, packages).

C# call method before override method

Good day, I have a base class with a virtual method that needs to be overridden per implementation, but I would like to call the base method first before overriding. Is there a way to accomplish this without having to actually call the method.

public class Base
{
   public virtual void Method()
   {
      //doing some stuff here 
   }
}

public class Parent : Base
{
  public override void Method()
  {
     base.Method() //need to be called ALWAYS
     //then I do my thing 
  } 
}

I cannot always rely that the base.Method() will be called in the override, so I would like to enforce it somehow. This might be a design pattern of some kind, any approach to accomplish the result will do.

mardi 27 décembre 2016

PHP Framework Design

Short Version: Are there standardized design and build strategies for building PHP web frameworks for creating applications?

Detailed Version: I would like to put together a larger scope web framework, such as developing WordPress or Drupal from the ground up, but I'm concerned about making sure I've brought together all of the needed elements on all of my pages, such as with security. In general, I'm not looking for traditional design patterns, such as factory or MVC, since these are still based on the developer remembering to bring everything together on each page. So are there any kinds of PHP development patterns that would address strategies on stacking your code with includes or recommendations on where to put code in a more modular design? It would be nice to have something similar to the other languages (such as Java and .Net) where you annotate your model to require certain access rights in order to implement the model. But with more of a stateless interaction on the web, I'm not quite feeling in control as I am with traditional compiled desktop apps.

To hit a complexity specifically using an MVC example, I don't want to have a single controller approach with a single URL running the whole web app. I also don't want to have a lot of copy and paste code. I would much rather reuse code but even more so create a standardized include that will work for all of my controllers. So are there specific recommendations for how to stack up my includes so I can employ basic security controls (maybe controller level all or nothing) while also making my general functions available?

Java Pattern with numbers

Hello i need to do the following /* 1234567 123456 12345 1234 123 12 1 */ i need it with a for loop and if statement please. that's the code in stars

for (int i = 0; i <= n; i++) {
        for (int j = n; j >= 0; j--) {
            if (i <= j) {
                System.out.print("*");
            }
        }
        System.out.println("");
    }

Design alternative for objects with mutually exclusive data members

It was tough to summarize the problem in the title; so allow me to clarify the situation here.

I have a class that I'm designing that represents a BER TLV structure. In this specification, the "data" portion of the TLV can contain raw bytes of data OR other nested TLVs. To support both forms, I use the same structure but with two vectors (only one will actually contain something, depending on what we find as we parse the TLV data):

class BerTlv
{
public:

    void Parse(std::vector<std::uint8_t> const& bytes_to_parse);

    // Assume relevant accessors are provided

private:

    // Will be m_data or m_nestedTlvs, but never both
    std::vector<std::uint8_t> m_data;
    std::vector<BerTlv> m_nestedTlvs;
};

From the outside, after this object is fully constructed (all TLV data parsed), the user will need to detect what kind of data they are dealing with. Basically, they'd have to check m_data.empty(), and if so, use m_nestedTlvs. I'm not really happy with this approach; it smells like it lacks a better design.

I thought of some form of a union, although I do not think a real union would be appropriate here since vector data is heap allocated. So I thought of std::variant:

std::vector<std::variant<BerTlv, std::uint8_t>> m_data;

However, I'm worried this negatively impacts the std::uint8_t case since that's literally just byte data. It will now become non-continuous as well. The variant only benefits the nested TLV case and not by much.

Next I considered using the visitor pattern here, but I can't quite visualize what the interface would look like or how this would improve usability in both cases (raw data vs nested TLVs). Is visitor the right solution here?

Nothing I've thought of so far feels right, so I'm hoping for feedback on a better design approach to this problem. The general problem here is having data members that are sometimes unused or are mutually exclusive. It's a problem I run into in other contexts as well, so it would be great to have a general design approach to such a problem.

Note that I have access to C++14 features and below.

How to invoke a class from referenced DLL dynamically in C#

I need your help guys.

I'm planning to create a proxy service API in Visual Studio (C#), where it has a generic handler that receives as a parameter a class name with other params. Let's say:

api.ashx?serviceName=GetClients&param=...

In my solution, I'm planning to have many class libraries, while each of them will represent a service i am going to provide in my API to my clients. I will reference all DLLS of the class libraries (Services that will return JSON) to the main project where the Generic Handler exists. For instance, If my handler received a request with a parameter value "serviceName=GetClients", I'll need to look for the referenced DLL called "GetClients" using reflection. Then i'll call a generic function inside this DLL, which will do some logic, and return a JSON back to the handler.

What kind of design pattern should I use for my problem? also, If you can refer me to websites that explains what i need to do, it'll be great.

THANKS!

c# Entity Framework when should I use an new dbContext?

I was wondering for some time what is the proper way to make a new instance of an dbcontext? I got some problem with it because when I make up change in my database through SQL Server my context doesn't update the data. Let me explain how my website work.

We are doing an appointment website for our customer to take appointment obviously. we will hosting all database on our server. How it work is the application made up 2 connection:

first connection

this connection connect all the time to the same database let's call it master. It'll redirect the user to the good database with the url code in it example: www.example.com/foo the server will check for the code where here is foo So it'll lookup in the table to matchup the code and then take the good database name where it should redirect and it's here that my second connection come's up

Second connection

This one will make the connection to the correct database according to the data the master has return. From here all seems to work well except for the DBContext that actually never update because I don't instantiate it correctly and I don't have an large experience with it. Here's the code i did with my coworker:

using System;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Routing;
using WebRV.Models.Entities;

namespace WebRV.RouteDb
{

    public class DbConnection
    {

        private static DbConnection instance;
        private Cliniciel_WebRV_Entities db;
        private String connectionString;
        private readonly Cliniciel_WebRV_MasterEntities masterDb = new Cliniciel_WebRV_MasterEntities();
        private Int32 idCie;
        private static readonly object myLock = new object();


        private DbConnection() {
            var context = new HttpContextWrapper(System.Web.HttpContext.Current);
            var routeData = RouteTable.Routes.GetRouteData(context);
            // Use RouteData directly:
            String code = routeData.Values["code"].ToString();
            //String  code = Thread.CurrentContext. .RequestContext.RouteData.Values["code"].ToString();
            var response = masterDb.SYS_tbCustDBLocation.Where(p => p.CustDBLocationCode == code).ToList();

            if (response.Count == 1)
            {
                try
                {
                    db = CreateConnection(response.FirstOrDefault());
                    idCie = (db.SYS_vwCie.Where(p => p.ClinicielWebName == code).FirstOrDefault()).IdCie;
                }
                catch (Exception e)
                {
                    throw e;
                }

            }
            else {
                throw new FormatException();
            }
        }

        private Cliniciel_WebRV_Entities CreateConnection(SYS_tbCustDBLocation data)
        {

            connectionString = *****

            db = new Cliniciel_WebRV_Entities();

            db.Database.Connection.ConnectionString = connectionString;

            db.Database.Connection.Open();

            return db;
        }

        private static void CreateInstance() {
            instance = new DbConnection();
        }

        public static DbConnection GetInstance() {
            lock (myLock)
            {
                if (instance == null)
                {
                    CreateInstance();
                }

            }

            return instance;
        }

        public String GetConnectionString()
        {
            return connectionString;
        }

        public Cliniciel_WebRV_Entities GetConnection()
        {
            return db;
        }

        public Int32 GetIdCie()
        {
            //hard code 1 but test
            //return idCie;
            return 1;
        }

    }
}

and here's an example of how I use it:

  //[CompanyCodeFilter]
    public class HomeController : AppointementController 
    {
        //public static Cliniciel_WebRV_Entities entityDB = DbConnection.GetConnection();

        public HomeController()
        {
            base.Refresh();
        }

 public JsonResult GetConsultationDescription(Int32 idService)
        {
            //base.Refresh();
            entityDB.Set<SYS_vwService>().AsNoTracking();
            var motifDescription = entityDB.SYS_vwService.Where(s => s.IDLang == cultureName && s.IdService == idService && s.IdCie == idCie).FirstOrDefault();
            var base64 = Convert.ToBase64String(motifDescription.ServiceImage);
            var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
            var imageDecode = imgSrc;
            if (base64 == "AA==")
            {
                imageDecode = "";
            }
            var result = new { motifDescription, imageDecode };


            return Json(result, JsonRequestBehavior.AllowGet);
        }
  }

Here base.refresh() call this:

using System;
using System.Linq;
using WebRV.Filters;
using WebRV.Localization;
using WebRV.Models.Entities;
using WebRV.RouteDb;

namespace WebRV.Controllers
{
    //[CompanyCodeFilter]
    public class AppointementController : BaseController
    {
        protected Cliniciel_WebRV_Entities entityDB;
        protected Int32 idCie;
        protected String cultureName;

        //public AppointementController() {
        //    Refresh();
        //}

        //Permet de bien vérifier quel DB utilisé, quel idCie et quel cultureName.
        protected void Refresh() {
            entityDB = DbConnection.GetInstance().GetConnection();
            idCie= DbConnection.GetInstance().GetIdCie();
            cultureName = CultureLocalization.GetCulture();
            //cultureName = "en-ca";
        }

    }
}

If someone can help me to instantiate the connection properly it'll be appreciate thank you

What programming patterns or strategy should I use to deal with small inconsistencies in data processing?

In the ruby gem I am writing I have to take in as input certain known query parameters and massage them into a query string and then use that constructed (url) string as a rest endpoint to retrieve that data.

Now there are some weird inconsistencies in inputs coming in and I am forking my code to normalize inputs into a consistent output.

   def build_query(params, endpoint)
      limit      = Hash[limit:      params[:limit]   ||  0]
      skip       = Hash[skip:       params[:skip]    ||  0]
      asc        = Hash[asc:        params[:asc]     || ""]
      desc       = Hash[desc:       params[:desc]    || ""]

      query = [limit, skip, asc, desc].select { |hash| hash.values.none? { |val| val == '' || val == 0 } }
      encoded = query.map{ |q| q.to_query }.join("&")

      references = build_references(params[:include]) || ""

      query_string = references.empty? ? "#{endpoint}#{encoded}" : "#{endpoint}#{references}&#{encoded}"
    end

You will see above that the references piece of the params are not handled the same way as the rest of the parameters. There are more slightly inconsistent edge cases coming soon. And the only way I know how to deal with these is to keep forking my code inside this function. It's going to get messy soon!

So how should I now refactor this code? Where should I go from here to manage this complexity? Should I use collaborating objects (ParamsBuilder or QueryManager) and some kind of polymorphism strategy?

I would like to keep my code simple and functional as much as possible.

Best Pattern to replace an util class

I have a class like an util, It contains all preparing and calling requests (I want easily to manage requests). Ex:

public void reqLogin(String emailAddress, String password) {
    JsonRequestBody parameters = new JsonRequestBody();
    parameters.put(USER_NAME, emailAddress);
    parameters.put(PASSWORD, password);
    mService.login(parameters.createRequestBody());
}
public void reqRegister(LocationWrapper location) {
    JsonRequestBody jsonRequestBody = new JsonRequestBody();
    jsonRequestBody.put(DEVICE_TOKEN, "myToken");
    jsonRequestBody.put(DEVICE_TOKEN_TYPE, "type");
    mService.register(jsonRequestBody.createRequestBody());
}

... 

But problem of this design is that in LoginFragment I can call Register request, and in RegisterFragment I can call Login request. So, is it bad solution to create this util class? Is there a pattern to solve my issue?

lundi 26 décembre 2016

C# Update out parameter in another function

I have class that defines the following methods -

void DoAction1(out object result)
{
    // The action is queued but not executed
}

void DoAction2(out object result)
{
    // The action is queued but not executed
}

void ExecuteAllActions()
{
    //Action 1 and Action 2 are executed in a batch.
}

What would be cleanest wato to update the out variables once the results are fetched from the ExecuteAllActions() method?

Domain Model pattern example

I'm just trying to find some examples of Domain Model pattern and I can't.

From what I found on the Internet Domain Model is just adding some "logic" methods to classes. For example

public class Income {
    private String title;
    private String comment;
    private String date;
    private Double amount;
    private Integer category;

    public ExIn(String title, String comment, Double amount, Integer category, String date) {
        this.title = title;
        this.comment = comment;
        this.date = date;
        this.amount = amount;
        this.category = category;
    }

    public Integer getCategory() {
        return category;
    }

    public void setCategory(Integer category) {
        this.category = category;
    }

    // more getters and setters
    // Domain Model part starts
    public boolean isPositive()
    {
        return amount > 0 ? true : false;
    }
    // more methods like that 
}

Did I understand it correctly? If not, I'd be grateful for a little example.

How to design services to fetch data that are required to be called multiple times?

I have a service that returns a promise.

function GetSuggestedPeersService($http, SITE_CONFIG) {
        var getSuggestedPeersService = this;

        var data;

        getSuggestedPeersService.getSuggestedPeersList = function() {
            var baseUrl = SITE_CONFIG.baseUrl + "fetchSuggestedPeers";
            var response = $http({
                method : 'POST',
                url : baseUrl,
                headers : {
                    'Content-Type' : 'application/x-www-form-urlencoded'
                },
                data : data
            });
            return response;
        }

        getSuggestedPeersService.setSuggestedPeers = function(suggestedPeers) {
            getSuggestedPeersService.suggestedPeers = suggestedPeers;
        }

        getSuggestedPeersService.getSuggestedPeers = function() {
            return getSuggestedPeersService.suggestedPeers;
        }

    }

Now I use the following in the Controller to resolve the promise:

//gets the suggested peers
var promiseSuggestedPeers = GetSuggestedPeersService.getSuggestedPeersList();
promiseSuggestedPeers.then(function (response) {
    peerHealthController.GetSuggPeersShow = response.data;
    GetSuggestedPeersService.setSuggestedPeers(peerHealthController.GetSuggPeersShow);

    return peerHealthController.GetSuggPeersShow;
})
.catch(function (error) {
    console.log("Something went terribly wrong Suggested Peers.");
});

Now my question is call this service multiple times and need to update this on other service calls as well.

What is the best way to write the controller part so as not to repeat the resolve promise every time I call the service?

One fragment with two or more layouts and behaviours

I have one problem:

I need to write fragment with settings for user, but when user is TYPE_USER he has some other behaviour and other layout than when he is TYPE_PREMIUM.

I wrote interface SettingsAction and two implementations:

SettingsActionForNormal and SettingsActionForPremium, but I dont know, is it correctly ?

Common things for both types should be placed in fragment or in based class for SettingsActionForNormal and.. which implements SettingsAction ?

How should be code architecture when there are many types of user and they have different behaviours and layouts in many fragments ?

I cant find a good open source project with thats problem.

dimanche 25 décembre 2016

UnitOfWork pattern for Entity Framework but with direct SQL queries

I'm trying to incorporate the Unit of Work pattern for my ASP.NET MVC project, and it is a bit different than other typical UoW design with Entity Framework.

My database has a highly normalised and pure relational structure in that it is not really EF friendly. Because of this I have created views that are mapped to entities so that I can still have all the EF and LINQ goodness when querying, but I have to use direct sql queries (e.g. Context.Database.ExecuteSqlCommand) when updating the entities.

This poses a challenge to my UoW design. As far as I know a general approach to UoW with EF is to basically call Context.SaveChanges() only when UoW.Commit() is called. This way all the tracked entity changes will be committed as a single transaction to the database at once.

However since I am using Context.Database.ExecuteSqlCommand, whenever I update an entity the transaction will happen immediately, hence losing the whole point of UoW. I'll give an example:

Traditional UoW with EF:

public void CreateOrder()
{
    var customer = new Customer();
    // this only adds the entity to the Context for tracking
    // e.g. Context.Customers.Add(customer);
    UoW.CustomerRepo.Add(customer); 

    // this too only adds the entity to the Context
    var order = new Order();
    UoW.OrderRepo.Add(order);

    // Commit. this internally calls Context.SaveChanges()
    // sending all changes to the db in a single transaction
    // Perhaps also with a TransactionScope.
    UoW.Commit(); 
}

My UoW with EF:

public void CreateOrder()
{
    var customer = new Customer();
    // this inserts a customer to the db immediately
    // e.g. Context.Database.ExecuteSqlCommand(insertSql);
    UoW.CustomerRepo.Add(customer); 

    // This too inserts an order immediately
    var order = new Order();
    UoW.OrderRepo.Add(order);

    // There is no point calling Context.SaveChanges()
    // here as all my changes are already executed with direct sql.
    UoW.Commit(); 
}

Anyone has come across similar issues? Should I just abandon UoW here and simply wrap all my repository actions in a single TransactionScope?

Should I create a JavaScript module for a collection of elements, or just a single element?

I'm using the model pattern with javaScript + Mustache to create a page where a set of subscribers can set their favorite topics (so that they can receive favorite posts from their publishers - this isn't a part of the question for now). Here is my index.html file.

<div id='subscriber-module'>
    <div id='subscriber-template'>
    
    <div class='subscriber'>
        <p></p>
        <input type='text' class='form-control' placeholder='Add Topic'>
        <button class='btn btn-default subscribe'>Subscribe</button>
        <ul>
            
            <li> 
            
        </ul>
    </div>
    
    </div>
</div>

I know the subscriber-template tag is redundant, but I was fiddling around with it so much that it was just better to leave it there because the javaScript code references this.

var Subscribers = (function(){

    var Subscribers = ['Ajay', 'Thor', 'Slick','Sassy','R2'];
    var topics = ['Cars','Halthor','Kites'];

    var notifications = [{
        topic:'Halthor',
        payload:'There was a battle here'
    },{
        topic:'Cars',
        payload:'Fast Pieces of shit'
    }];

    this.$el = $('#subscriber-module')
    this.$ul = $el.find('ul')
    this.$textbox = $el.find('input[type=text]')
    this.$button = $el.find('.subscribe');
    var template = $el.find('#subscriber-template').html();

    //bindEvents
    $el.delegate('.subscribe','click',addTopic)

    _render();

    function _render(){
        data = {
            Subscribers: Subscribers,
            notifications: notifications
        }

        $el.html(Mustache.render(template, data))
    }

    function addSubscriber(value){
        console.log('typeof value in add Subscribers: ' + typeof value)
        Subscribers.push(value);
        _render();
    }

    function reomoveSubscriber(value){
        console.log('typeof value in remove Subscribers: ' + typeof value)
        indx = Subscribers.indexOf(value)
        if(indx != -1) Subscribers.splice(indx, 1)
        _render()
    }

    function addTopic(event){
        topic = $(event.target).siblings('input')[0].value
        topics.push(topic);
        console.log(topics)
    }

    // Haven't worked on this yet
    function removeTopic(value){
        alert(typeof value)
        indx = Subscribers.indexOf(value)
        if(indx != -1) topics.splice(indx,1);
    }

    return {
        remove: reomoveSubscriber,
        add: addSubscriber,
        addTopic: addTopic,
        removeTopic: removeTopic
    }

})()

The Subscribers module holds the content for all subscribers. But there are some parts of the code above that doesn't make sense. Subscribers.addTopic(), for example, will add a topic to all subscribers. This shouldn't be the case. Every subscriber should have their own topics. Should I add a subscriber module with the addTopic,removeTopic and notifications instead of the Subscribers module? If so, how should I make the Subscribers and Subscriber modules co-exist?

For starters, I thought of adding to the HTML code like so:

<div id='subscriber-module'>
    <div id='subscriber-template'>
    
    <div class='subscriber'>
        
        <p></p> //Should this dot even be here now?
        <input type='text' class='form-control' placeholder='Add Topic'>
        <button class='btn btn-default subscribe'>Subscribe</button>
        <ul>
            
            <li> 
            
        </ul>
        
    </div>
    
    </div>
</div>

But I'm now at a loss. How should I proceed? I don't think the Pubsub pattern is required just yet. There is no "publisher" now. If possible, could you code the structure of the module pattern for this question? Is it better to have a module for a class of objects (Subscribers), or just for a single subscriber, or both?

Communication between Fragment and Activity in Android

I considered this documentation and several SO questions or different tutorials for fragment to activity communication. I'm building a simple chat for my App. When I click a chat room in my InboxFragment I want to pass the name of the chat room to my ChatActivity and add the name of the chat room to the ListView inside the ChatActivity.

The Problem is that I always get the error message that the ChatActivity doesn't implement the interface OnChatRommSelected.

The error message is:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.lyl.nairad, PID: 3018
                  java.lang.ClassCastException: com.lyl.nairad.Activities.MainAppActivity@2600f9ae must implement OnChatRoomSelected
                      at com.lyl.nairad.Fragments.InboxFragment.onStart(InboxFragment.java:137)

My InboxFragment looks like this:

EDIT: In the InboxFragment are some more variables, etc. but I let them away to keep the code as short as possible.

public class InboxFragment extends Fragment {

    // [BEGIN: Communication instances
    OnChatRoomSelected mCallback;
    // END]

    private final String TAG = "InboxFragment";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_inbox, container, false);
        callingActivity = getActivity();
        // Some Code...

        chats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                sendChatRoomName(String.valueOf(chats.getItemAtPosition(position)));
                Intent i = new Intent(getActivity(), ChatActivity.class);
                startActivity(i);
            }
        });

        return view;
    }
    public void refresh(){

        ((TextView)getActivity().findViewById(R.id.toolbar_title)).setText("Chats");
    }

    @Override
    public void onResume() {
        super.onResume();
        refresh();
    }

    // [BEGIN: Interface for Fragment to Activity Communication
    public interface OnChatRoomSelected {
        public void selectedChatRoom(String chatRoomName);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onStart() {
        super.onStart();
        try {
            mCallback = (OnChatRoomSelected) getActivity();
        } catch (ClassCastException e) {
            throw new ClassCastException(getActivity().toString()
                    + " must implement OnChatRoomSelected");
        }
    }

    public void sendChatRoomName(String chatRoomName) {
        mCallback.selectedChatRoom(chatRoomName);
    }
    // END}
}

My ChatActivity looks like this:

public class ChatActivity extends Activity implements InboxFragment.OnChatRoomSelected {

    Button send;
    EditText msgField;
    ListView newsExtending;
    ArrayList<String> messages;
    ArrayAdapter<String> adapter;

    private final String TAG = "ChatActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        messages = new ArrayList<>();
        send = (Button) findViewById(R.id.sendMsgBtn);
        msgField = (EditText) findViewById(R.id.aMessage);
        newsExtending = (ListView) findViewById(R.id.privateMessagesList);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, messages);
        newsExtending.setAdapter(adapter);

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = msgField.getText().toString();
                messages.add(text);
                adapter.notifyDataSetChanged();
                msgField.setText("");
            }
        });

    }
    @Override
    public void selectedChatRoom(String chatRoomName) {
        messages.add(chatRoomName);
        adapter.notifyDataSetChanged();
    }

}



When I comment out

@Override
    public void onStart() {
        super.onStart();
       /* try {
            mCallback = (OnChatRoomSelected) getActivity();
        } catch (ClassCastException e) {
            throw new ClassCastException(getActivity().toString()
                    + " must implement OnChatRoomSelected");
        }*/
    }

in the InboxFragment, my error looks like this:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.lyl.nairad, PID: 3334
                  java.lang.NullPointerException: Attempt to invoke interface method 'void com.lyl.nairad.Fragments.InboxFragment$OnChatRoomSelected.selectedChatRoom(java.lang.String)' on a null object reference
                      at com.lyl.nairad.Fragments.InboxFragment.sendChatRoomName(InboxFragment.java:143)
                      at com.lyl.nairad.Fragments.InboxFragment$2.onItemClick(InboxFragment.java:102)

Software design solution - Game

Before getting to the point, I'll make an introduction of WHAT I am trying to do. I will then provide some code and finally state my issue/question/problem.

The scenario is the following: The battle system of a turn-based rpg game is designed. During the battle, player input can produce different results depending on the "current state" of the battle. I am implementing the State Pattern to solve this.

For example, if the battle is in the action selection state, then the player highlights the action he desires to take, using the UP and DOWN keys and then activates it using the ENTER key.

The next state that the battle system goes into, depends on the action chosen. E.g. if "Attack" is selected, the battle goes into the SelectTargetState. If "Spell" is selected, the battle goes into the SelectSpellState, and then into the SelectTargetState.

Below I provide some code in Java, including only the parts that are immediately relevant. After that, the actual question is asked.

// The BattleScene class, representing the whole battle system
public class BattleScene
{
    private State currentState; // The current state of the system
    // Below are all other attributes such as, heroes, enemies etc.
    ..
    ..

    public void input(int key)
    { currentState.input(key); }
    // The actual implementation depends on the state
    // As said above: "player input can produce different results,
    //  depending on the 'current state'"

    // Setter
    public void setState(State state)
    { currentState = state; }

}

// The abstraction of all States
public abstract class State
{
    // All of them contain a reference to the system they belong to,
    // so that they can "change/control" it
    private BattleScene parent;

    // Constructor
    public State(BattleScene parent)
    { this.parent = parent; }

    // The actual input handling is to be represented by subclasses
    public abstract void input(int key);
}

// A concrete State class, displaying a proper example
public class ActionSelectState extends State
{
    private String[] actions; // List of available actions
    private int index; // The currently "highlighted" action

    // Constructor
    public ActionSelectState(BattleScene parent, String[] actions)
    {
        super(parent);
        this.actions = actions;
    }

    public void input(int key)
    {
        switch(key)
        {
            case DOWN:
                incIndex(); // Increases index safely by 1
                break;
            case UP:
                decIndex(); // Decreases index safely by 1
                break;
            case ENTER:
                activateAction();
                break;
        }
    }

// THE ACTUAL PROBLEM - READ BELOW
    private void activateAction()
    {
        if(action.compareTo("Attack")==0)
            parent.setState(new SelectTargetState(parent));
        else if(action.compareTo("Spell")==0)
            parent.setState(new SelectSpellState(parent));
    }
}

The problem/issue is that for every possible action, there could be a different path and number of states to be followed. E.g.: - Attack->Select Target-> Execute Action - Spell->Select Spell->Select Target(s)->Execute Action - Item->........ - Possibly dozens of commands in the future....->....->....

The activateAction() above would then need dozens of "if..else". And what if other states need similar conditional selections depending on the action? That would require each state to have long "if..else" statements as well. Maybye even the number/kind of states change in the future, for instance more will be added.

Is there any sophisticated solution to this problem? Any way to make it resistant to scaling (i.e. avoid exponential increase in conditional statements)? Or am I limited to the large if..else (or switch..doesn't matter)?

Open to any ideas, suggestions, solutions. Maybye some different overall design? Another pattern? Additional patterns? If you want more details, let me know. Regarding code, you can also provide equivalent C++ code if it's more convenient for you. I'm interested in a design solution, from a software engineering point of view...not in language specific solutions.

samedi 24 décembre 2016

Design Pattern for handling web services

This is a designing question from an interview :

Create a Java application which consumes REST web services and shows their response.

Which design pattern would you use such that any error encountered (such timeout, does not exists 404, etc.) can be gracefully handled and proper message shown without causing the application to fail?

What case of inheritance will be correct, rectangle from Square or conversely?

What case of inheritance will be correct?
When we inherit rectangle from square or square from rectangle or we shouldn't do inherit in this case?

Hide 'meta' (e.g. analytics) code in Application

I'm developing an iOS application in Swift and as the project grows my codebase is becoming crowded with 'meta' code like analytics and event logging. Is there a nice way to hide this away in another class so that my business-logic in the main classes (e.g. custom ViewController classes) isn't cluttered?

Better way to return a new instance of Process

I have a below factory which will get called from multiple threads.

public class ProviderFactory {
  private final Map<TypeName, Provider> typeToProvidersMap;

  private static class Holder {
    private static final ProviderFactory INSTANCE = new ProviderFactory();
  }

  public static ProviderFactory getInstance() {
    return Holder.INSTANCE;
  }

  private ProviderFactory() {
    Map<TypeName, Provider> tmp = new HashMap<>();
    typeToProvidersMap.put(TypeName.typeA, new DataProvider());
    typeToProvidersMap.put(TypeName.typeB, new ProcessProvider());

    this.typeToProvidersMap = Collections.unmodifiableMap(tmp);
  }

  public IProcess createNewProvider(TypeName typeName) {
    Provider provider = typeToProvidersMap.get(typeName);
    if (provider == null) {
      throw new IllegalArgumentException("invalid typeName is passed");
    }
    IProcess process = new ProcessImpl(typeName.name(), provider);
    return process;
  }
}

In my above factory createNewProvider method will be called from multiple threads. It looks like there is no need to use the Holder pattern in such a convoluted way the way I am doing right now? For instance, I am using inner class just to hold the instance that I immediately construct?

Is it ok to use factory pattern here the way I am using right now or is there any other better and simple way to do the same thing which is also thread safe?

Rails pattern for destroying relationship between two ActiveRecord objects

Say I have two models, A and B, where each has a has_and_belongs_to_many relationship with the other. That is, some A objects and B objects are "connected".

What would be the proper way to offer a route to destroy this relationship? It doesn't really make sense to be a destroy action on A or B's controller since we aren't destroying A or B. Is there some sort of standard way to do this?

Thanks :)

Angular good design pattern for implementing utility functions

I searched for a lot of design patterns, but found nothing on how to implement functions that are going to be used both in some controllers and in html markup. I really want to escape copy-pasting functionality, so here goes the problem.

I have some items stored in localStorage as an Array of entitites, each of which has a price, quantity and discount. Call that array a cart of items. In a certain page I need to interpolate the sum of the prices as an "overall price". That is the 'cart displaying page', which is basically a list of items from the cart. On the other hand, I have an 'order page' with a form, in which the overall price should also be shown. Say this pages are manipulated with two different controllers: OrderController and CartController, in both of which I have a function called calculatePrice, which returns the overall sum, which is then interpolated inside the html in both order.html and cart.html.

So it happens I already did some copy-pasting. And if (which is possible in the nearest future) I have another controller/view which needs this function, I'll end up copy-pasting again.

My thoughts on this:

1) Create a $rootScope function calculatePrice and just use it as is, both inside controllers and the view. Undesired, don't want to insert too much imperative code inside the 'run' cycle of my app

2) Create a service for utility functions, inject it inside the controllers and only declarative style like '$scope.someFunction = service.someFunction'

3) Create a service, inject it inside the app.run function and connect it to rootScope

But I don't think any of this is right. I want to find the most possible clean solution.

Whats a good design pattern for class that wraps shader parameter values

I am trying to design a class that would wrap shader parameter in such way that it would enable the user to easily set and get its value without a need to write a tone of validation code outside of this class implementation.

The problem is that obviously the shader parameter values can be of different types, and weather I use templates or method overloading it results in a lot of messy code that if one was to use this class it would probably not be a very pleasant experience.

Is there some clever design pattern that once implemented would render the usage of said class to be more straight forward ? I wouldn't mind if the mechanism was more complex as long as its implementation is not exposed to the user of this class.

Also just to be more clear, this shader parameter class is somewhat abstract in that its purpose is only to store the parameter for easier editing and handling across my code base. It does not interact or have any knowledge about the actual shader.

vendredi 23 décembre 2016

User roles in Java

I am building POS system. The think is that I don't know what roles are going to be with what functionality. Here is what I have till now:

  • I imagined that I have one main class for javafx primary stage, scene and tabpane. Also, there is each class which extends Tab class for tabPane, and all needed code for that functionality. So each tab is separate.
  • On other hand. There is User class which is abstract with basic attributes and abstract method tasks(), and in each concrete user role ( Administrator ) class which extends this abstract class implement this method. In tasks() method I would add in List all tabs class which are needed for that user role.

I want to know if this method for users role is good or bad. Acctualy I am not satisfied. The reason is open-closed OOP principle. I am not sure which users role are going to be, so I want to make it dynamic.

  • Now, what I have in mind, is that I have only one user for start, and that is Administrator. Then, he and only he can make other user roles and save to database. User role tabs he need, administrator would add while creating user role. This way, you can return and add some new functionality to user role. There is no need to go back to code, and adding new to tasks() method.

My concerne is how to implement this. What should I put in database for tasks, should I put Strings and then in some concrete class to add tasks based on string ( With lots of if statement ), or should I serialize arraylist of tasks and then save to database?

Count number of occurrences in file. conditional pattern matching

Sorry if the title doesn't make it clear.

I have a file to be read every 15 mins and find a particular pattern in it (e.g. timeout). File does not have any fixed update frequency.

Outcome expected:- 1. if pattern is found 3 times in 15 mins, run command1. 2. if pattern is found 5 times in 15 mins, run command2.

File to be read from last read position for each check.

Thanks, GRV

How do I call a function to run in a graph window in a specific pattern?

I have a function with objects that has to run at specific points in the graph window.

Each line represents the function (100x100) in what it is supposed to be a 500x500 window.

-----
 ---
  -
 ---
-----

I know how to make it run like this:

-----
-----
-----
-----
-----

by using nested loops.

def AssortmentOfObjects(size):
    win =GraphWin("Object assortment", size,size)
    ypoint = 0
    for y in range(5):
        xpoint = 0
        for x in range(5):
            Objects(win, xpoint, ypoint)
            xpoint = xpoint + 100
        ypoint = ypoint + 100

Apparently you can use if statements to make them run in a tessellation.
I just have no idea how.

Thank you for any help! Much appreciated.

How to validate each process object from its own validator?

I have two process and for each process, I will get different Record object and I need to validate those Record object. This means I cannot use single validator as I have to validate different fields for both the process.

  • For processA, I am using ValidatorA class to validate its Record object.
  • For processB, I am using ValidatorB class to validate its Record object.

If they are valid, then I will move forward otherwise I won't move forward. Below is my process code both for A and B.

public class ProcessConsumer implements Runnable {
  private static final Logger logger = Logger.getInstance(ProcessConsumer.class);
  private final String processName;
  private final Validator validator;
  private final RecordProcessor<byte[], byte[]> process;

  public ProcessConsumer(String processName, Validator validator) {
    this.processName = processName;
    this.validator = validator;
    this.process = new RecordProcessor<>();
  }

  @Override
  public void run() {
    try {
      process.subscribe(getTopicsBasedOnProcessName(processName));
      ....

      while (true) {
        ConsumerRecords<byte[], byte[]> crs = process.poll(2000);
        for (ConsumerRecord<byte[], byte[]> cr : crs) {
          // record object will be different for my both the processes.
          Record record = decoder.decode(cr.value());
          Optional<DataHolder> validatedHolder = validator.getDataHolder(processName, record);
          if (!validatedHolder.isPresent()) {
            logger.logError("records dropped. payload= ", record);
            continue;
          }
          // send validatedHolder to processor class
          Processor.getInstance().execute(validatedHolder);
        }
      }
    } catch (Exception ex) {
      logger.logError("error= ", ExceptionUtils.getStackTrace(ex));
    }
  }
}

Below is my ValidatorA class in which I am validating few fields on record object and if it is valid, then I am returning DataHolder.

public class ValidatorA extends Validator {
  private static final Logger logger = Logger.getInstance(ValidatorA.class);

  @Override
  public static Optional<DataHolder> getDataHolder(String processName, Record record) {
    Optional<DataHolder> dataHolder = Optional.absent();
    if (isValid(processName, record))
      dataHolder = Optional.of(buildDataHolder(processName, record));
    return dataHolder;
  }

  private DataHolder isValid(String processName, Record record) {
    return isValidClientIdDeviceId(processName, record) && isValidPayId(processName, record)
        && isValidHolder(processName, record)
  }  

  private DataHolder buildDataHolder(String processName, Record record) {
    Map<String, String> holder = (Map<String, String>) DataUtils.extract(record, "holder");
    String deviceId = (String) DataUtils.extract(record, "deviceId");
    Integer payId = (Integer) DataUtils.extract(record, "payId");
    String clientId = (String) DataUtils.extract(record, "clientId");

    // add mandatory fields in the holder map after getting other fields
    holder.put("isClientId", (clientId == null) ? "false" : "true");
    holder.put("isDeviceId", (clientId == null) ? "true" : "false");
    holder.put("abc", (clientId == null) ? deviceId : clientId);

    return new DataHolder.Builder(record).setClientId(clientId).setDeviceId(deviceId)
        .setPayId(String.valueOf(payId)).setHolder(holder).build();
  }

  private boolean isValidHolder(String processName, Record record) {
    Map<String, String> holder = (Map<String, String>) DataUtils.extract(record, "holder");
    if (MapUtils.isEmpty(holder)) {
      logger.logError("invalid holder is coming.");
      return false;
    }
    return true;
  }

  private boolean isValidpayId(String processName, Record record) {
    Integer payId = (Integer) DataUtils.extract(record, "payId");
    if (payId == null) {
      logger.logError("invalid payId is coming.");
      return false;
    }
    return true;
  }

  private boolean isValidClientIdDeviceId(String processName, Record record) {
    String deviceId = (String) DataUtils.extract(record, "deviceId");
    String clientId = (String) DataUtils.extract(record, "clientId");
    if (Strings.isNullOrEmpty(clientId) && Strings.isNullOrEmpty(deviceId)) {
      logger.logError("invalid clientId and deviceId is coming.");
      return false;
    }
    return true;
  }
}

And below is my ValidatorB class in which I am validating few different fields as compared to ValidatorA on record object and if it is valid, then I am returning DataHolder.

public class ValidatorB extends Validator {
  private static final Logger logger = Logger.getInstance(ValidatorB.class);

  @Override
  public static Optional<DataHolder> getDataHolder(String processName, Record record) {
    Optional<DataHolder> dataHolder = Optional.absent();
    if (isValid(processName, record))
      dataHolder = Optional.of(buildDataHolder(processName, record));
    return dataHolder;
  }

  private DataHolder isValid(String processName, Record record) {
    return isValidType(processName, record) && isValidDatumId(processName, record) && isValidItemId(processName, record);
  }  

  private DataHolder buildDataHolder(String processName, Record record) {
    String type = (String) DataUtils.extract(record, "type");
    String datumId = (String) DataUtils.extract(record, "datumId");
    String itemId = (String) DataUtils.extract(record, "itemId");

    return new DataHolder.Builder(record).setType(type).setDatumId(datumId)
        .setItemId(itemId).setHolder(holder).build();
  }


  private boolean isValidType(String processName, Record record) {
    String type = (String) DataUtils.extract(record, "type");
    if (Strings.isNullOrEmpty(type)) {
      logger.logError("invalid type is coming.");
      return false;
    }
    return true;
  }  

  private boolean isValidDatumId(String processName, Record record) {
    String datumId = (String) DataUtils.extract(record, "datumId");
    if (Strings.isNullOrEmpty(datumId)) {
      logger.logError("invalid datumId is coming.");
      return false;
    }
    return true;
  }   

  private boolean isValidItemId(String processName, Record record) {
    String itemId = (String) DataUtils.extract(record, "itemId");
    if (Strings.isNullOrEmpty(itemId)) {
      logger.logError("invalid itemId is coming.");
      return false;
    }
    return true;
  }
}

And below is my abstract class:

public abstract class Validator {
  public abstract Optional<DataHolder> getDataHolder(String processName, Record record);
}

Question:

This is how I am calling for both of my process. As you can see, I am passing processName and its particular validator in the constructor argumnets.

ProcessConsumer processA = new ProcessConsumer("processA", new ValidatorA());
ProcessConsumer processB = new ProcessConsumer("processB", new ValidatorB());

  • Is this a good design where for each of my process, pass its validator along with?
  • Is there any way we can avoid passing that? And internally figure out what validators to use basis on the processName? I already have an enum with all my processName. I need to make this design extensible so that if I add new process in future, it should be scalable.
  • Also the way I have my abstract class Validator is right? It is not doing any useful things at all looks like.

Each of my Validator is basically trying to validate whether the record object is valid or not. If they are valid, then they make DataHolder builder and return it, otherwise it returns Optional.absent();