jeudi 31 août 2017

Where to test default method implementation of superclass

I have fallowing classes:

Parent.java

interface Parent{
    void method1();

    default void method2(){
       //some default impl
    }
}

ChildOne.java

class ChildOne implements Parent{
    @Override
    void method1(){
        //ChildOne specific implementation
    }
}

ChildTwo.java

class ChildTwo implements Parent{
    @Override
    void method1(){
        //ChildTwo specific implementation
    }
}

Question is: where I should put a method 2 test? I know that for unit tests I should test concrete implementation so ChildOne and ChildTwo but when I have the same implementation of method2 I don't want to duplicate my test for it. However putting it into one of these classes don't seems to be good either.

Ofc, question is the same for abstract class with default implementation instead of interface.

mercredi 30 août 2017

Recommended design patterns to apply

I need to solve a problem which at the first seems simple but make me confused quickly.

Suppose I have a User which holds Box objects. A Box is an abstract concept that is concretely implemented by some concrete classes, e.g. MoneyBox, PointBox, ValueBox, ItemBox, etc.

Moreover, a box object can be composed of multiple dependent Box objects which can be of the same type described above.

This means that a user can hold, for example, a MoneyBox and a PointBox. The MoneyBox can also have a dependent DiscountBox.

A box supports a defined number of behaviors like Activate, Use, Disable, etc.

The algorythm is activated from a request that should be applied to a User. The requests then shall be forwarded to every Box of that user. If a Box has dependents boxes, those shall be notified about the requests as well.

Forwarding a request to a box can be done in parallel for the boxes directly holded by the user but shall be done sequentially, based on an order field, to dependent boxes.

I have read many sources on the internet including patterns like Mediator, Chain of responsibility and Command but I can't get through on putting them all together.

Any help and/or suggestions?

Generic Strategy pattern

I'm trying to implement strategy pattern with generic types. I try to create object and the end invoke it but I have no idea how should look like signature of it. My problem is in ObjectProcessor class(Do method).

//my code
abstract class Credential {}
class SNMP : Credential { }
class HTTP : Credential { }

//dll
abstract class CredentialDLL { }
class SNMPDLL : CredentialDLL { }
class HTTPDLL : CredentialDLL { }

interface IMapper<T, Y>
{
    T Map(Y input);
    Y Map(T input);
}

class SNMPMapper : IMapper<SNMP, SNMPDLL>
{
    public SNMPDLL Map(SNMP input) { throw new NotImplementedException(); }
    public SNMP Map(SNMPDLL input) { throw new NotImplementedException(); }
}

class HTPPMapper : IMapper<HTTP, HTTPDLL>
{
    public HTTPDLL Map(HTTP input) { throw new NotImplementedException(); }
    public HTTP Map(HTTPDLL input) { throw new NotImplementedException(); }
}

class ObjectProcessor
{
    CredentialDLL Do(Credential input)
    {
        IMapper <?,?> mapper; // ??

        if (input is SNMP)
        {
            mapper = new SNMPMapper();
        }
        else
        {
            mapper = new HTPPMapper();
        }

        return mapper.Map(input);
    }
}

A little bit confused of `new` keyword in factory design pattern in javascript?

In the following code

var peopleFactroy = function(name,age,state) {

var temp = {}

temp.name  = name;
temp.age   = age;
temp.state = state;

temp.printPerson = function() {
  console.log(temp.name +" "+temp.age+" "+temp.state);


   }

 return temp;
 }

var person1 = peopleFactroy('Mahmoud',21,'lA');
var person2 = peopleFactroy('Mohamed',26,'bt');

person1.printPerson();   //Mahmoud 21 lA
person2.printPerson();   //Mohamed 26 bt

I know it is okay not to use the new keyword as i am returning an object from the constructor function and creating any number of persons, each will have his own object.

Now my question is if i used new keyword in the above example when creating persons object what would be the difference? , i tried that and gives me the same results but are they truly the same concept so they produce the same results or they are technically different but produce the same results?

ZeroMQ Choosing Correct Client-Worker Model for a Call Center

I have a project that needs to be written in Perl so I've chosen ZeroMQ.

There is a single client program, generating work for a variable number of workers. The workers are real human operators who will complete a task then request a new task. The job of the client program is keep all available workers busy all day. It's a call center.

So each worker can only process one task at time, and there may be some time before requesting a new task. And the number of workers may vary during the day.

The client needs to keep a queue of tasks ready to give to workers as and when they request them. Whenever the client queue gets low the client can generate more tasks to top-up the queue.

What design pattern (i.e. what ZeroMQ Socket combination) should I use for this? I've skimmed through all the patterns in the 0MQ Guide and can't find anything that matches this.

Thanks

Java - Factory and Strategy Patterns with Generics

I'm trying to implement a Strategy + Factory pattern using generics. The goal is to return to a client class an implementation of the interface DocumentDao that can deal with a type T extends Document, so I've multiple Dao interface extending DocumentDao for different subtypes of Document.

Here is my code:

public class Document { ... }

public class DocumentA extends Document { ... }

public class DocumentB extends Document { ... }

public interface DocumentDao<T extends Document> {
   public void update(T document);
}

public interface DocumentADao<DocumentA> {}

public interface DocumentDaoFactory {
   public DocumentDao<T extends Document> getDaoInstance(Class<T> clazz);
}

Then I try to use the Factory:

private <T extends Document> void someMethod(T document) {
   ...
   DocumentDao<T> documentDao = this.documentDaoFactory.getDaoInstance(document.getClass());
   documentDao.update(document);
   ...
}

But the compiler complaints about the getDaoInstance() call:

Type mismatch: cannot convert from DocumentDao<? extends AbstractGDriveDocument<?>> to DocumentDao<T>

How to deal with this situation? How can I obtain a similar solution?

Thanks

Symfony how to get container in my service

I have project and inside this project, I have big own service which is huge and complicated with own dependencies etc... And I wanna create for this service with purpose to use my service in controllers like:

$myService = $this->container->get('service_from_my_domain');

My question - is how inside my facade I can get access to container to service's dependencies. I know only 1 way - is to inject dependency into service in yaml config.
But is there another way to do it? Like:

$dependency = Container::getInstance()->get('my_dependency_service');

I've found this answer but using global variable feels like back in time...

PS: I don't want to inject dependency through yaml config (constructor injection not setter injection) because I don't need IoC () here.

Unity multiplayer design pattern

I am trying to create multiplayer game in unity using Unet. Searched on web for design pattern but didn't find any promising answers. I have started with development and I am not sure if that is correct approach. I have explained flow below. Please let me know if I should go ahead with that or any other options:

As command works on player object only, I am creating network interface class for all non player objects which will implement commands for them. These interfaces will be attached to player object. e.g. Enemy manager class : this class spawns enemies. NetworkEnemyManager class : interface attached to player.

EnemyManager::spawnEnemy will call command function in interface and interface will call a enemy manager function which will instantiate enemies and then do the network spawn.

Please comment if question is not clear.

Subclassing and Exposing superclass - Is it a Facade design pattern?

Lets assume we have a class A, and 2 subclasses of this class - class A1 and class A2

If we do not know if an object coming in is of type A1 or A2, we do something like: object = incomingObject as A

Is this still using the Facade design pattern? Or is there a different name for this pattern?(maybe just simple inheritance)

List of similar objects - invoke different method for each element

I'm looking for a good practice/idea how to write a clean code for my solution. Let's say I have class Foo:

public class Foo
{
    public SomeEnumType Type { get;set; }
    ....
}

I got a list of these elements like:

List<Foo> Foos

Now I want to iterate over my list and invoke different methods for any EnumType. For now I'm just doing something like this:

foreach (var x in Foos)
{
     if (x.Type == XXX)
        invoke first();
     else if (x.Type == YYY)
        invoke second();
     .....
}

It looks OK if i got one or two values in my TypeEnum, but unfortunately I will have about ~~30 and as I assume it will look terrible with ~~30 else. How to make it better? Does anyone have met such a problem before?

Is there any better way to track subscriber changes?

Lets say we have a Client class with method to send messages to server queue. It is also subscribed to queue and server will send a notification back to all clients when it receives a new message from any of registered clients:

    public class Client {
        public void sendMessage(String message) {
            // Method to send messages to server
        }

        public void messageDelivered(String receivedMessage) {
            // This is a method subscribed successfull message delivering
        }
    }

In another class I would like to instansiate my Client, send a message and check that it was sent successfuly:

    public class ParentClass {
        protected void checkConnection() {
            Client client = new Client(); // Lets skip all configuration and connection details

            String testMessage = "Test message";
            client.sendMessage(testMessage);

            // Check that messageDelivered() was called in client with testMessage parameter
        }
    }

What is the best way to check that messageDelivered() was called asynchroniously inside parent checkConnection() method?

I see the simple solution to create a flag in Client class, update it when message is delivered and wrap checking of this flag in some loop limited by time in parent class. But this option looks very dirty for me. Maybe there are some better practicies or "watchers" in Java SDK?

How to reduce amount of parameters passed to main

Is there any way of somehow reducing or compacting the amount of arguments passed to main they these are many?

Let's say I have a Ludo game, and I need to pass number of players, names, colors, type of player (human, computer), type of AI for computer players. That's a lot of arguments.

I don't think I can use any of the techniques described in Effective Java. Is there any smart way of achieving this?

Java Passing Parameters Best Practice

Which approach is the best practice in Java - ORM - RestFul Services?

1-Get a User JSON from a Client

2-Create a User object like : User user = JSON_to_User_Object_method

3-Call the service method to add user, and pass the User object like : service.addUser(User user)

or

1-Get a User JSON from a Client

2-Call the service method to add user but pass the Json values to the service's method like : service.addUser(jsonobject.name, jsonobject.surname, ......)

3-And handle the other stuff in the service method named addUser,(create User Pojo, end persist and so on..)

mardi 29 août 2017

How to override javascript module pattern public method?

I have a module that looks like this:

var V;

V = (function() {

    var V = function() { }

    V.doSomething = function() {
        console.log('A');
    };

    return V;

})();

I would like to, after this is declared, override that doSomething method so that when I call V.doSomething() something else is printed instead of A.

I tried to simply assign a new function like so:

V.doSomething = function() { console.log('B'); }

...but that doesn't work, when I invoke V.doSomething() I get the original function invoked.

Is there a way to do that?

Decorator functions in Go

Decorator pattern (functions) has many benefits:

It is very useful when a method has many orthogonal concerns... I.e., None of these concerns are related, other than that we wanna do all of them whenever we call our method. This is where the decorator pattern really helps.

By implementing the decorator pattern we subscribe to the open-closed principal. Our method is open to future extension but closed to future modification. There's a lot of groovy benefits to obeying the open-closed principle.

However, all the examples that I found are really complicated (e.g., writing HTTP servers with many middlewares). This make it difficult for me to apply the principle elsewhere. I need something that I can easily try on so as to wrap my head around it.

Can someone give me an simpler example that can best illustrate how to do Decorator pattern (functions) in Go please?

This example by Alex Alehano, is too simple to be put into practical use. I need something that can illustrate this:

func Decorate(c Decorated, ds ...Decorator) Decorated {
    decorated := c
    for _, decorate := range ds {
        decorated = decorate(decorated)
    }
    return decorated
}

A string manipulation according to different option/instruction, e.g., to upper, to lower, to base64, etc, would be the best example IMO. Thanks

Is hybridation of design pattern a bad pratice?

My experience and understanding of design patterns comes from working with Laravel, so i'm actually only experienced in MVC design pattern, but I found my self developing a sort of "autocompiling" view for each of the CRUD operations, so for example i usually put some sort of Array in my model to describe how i want the view to be generated for the model itself, and after that i write a general view that read out the model proprieties and based on the array it will generate the fields as required, something like:

class User extends Model{
    public $editFormArray=array(["name","text",20],
                                ["surname","text",30]);
    [...]
}

and the view will have and implementation that loads the model sent to it, and based on the $editFormArray propriety, it will generate itself

Something like:

@foreach($resource->editFormArrayas $currForm)
    @if ($currForm[1]=="text")
        <div class="form-group">
           <div class="col-md-12">
              <input name="" type=""
                     placeholder="" size="">
           </div>
        </div>
    @endif
    [...]
@endforeach

this kind of approach let's me create only 1 view for CRUD operation (and some others view that can't be automatically computed, as per required) and also allows me to change the model form on the fly, adding, removing and editing fields as i see fit on the fly, but also makes my model files be really loaded.

One of my co-worker recently took a course about design patterns and thinks this is bad pratice, saying a normal MVC, with a View manually generated for each single model CRUD operation would be the right way to do it, but i think he is wrong, because the View itself doesn't really compute any real logic (all the logic is actually kept on the controller), it only computes "display logic" as in the logic required to correctly display the UX itself.

Someone could shred some light on the arguments?

Dynamic function mapping

I'm currently playing around with Design Patterns in Python. I tried to write a generic Proxy which counts calls to attributes/functions. This works fine with getattr for own types, but doesn't work for stuff like str(), len() etc. So I tried dynamically remapping the function calls to the functions of the child object, but It doesn't work. Anyone can help me out on this?

class CountAccessProxy():
  def __init__(self, obj):
    self._obj = obj
    self.updateFuncs(dir(obj))
    self.countAccess={}
    print(self.__dict__)

  def __getattr__(self, att):
    self.countAccess[att]= self.countAccess.setdefault(att, 0) +1
    return getattr(self._obj, att)

  def updateFuncs(self,funcs):
    for func in funcs:
      if "__" in func:
        #Try to remap the functions to the functions of child obj
        self.__dict__[func] = getattr(self._obj,func)


listy = CountAccessProxy([0,2,5,5])
print(len(listy))

Traceback (most recent call last):
  File "proxy.py", line 52, in <module>
    print(len(listy))
TypeError: object of type 'CountAccessProxy' has no len()

Java observer pattern for a GUI - distinguish between different events without typeof

I have a simple Controller object that that implements Observer (i.e. it is the observer) which listens for events from a Mouse object that extends Observable (i.e. it is the observee).

So there can be multiple events in a Mouse object e.g. left click, scroll up, etc.

Now the Controller class implements the required method which is called every time any of the above events happen:

@Override
public void update(Observable o, Object arg)
{

}

So it is the arg parameter that I am having trouble deciding how to approach (this case I am working on is simple enough such that the o parameter is not a concern). What is a good way to distinguish between different mouse events without using typeof?

I.e. what parameter should I feed in the notifyObservers(Object arg) method in the Mouse observee class?

How to enforce implementing classes to be immutable?

While designing a small app, I've found that it would be very convenient for implementations of an interface A to be immutable.

I can't just use the immutable interface pattern because the interface has a method execute(Command command), which has a big potential to mutate state. I expect implementations of A to have fields of mutable types. The given Command will operate on them, for instance:

public class AImpl implements A {

    private List<PotentiallyMutable> elements;

    @Override
    public void execute(Command command) {
        elements.get(command.getUnitIndex()).doSomething(); // State changed
    }
}

But as I said I want instances to be immutable. I can specify that implementations should be immutable in the javadoc. I can also change the method signature to A execute(Command) as a reminder to implementors, and suggesting implementations to be used à la BigDecimal/String:

aImpl = aImpl.execute(command)

Which is an idiom I don't like. Also, it obviously wouldn't prevent this:

    @Override
    public A execute(Command command) {
        elements.get(command.getIndex()).doSomething(); // State changed
        return this;
    }

Is there anything else that I can do or any other pattern that I can apply?

Java regular expression statement expansion

I have a simple Java class to validate Visa and Mastercard numbers:

public class ValidateCC
{
  public static void main(String[] args)
  {
    String ccStr = "4543600322751739";
    System.out.print(ccStr.matches("(4|5)[0-9]{15}"));
  }
}

I need to expand this regular expression by validating another type of card number that must begin with 35, 97 or 65.

How can I achieve this please?

Thanks.

AC and remote java design

I have a design question. Like I have 2 AC and one remote. I need to design this in java and both AC need to operate using the same remote.

Here I can use the java observer design pattern , but how well it will serve my purpose .. doubtful.

Kindly help.

Xcode MVC pattern - where to put the code - how you do it

I do have a simple Xcode project and have structured it like this:

myProject
--Storyboards
----LaunchScreen.storyboard
----Tutorial
-------Tutorial.storyboard
-------TutorialFeature.xib
--Data
----Tutorial
-------TutorialData.plist
---Model
-----Tutorial
-------TutorialModel.swift
--View
----Tutorial
-------TutorialFeature.swift
--Controller
----Tutorial
-------TutorialController.swift

According to the MVC pattern rules (feel free to correct me when I'm wrong):

  • the Model deals with the Data
  • the Controller deals with the Model, business logic and passes everything to the View
  • the View displays it all

I'm dealing with a NIB which is loaded by the View and populated with Data from the Model by the Controller. In the example above:

  • TutorialFeature (View) -> loads: TutorialFeature.xib
  • TutorialController loads Data from TutorialModel and passes it to the View

However, I've seen many examples where the NIB is loaded and populated with Data in the Controller, leaving the View with just the Outlets.

What's the best practice from your point of view and am I wrong to load the NIB from the View as it can be seen as business logic, no?

lundi 28 août 2017

Accessing all derived children from parent in singleton

I am trying to write a singleton parent class that could be used as a basic accessor for all of its derived children, and getting stuck on wrapping my mind around the logic. I wrote some code, but it doesn't compile :(

Also, I am not sure if I am using the design pattern right either -- maybe I am supposed to use some other one?

Below is the code that I am trying to compile. The main point of the final code is to have a singleton for global configuration, and the children are configuration classes for different parts of the program.

template <struct T>
struct Parent {
    T* operator[](std::string child) {
        return dynamic_cast<T*>(children_[child]);
    }
    static const T& getInstance() {
        if (!one_parent_to_rule_them_all_) 
            one_parent_to_rule_them_all_ = new Parent;
        return dynamic_cast<T>(*one_parent_to_rule_them_all_); 
    }
    std::string Dump() {
        std::string res = "";
        for (const auto& child : children_) {
            res += child.second->Dump();
        }
        return res;
    }
protected:
    Parent() = default;
    Parent(std::string child_name, Parent* child) {
        children_[child_name] = child;
    }
    static Parent* one_parent_to_rule_them_all_;
    static std::map<std::string, Parent*> children_;
};

struct Child1 : Parent<Child1> {
    Child1() : Parent("child1", this);
    int foo = 0;
    std::string Dump() {
       return std::string(foo); 
    }
};

// More children here!

class ICanHazParentz {
// This class wants to have an instance of the parent, 
// without specifying the children
public:
    Parent p;
    void Dump() {
        std::cout << Parent::Dump() << std::endl;
    } 
}

class ICanHazChild1 {
// This class wants to have access to a child, 
// without specifying the parent
public:
    void Dump() {
        std::cout << Parent::getInstance()["child1"]->Dump() << std::endl;
    } 
}

int main() {
    Child1 c1;
    // More children
    ICanHazParentz ichp;
    ichp.Dump();
}

Although the current code looks silly, it is just an oversimplification of the final code.

findByUsername or find method of Facade absract class

I'm trying to make a Login app with JSF, and I found in forums that a lot of people use LoginByUsername(or findByUsername or whatever they call it ,anyway a method that does find the username and returns the user) and they put it in the facade(session bean for entity class) ! But the facade itself gives us something called find(Object id) ,and the id is username . so what's better? and why?

thanks in advance for your help

go design - correct way to pass data/behaviour around, in large codebase used by multiple teams

I managed to convince a bunch of colleagues to try go for a new system. None of us is experienced in go and while this is a 'because we can' project and we have some budget to burn I would like to see go succeeding within the company in the long term, so some planning is needed beforehand..

I'm looking for the 'proper go way' of structuring a program when it comes to passing data and behaviour between distinct 'units'. More specifically the program will be comprised of multiple packages, each of which performs some data collection and analysis and stores the results in a fairly large struct (one struct/one type per package mostly). We want to define 'contracts' with other teams that create other packages that are concerned with parsing that data and either presenting it (through http web rpc for example) or performing further analysis etc

I want to avoid:

  • duplication of code (i.e. I don't want to have a separate parser for each type, I expect a lot of overlapping functionality between the produced types)

I want to achieve:

  • keeping responsibilities separate as much as possible (i.e. parsing the data belongs in a parser package, not in the same package as the one that scans the system for data, as maintenance is then likely to become problematic, same with presenting the data, I don't want every parser package to bundle it's own router etc)

Essentially it boils down to:

  • what to use to pass these 'objects' around - I can't just use the equivalent of map[string]object for example (or can I?), a single type struct with bazillions of fields followed by if/else in the code doesn't seem to make too much sense either and marshalling/unmarshalling to json feels too 'heavyweight'. I thought about getters/setters on an interface but that is probably too java-like and not what a proper gopher would do
  • how to structure the program in order to achieve as little duplication as possible, end up with a recommended design based on go principles etc. I took some time to go through the code in some popular "devops" projects and it seems it's a right mess at the moment :)

As an example, if I was using an object oriented language I would be able to 'wrap' my data in plain objects with getters/setters that would present a uniform interface regardless of the underlying data type, then on a higher level define interfaces with a basic shared set of messages, have classes implement these behaviours, use inheritance to minimize code duplication between classes of the same base type etc.

What algo/design pattern do i need to keep limited time series data constantly updated?

I'm a hobbyist coder; never worked professionally. I am not looking for anyone to write code for me, but I need to know how to approach this problem and, perhaps, ideas for further research. This problem is an outgrowth of my kid's science project that I wanted to toy with.

Bottom line is: I have a sensor that feeds data objects at irregular and unpredictable intervals (temp, air pressure, other things). Each new "update" feeds another data object with all the pertinent info...and each object has a time stamp. The unpredictability is the core of the problem, and that will not change. As my code gathers new data objects at irregular intervals, I need to run simple arithmetic operations on the data objects for the last n minutes. I need to output these arithmetic operations continuously on each new "update" of fresh data. The sensor could put out as many as, say, 20 updates per second...or fewer. CPU and RAM usage are a mild concern, but I want to focus on getting working design first.

At first, I was thinking circular array or queue, but that's no good since I do not know how many objects will cover the last n minutes.

Next, I considered a doubly linked list. The problem with this approach is that it will have to consume heavy CPU by iterating over the entire list each new "update" in order to remove outdated objects from the list or will have to consume a lot of ram if I do not remove old objects from the list each time.

I am wondering what design patterns (and data structures) might fit this problem, and what other items I could research to learn more to solve this problem.

I realize I am not giving much information here, but I want to keep simple and I believe I have given the gist of the problem.

I really appreciate any help. Btw, I'm using C# and the CLR for now. Python might be a better option since this is data-science'ish. I believe I could write and/or consume a Python library/class. I'm not real fluent with Python.

What is the difference between State and Momento design pattern? As both are used for State Preservation

What is the difference between State and Momento design pattern? As both are used for State Preservation

Java Builder pattern with inheritance

I want to implement a builder pattern with static inner classes for lets say classes A with fields (a1, a2, a3), B with fields (b1, b2) and C with fields (c1), whereas all share fields (s1, s2) from super class SuperClass:

public class A extends SuperClass {
    private final String a1;
    ...

    private A(ABuilder builder) {
        super(builder);
        this.a1 = builder.a1;
        ...
    }

    public static class ABuilder extends SuperClassBuilder implements ABuilderInterface {
        private String a1;
        ...

        @Override
        public ABuilder withA1(String a1) {
            this.a1 = a1;
            return this;
        }
        ...

        @Override
        public S build() {
            return new A(this);
        }
    }
}

Accordingly for B and C the builders just differ that they have their own fields and implement their own interfaces (BBuilderInterface and CBuilderInterface), whereas these interfaces are only defining which methods are to be implemented:

public interface ABuilderInterface extends SuperClassBuilderInterface {
    ABuilderInterface withA1(String a1);
    ...
}
...<interfaces for B and C>

public interface SuperClassBuilderInterface {
   SuperClassBuilderInterface withS1(String s1);
   ...
   SuperClass build();
}

// Usage of the builders:
public SuperClass foo() {
    return new A.ABuilder()
        .withA1(...) // returns ABuilderInterface
        ...
        .withS1(...) // returns SuperClassBuilderInterface
        ...
        .build();
}

Now you can spot the limitation that when I use the builder I have to pay attention to call the with... methods related to the child class first, then chain the ones for the super class, which is not a big of a deal, but still not sure whether good practice. On the other side I could add the with... methods of the children classes to the super class interface all together and then the limitation is gone, but then I have an interface with mixed with... methods of different child classes.

Which one would you prefer/suggest?

How to create generic method for methods that have the same structure?

I have the following method in CommentsService class:

async def background_job_auto_approve(self):
    while True:
        new = get_comments_by_status(CommentStatus.NEW.value)
        pending = get_comments_by_status(CommentStatus.PENDING.value)
        all_comments = new + pending
        for comment in all_comments:
            if check_it_auto_approve(item=comment):
                await self.auto_approve(comment_id=comment['comment_id'],
                                        alert_id=comment['alert_id'])
                yield comment
        await asyncio.sleep(self.check_expire_seconds)

But I have exactly the same method in my AlertsService:

async def background_job_auto_approve(self):
    while True:
        new = get_alerts_by_status(AlertStatus.NEW.value)
        pending = get_alerts_by_status(AlertStatus.PENDING.value)
        all = new + pending
        for alert in alerts:
            if check_it_auto_approve(item=alert):
                await self.auto_approve(alert_id=alert['alert_id'])
                yield alert
        await asyncio.sleep(self.check_expire_seconds)

How to avoid code duplication?

Validating Controller classes in java using @Pattern annotation for multiple strings

I am validating a java class using @Pattern annotation from Deadbolt. I want to give access if either of these strings are present : 'TM_TASK' OR 'TM_CHECKLIST'. Right now i am a little confused as to how to provide these strings inside @Pattern so that it gives access if the string matches either of those 2 strings.I am also open to using regex (although i am new to them) as to how to verify if it is any of those 2 strings ('TM_TASK' OR 'TM_CHECKLIST') using Regex and not any other invalid string.

e.g.

@Api(value = "/tasks")
@Pattern(value = "^[a-zA-Z0-9_]*$", patternType = PatternType.REGEX)
public class TaskController extends BaseController {

  private static Logger.ALogger log = Logger.of(TaskController.class);
  private TaskService taskService;
  private FormFactory formFactory;
}

How to generalize logic for two classes that do exactly the same but for different entity?

I have two classes in my project: first do something with comments, second with alerts: AlertFilterService and CommentFilterService

They have almost identical constructors and exactly the same methods signature, like do_somethig_for_alerts(self) and do_something_for_comments(self).

do_somethig_for_alerts(self):
   some_code
   if
       code
   else:
       message['status'] = AlertStatus.NEW.value
       await self.db.store_alert(message)

do_somethig_for_comments(self):
   some_code
   if
       code
   else:
       message['status'] = CommentStatus.NEW.value
       await self.db.store_comment(message)

How to avoid code duplication? What is the best way to do this?

Design Pattern: Restoring State & Operation

What would be a good approach to resume both the state & operation of an object?

For example, when transition to a particular state, the object will need to perform a certain operation.

The problem is when restoring the state directly via the object constructor: it is not a good practice to perform operation in the constructor. So at this point, only the state is restored, not the operation.

enum State { OPEN, CLOSED }

class Stuff {

    State state;
    Timer timer;

    Stuff(State state, Timer timer) {
        this.state = state;
        this.timer = timer;

        // It is not a good idea to call timer.start() here when the state = OPEN.
    }

    void open() {
        state = OPEN;
        timer.start();
    }

    void close() {
        state = CLOSED;
    }

}

multi match pattern without liner search in nodejs

We intend to use linear searches without going through Determine which pattern matches the pattern.

Pattern Example : (keys of json) /Panel/table/:name/update/:id

The field to be searched /Panel/table/person/update/7

Our idea is Jason's Keys

dimanche 27 août 2017

Scala : Registry design pattern or similar?

I am migrating my system from java to Scala. I have used registry pattern in my java code to get the implementation from the string. Is there any similar thing I could do with scala ? I am new to scala, can someone point to me proper references ?

My java code :

public class ItemRegistry {

    private final Map<String, ItemFactory> factoryRegistry;

    public ItemRegistry() {
        this.factoryRegistry = new HashMap<>();
    }

    public ItemRegistry(List<ItemFactory> factories) {
        factoryRegistry = new HashMap<>();
        for (ItemFactory factory : factories) {
            registerFactory(factory);
        }
    }

    public void registerFactory(ItemFactory factory) {
        Set<String> aliases = factory.getRegisteredItems();
        for (String alias : aliases) {
            factoryRegistry.put(alias, factory);
        }
    }

    public Item newInstance(String itemName) throws ItemException {
        ItemFactory factory = factoryRegistry.get(itemName);
        if (factory == null) {
            throw new ItemException("Unable to find factory containing alias " + itemName);
        }
        return factory.getItem(itemName);
    }

    public Set<String> getRegisteredAliases() {
        return factoryRegistry.keySet();
    }
}

My Item interface :

public interface Item {
    void apply(Order Order) throws ItemException;

    String getItemName();
}

I map the string like :

public interface ItemFactory {

    Item getItem(String itemName) throws ItemException;

    Set<String> getRegisteredItems();
}


public abstract class AbstractItemFactory implements ItemFactory {


    protected final Map<String, Supplier<Item>> factory = Maps.newHashMap();

    @Override
    public Item getItem(String alias) throws ItemException {
        try {
            final Supplier<Item> supplier = factory.get(alias);
            return supplier.get();
        } catch (Exception e) {
            throw new ItemException("Unable to create instance of " + alias, e);
        }
    }

    protected Supplier<Item> defaultSupplier(Class<? extends Item> itemClass) {
        return () -> {
            try {
                return itemClass.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                throw new RuntimeException("Unable to create instance of " + itemClass, e);
            }
        };
    }

    @Override
    public Set<String> getRegisteredItems() {
        return factory.keySet();
    }
}

public class GenericItemFactory extends AbstractItemFactory {

public GenericItemFactory() {
     factory.put("reducedPriceItem",  () -> new Discount(reducedPriceItem));
     factory.put("salePriceItem",  () -> new Sale(reducedPriceItem));
}
}

where Sale and Discount are implemntation of Item. I use the newInstance method in ItemRegistry to get the class based on the name. Can some one suggest me any similar thing which can allow me to do the same in scala ?

Is this design of a Spring JPA DAO bad or improper?

I have been working to generalize the methods of the DAO for a project using Spring, JPA and Hibernate. However, I am still very much learning Spring, Java, and coding in general.

Is the below design bad or perfectly fine? Is there a better way to accomplish the same thing? Any advice would be greatly appreciated.

I have simplified the class:

@Repository
public class TestRepository
{
    @PersistenceContext
    private EntityManager entityManager;

    public List<?> getListResults(Class<?> dtoClass, String sqlString)
    {        
        List<?> returnList = null;

        Query query = entityManager.createNativeQuery(sqlString, dtoClass);

        try
        {
            returnList = (List<?>) query.getResultList(); 
        }
        catch (Exception e)
        {

        }

        return returnList;
    } 
}

Examples of GoF Design Patterns in Python core libraries

I am learning GoF Python Design Patterns and I want to see some real life examples of them. What are some good examples of these Design Patterns in Python's core libraries?

[Interview Preparation:Design Patterns] [on hold]

I want to prepare for Design Round in Interviews.
I am looking for a Cook Book.What I mean by Cook Book is that I have read at so many places that best book for Design Pattern is Gang of Four(GoF). I am looking for solution some common interview Design Problems. 1)Design a Cab Book(like Ola/Uber)
2)Design Cinema Management System(like BookMySHow)
3)Design Employee Management System
4)Design Chess Game API at client and server side.
5)Design Parking Lot
6)Design EVM (Electronic Voting Machine)
7)Design Food Ordering (Like Food Panda)
8)Fetch Tweet List of ALL peoples whom some one is following on Twitter.
9)Design Google News.
10)Design MakeMytrip.com
11)Traffic Management System
and so on.
The problems I mention will almost cover all design problems asked at my level[4 years Experience]. I can also look answers for these problems online but I found that answers are very different on different sites.
And Most of the sites do not have follow up questions [like what happens if user internet stops working before generating bill in ola cab]

So can I find a book addressing my requirements.If not ,what is the best way to prepare.Design Pattern Book which I have read is [Peeling Design Patterns by Narsimha Karumanchi].

Populate List from pojo in given order

I have a POJO object having few fields and a list of string. We have to create a list of object using field values of pojo, in exactly same order as of list of string. Right now I am calling list.add with pojo getters while looping on list of String-

public class ResultSet {private String field1;
private String field2;
private String field3;
private String field4;


public List<Object> populateResultList(List<String> list) {
    List<Object> resultSet = new ArrayList<>();
    for (String filedName : list) {
        if ("Field1".equalsIgnoreCase(filedName)) {
            resultSet.add(getField1());
        } else if ("Field2".equalsIgnoreCase(filedName)) {
            resultSet.add(getField2());
        } else if ("Field3".equalsIgnoreCase(filedName)) {
            resultSet.add(getField3());
        } else if ("Field4".equalsIgnoreCase(filedName)) {
            resultSet.add(getField4());
        }
    }
    return resultSet;
}


public String getField1() {
    return field1;
}

public String getField2() {
    return field2;
}

public String getField3() {
    return field3;
}

public String getField4() {
    return field4;
}}

Is there any better way to achieve this as its lot of boilerplate code.

How to deal with exception when building an API wrapper?

I'm trying to build a wrapper for an API. The API can send me all kind of response: 200, 403, 404, 429, 500 now I want my wrapper to be able to handle exceptions, this is my current class:

class API:
    def __init__(self, key):
        self.key = key

    def get_some_object_from_a_endpoint(self):
        call = requests.get("adress_of_a_endpoint&api_key={0}".format(self.key))
        content = call.json()
        my_object = MyClass.build_object_from_api_data(content)
        return my_object

Now I thought about defining a function in my class that will manage all the call and call this function in each of my endpoint, so my class will look like this:

class API:
    def __init__(self, key):
        self.key = key

    @staticmethod
    def check_exception(request):
        if request.status_code == 200:
           return request.json()
        if request.status_code == 404:
            print("Not found")
        ...  # management of other exceptions


    def get_some_object_from_a_endpoint(self):
        call = requests.get("adress_of_a_endpoint&api_key={0}".format(self.key))
        request_result = self.check_exception(call)
        if request_result:
           content = call.json()
           my_object = MyClass.build_object_from_api_data(request_result)
           return my_object
        else:
           return MyClass()

I will use my API wrapper that way:

api = API("my_key")
my_object = api.get_some_object_from_a_endpoint() # Will have the data from the API, the default object or raised some exception depending of the error code

What annoy me with my solution is that for every endpoint I will have the same piece of code:

call = requests.get("adress_of_a_endpoint&api_key={0}".format(self.key))
request_result = self.check_exception(call)
if request_result:
   ...
   return my_object
else:
   return MyClass()

Does my solution respect common design pattern? Is there a better practices for solving this kind of problem?

Mentioning a user with @ using Linkify and regex

I'm currently using the following pattern:

Pattern mentionPattern = Pattern.compile("@([A-Za-z0-9_]+)");

This will find a user named @user for example, but it won't find @user. or @user!hello. I'd like to basically capturing everything until the first whitespace. What pattern can I use to find these kinds of usernames?

samedi 26 août 2017

Reducing code duplication in hibernate sessions

I am developing a REST web service using Jersey and Hibernate with Postgres for the backend. I have 3 packages for models, resources and services each. For each method in services I'm duplicating the code:

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
    transaction = session.beginTransaction();
    ***SOME UNIQUE OBJECT***  = (***SOME UNIQUE OBJECT TYPE***) session.save(***SOME UNIQUE OBJECT***);
    session.getTransaction().commit();
} catch (HibernateException e) {
    if (transaction != null) {
        transaction.rollback();
    }
} finally {
    session.close();
}
return ***SOME UNIQUE OBJECT***;

Can someone advise how I can do this without duplicating this code. I'm thinking of writing an interface for the entity model classes. Then pass that interface to the above code. Not sure if this is the best way to do this.

MVC + REST + nested resources + single page app

I'm a novice, but struggling hard to implement this interactive application I'm working on "the right way" or at least a good way in terms of scalability, maintainability, modularity, development speed and tool independence. That's why I chose the REST design guides and a framework which implements MVC.

However I can't get my head around where to put what in the following situation and any input or reading material from a more experienced developer in this techniques would be greatly appreciated :

I'm developing a single page web app which creates a resource that has several nested resources within. In the create methods and alike, I need to call the create methods from the nested resources. Right now every GET request is responded with a JSON, which the front end then parses, shows and add dynamically to the page accordingly. The question is : where should this create and store methods from nested resources be, in the controller or in the model?

Currently, my approach is : since the controller function is to handle user input, interact with model and return the view accordingly, the nested store methods are in the model since they're not created independently, their create methods are in the controller since they're requested from ajax calls, but this isn't nested, and so on. I'm worried that this is too mixed up and not general.

Am I ok ? Am I mixed up? I don't wanna make a mess for my coworkers to understand. Theory becomes tricky when applied..

module interconnection interface design

I want to have some simple interfaces for the users to connect some pre-defined modules (I'm free to modify them if I have to). Each module has a few named inputs and outputs. One module may connect to a few modules. A few modules can connect to a single module.

This is what I have in my mind so far: Option 1: Each module has "in" and "out" dictionary for input and output, and the connection is made through code like this:

a.out["out 1"].to(b.in["in 1"]) # connect a's "out 1" output to b's "in 1" input
a.out["out 2"].to(b.in["in 2"]) # connect a's "out 2" output to b's "in 2" input

But this looks quite tedious, so I came up with Option 2:

# connect a to b, also a to c, then list which inputs connect to which outputs
a.to(b,{"out 1":"in 1",
        "out 2":"in 2"},
     c,{"out 4":"in 1",
        "out 3":"in 2"})

This seems to look better as it's clearer to me which modules are connected and also the mapping between their outputs and inputs.

I wonder if there is any room to improve the above, to clearly show:

  • module level connections, e.g. module a connect to module b
  • outputs and inputs connections
  • simple and clear interface. By 'simple', I mean less typing; 'clear' means easy to understand. I understand that sometimes I can't have both in that case, 'clear' interface is preferable.

I'm not proficient in Python(2.7) so there might be some syntax or operator or data structure that I am not aware of but I may be able to take advantage for this purpose.

Mapper Class and Reducer Class in MapReduce Design pattern

I am a new guy learning MapReduce design patterns and I have some doubt on this code on the Mapper class and Reducer Class design, I have come here to clear my confusion by your kind help.

I am familier with Map Side Joining in MapReduce and I learned this:

public static class CustsMapper extends Mapper<Object, Text, Text, Text> {
        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {

Here, in the above code snippet I learned that we extends our class to Mapper class and as the Object is a key and Text is a value so map method take this key-value as an input with the context object helps here like this as an output context.write(new Text(), new Text()) as per the design of the logic body of the code.

BUT MY TWO QUESTIONS ARE GIVEN BELOW,

  1. Why we have extended our class to MapReduceBase(what it does?) and why we have implemented our class to Mapper(I knew it's a class but in the web somewhere its showing as an interface so if I extends it to org.apache.hadoop.mapreduce.Mapper<KEYIN,VALUEIN,KEYOUT,VALUEOUT> class what is the problem?
  2. In the map function what does OutputCollector<Text, IntWritable> output, Reporter reporter ?? I didn't know it? I knew that Context context should be here but what is OutputCollector and Reporter here?

I was doing this program given below:

Input:

1979   23   23   2   43   24   25   26   26   26   26   25   26  25 
1980   26   27   28  28   28   30   31   31   31   30   30   30  29 
1981   31   32   32  32   33   34   35   36   36   34   34   34  34 
1984   39   38   39  39   39   41   42   43   40   39   38   38  40 
1985   38   39   39  39   39   41   41   41   00   40   39   39  45 

Code:

package hadoop; 

import java.util.*; 

import java.io.IOException; 
import java.io.IOException; 

import org.apache.hadoop.fs.Path; 
import org.apache.hadoop.conf.*; 
import org.apache.hadoop.io.*; 
import org.apache.hadoop.mapred.*; 
import org.apache.hadoop.util.*; 

public class ProcessUnits 
{ 
   //Mapper class 
   public static class E_EMapper extends MapReduceBase implements Mapper<LongWritable ,Text,Text,IntWritable>       
   {       
      //Map function 
      public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException 
      { 
         String line = value.toString(); 
         String lasttoken = null; 
         StringTokenizer s = new StringTokenizer(line,"\t"); 
         String year = s.nextToken(); 

         while(s.hasMoreTokens())
            {
               lasttoken=s.nextToken();
            } 

         int avgprice = Integer.parseInt(lasttoken); 
         output.collect(new Text(year), new IntWritable(avgprice)); 
      } 
   } 


   //Reducer class 
   public static class E_EReduce extends MapReduceBase implements Reducer< Text, IntWritable, Text, IntWritable> 
   {     
      //Reduce function 
      public void reduce( Text key, Iterator <IntWritable> values, 
         OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException 
         { 
            int maxavg=30; 
            int val=Integer.MIN_VALUE; 

            while (values.hasNext()) 
            { 
               if((val=values.next().get())>maxavg) 
               { 
                  output.collect(key, new IntWritable(val)); 
               } 
            } 

         } 
   }  


   //Main function 
   public static void main(String args[])throws Exception 
   { 
      JobConf conf = new JobConf(ProcessUnits.class); 

      conf.setJobName("max_eletricityunits"); 
      conf.setOutputKeyClass(Text.class);
      conf.setOutputValueClass(IntWritable.class); 
      conf.setMapperClass(E_EMapper.class); 
      conf.setCombinerClass(E_EReduce.class); 
      conf.setReducerClass(E_EReduce.class); 
      conf.setInputFormat(TextInputFormat.class); 
      conf.setOutputFormat(TextOutputFormat.class); 

      FileInputFormat.setInputPaths(conf, new Path(args[0])); 
      FileOutputFormat.setOutputPath(conf, new Path(args[1])); 

      JobClient.runJob(conf); 
   } 
} 

Output:

1981    34 
1984    40 
1985    45 

Tab building logic in Firefox like application

I am building GUI application. My application (Shell) looks like Firefox - there are tabs and there are different components inside each tab. My components are window, modules, layout and etc and they include small elements like buttons, text fields etc. Besides these components I inject using CDI.

My problem is that I can't understand where I should put logic of building such tab. For example I have tab that shows application settings. Fist my attempt was

public class SettingsTab{

  @Inject
  private Window window; 

  @Inject
  private FooLayout layout; 

  @Inject
  private ModuleA moduleA;

  @Inject
  private ModuleB moduleB;
  ....
}

And after that I did

Shell.add(settingsTab);

But this code seems a little bit strange to me. Maybe such logic must be put in some like *Builder or *Manager. Where is such logic put in GUI applications?

Create interface in python

This is related to pattern design in Python, especially interface building. I need to implement generic interface to handle call and dispatch into specialized functions.

I have this code :

def get_batch(func_name_id="", ddict={}, VERBOSE=0):
    if VERBOSE : print( "get_batch: " + func_name_id)
    try :
      return globals()[func_name_id](ddict)     
    except Exception as e:
      print(e)
      print("No batch  available")
      return []

Main reason is this creates a loose interface with history code, and adding new specialized function does not require changing the core part.

Is it a good way to implement interface in python, what are the potential issues I have to face ?

Design pattern for different method signiture

I am new to design pattern.

My question is what pattern do I use in below case?

interface UserExtractorService {
    String getUser(XXXX);
    default validate(File file);
}

class AExtractorService {
    public String getUser(String url) {
           validate(downloadfromWeb(url));
       return getFromWeb(url);
    }
}

class BExtractorService {
    public String getUser(File) {
           validate(file);
           parsingFromFile(File);
       return parsingFromFile(File);
    }
}

class Client {

    public void GetUsers(String key) {
         userExtractorService.getUser(key);
    }

    public void GetUsers(File file) {
         userExtractorService.getUser(file);
    }
}

I want to group AExtractor and BExtractor, because it need operate similar behavior.

Using Ninject with static methods

My goal is to use Ninject in my application with static methods. I am aware of the fact that the static methods should not have any dependencies since it is hard from testing point of view. But, in my application I am not in the position to make each method static to non-static. I need to implement DI with minimal changes, i.e. I should change the code at one lance and it should change the implementation everywhere where that method or class is being called. I don't want to use the Service Locator pattern too, considering that is not even a pure DI pattern.

In order to keep all those above points in my mind, I implemented the following set up and it has been working well. I need your thoughts whether I did it correct or not to use Ninject with static methods.

My ASP.NET WebForms set up:

Solution: NinjectPlayGround

Projects:

NinjectPlayGround (Web Project)
NinjectPlayGround.BL (Business Layer)
NinjectPlayGround.Common (POCO layer)

enter image description here

In order to use Ninject I installed Ninject.Web

NinjectWebCommon.cs Code:

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(NinjectPlayGround.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(NinjectPlayGround.App_Start.NinjectWebCommon), "Stop")]

namespace NinjectPlayGround.App_Start
{
    using System;
    using System.Web;

    using Microsoft.Web.Infrastructure.DynamicModuleHelper;

    using Ninject;
    using Ninject.Web.Common;
    using NinjectPlayGround.Common;
    using NinjectPlayGround.BL;

    public static class NinjectWebCommon 
    {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();

        /// <summary>
        /// Starts the application
        /// </summary>
        public static void Start() 
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);
        }

        /// <summary>
        /// Stops the application.
        /// </summary>
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }

        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            try
            {
                kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

                RegisterServices(kernel);
                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<ILogger>().To<DefaultLogger>();

            // Set static properties
            CommonHelper.Logger = kernel.Get<ILogger>();
        }        
    }
}

I added the following two custom lines there:

        kernel.Bind<ILogger>().To<DefaultLogger>();

        // Set static properties
        CommonHelper.Logger = kernel.Get<ILogger>();

CommonHelper is the class which has static methods where I want to use Logger instance.

CommonHelper class code:

using NinjectPlayGround.Common;

namespace NinjectPlayGround.BL
{
    public class CommonHelper
    {
        public static ILogger Logger { get; set; }

        public static void RunCleanUp()
        {
            // Run clean up
            //.....


            Logger.Log("Clean up done");
        }
    }
}

ILogger class code:

namespace NinjectPlayGround.Common
{
    public interface ILogger
    {
        void Log(string message);
    }
}

DefaultLogger class code:

using System.Diagnostics;

namespace NinjectPlayGround.Common
{
    public class DefaultLogger : ILogger
    {
        public void Log(string message)
        {
            Debug.WriteLine(message);
        }
    }
}

Since Ninject attribute is not allowed on static properties like this:

public static ILogger Logger { get; set; }

I set that property via RegisterServices method present in NinjectWebCommon class which is called only once per application start (correct me if I am wrong here)

        // Set static properties
        CommonHelper.Logger = kernel.Get<ILogger>();

From UI this helper method is called like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ninject;
using NinjectPlayGround.BL;

namespace NinjectPlayGround
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CommonHelper.RunCleanUp();
        }
    }
}

Al the above setup is working fine i.e if I change the DefaultLogger to PersistentLogger (which is another implementation of ILogger)

  kernel.Bind<ILogger>().To<DefaultLogger>();

to

 kernel.Bind<ILogger>().To<PersistentLogger>(); 

I can see PersistentLogger being called instead of DefaultLogger without making any mess/changes in the CommonHelper class.

Is this the correct way to use Ninject with static methods?

Is this how I need to set all static properties which I need to set via DI in RegisterServices method of NinjectWebCommon class?

Will I face any difficulties with this kind of implementation?

vendredi 25 août 2017

Does holding information in a Factory instead of passing it through calling code make sense?

I have a factory which creates objects that are widely used through my application. Some of the objects the factory creates require another dependency. This optional dependency is an interface/class with settings from a local settings file. Currently both the factory interface AND the settings interface are injected into something like 20 classes. Albeit, the number of classes would be less if the applications inheritance tree wasn't about 6-7 levels deep (meaning the IFactory and ISettings get passed through 6 constructors and finally arrive at a base class which assigns them to a field).

The deep inheritance isn't getting changed anytime soon, but I thought that I could lessen the load of these constructors by removing the ISettings from them and putting it in the IFactory implementation itself. The ISettings would be injected into the concrete factory through the constructor, and then instead of passing the ISettings as a part of the Create() method, it would just use the factory ISettings readonly property. These settings are guaranteed to be immutable once the program starts.

Is this frowned upon in any way, and are there better ways of going about this? Some coworkers think that Factories should almost never hold state...but they aren't exactly sure why.

These are similar questions that I found, that gave answers but I'm still looking for a more fleshed out answer if possible.

Adding Properties to Abstract Factory

Abstract Factory Pattern and Properties

Simple example:

interface IObjValidator
{
    bool Validate();
}

interface IObjValidatorFactory
{
    IObjValidator Create();
}

class ObjValidatorFactory : IObjValidatorFactory
{
    // Is it OK for the factory to hold this field?
    private readonly ISettings settings;    

    public IObjValidator(ISettings settings)
    {
        this.settings = settings;
    }    

    IObjValidator Create(ObjValidatorMode mode)
    {
        switch(mode)
        {
             case ObjValidatorMode.One:
                 return ObjValidator1();

             case ObjValidatorMode.Two:
                 return ObjValidator2(this.settings);
        }
    }
}

class ObjValidator1: IObjValidator
{
    public bool Validate()
    {
        // Do stuff.
    }
}

class ObjValidator2: IObjValidator
{
    private readonly ISettings settings;

    public ObjValidator2(ISettings settings)
    {
        this.settings = settings;
    }

    public bool Validate()
    {
        // Use ISettings field data here.            
    }
}

Is this a good case for the Strategy Pattern

I have the following inputs:

  1. A CSV File
  2. An array of grammar rules. The grammar rules are
    basically metadata that tells me what which each column datatype
    should be.

The output would return back to me a list of records that had any errors. So if column should be a date but I'm given the wrong format. I would return those rows.

The csv file would be something like this:

first_name,last_name,dob,age,
john,doe,2001/05/02
mary,jane,1968/04/01

Metadata:

column:first_name
type:string

column:dob
type:date

I was wondering if the strategy pattern would be the right choice. I was thinking of injecting the proper grammar (metadata) depending upon the file. I have multiple files I want to validate.

How to approach strategy design in OOP. [migrated]

My class pseudo code is in the following format:

public class Config {
    final private Map<String, TableSchema> schemas;

    public Config() {
        schemas = parseSchemas();
    }
    public TableSchema getSchema(String tableName) {
        TableSchema tableSchema = schemas.get(tableName);
        if(/*Based on certain conditions*/) {
            return new TableSchema(/*Pass some values*/)
        }
        return tableSchema;
    }
    Map<String, TableSchema> parseSchemas() {
        //Read some config files 
        tableSchema = new TableSchema(/*Pass some values based on the read config files*/);
        schemas.put(tableName, tableSchema);
    }
}

public class DBOperations {
    private final TableSchema schema;
    public DBOperations(Config config, String tableName) {
        schema = config.getSchema(tableName);
    }
}

public class TableSchema {
    method1();
    method2();
}

To access the TableSchema methods in DBOperations, all I needed to do was call schema.method1() and so on. However now I need to have multiple implementations of DBOperations which may not all have the same TableSchema methods to operate on (function name might be the same, but implementation is different). For this I was thinking of making a TableSchema interface and have multiple implementations of it based on my requirements along the lines of strategy pattern.

However if I use the strategy pattern, I will need to pass the constructor as well. However the values of the class TableSchema depends on the values I retreive in the class Config. How should I approach my design in this case?

C# Generic Parent Children Definition

I'm trying to design a parent/children definition in C#, but receive some compilation errors, which are not clear for me:

namespace TestProject1
{
    public abstract class BaseElement
    {
    }

    public abstract class Child<T> : BaseElement
    {
        public BaseElement Parent { get; set; }
    }

    public abstract class Parent<T> : BaseElement
    {
        public IQueryable<BaseElement> Children { get; set; }
    }

    public abstract class ParentChild<TParent, TChild> : BaseElement 
        where TParent : Parent<BaseElement> 
        where TChild : Child<BaseElement>
    {
        public void AddChild(TChild child)
        {
            child.Parent = this;
        }
    }

    public class Root : Parent<Trunk>
    {
    }

    public class Trunk : ParentChild<Root, Branch>
    {
    }

    public class Branch : ParentChild<Trunk, Leaf>
    {
    }

    public class Leaf : Child<Branch>
    {
    }
}

One of the compilation errors is in line public class Trunk:

Error CS0311 The type TestProject1.Root cannot be used as type parameter TParent in the generic type or method ParentChild<TParent, TChild>. There is no implicit reference conversion from TestProject1.Root to TestProject1.Parent<TestProject1.BaseElement>.

But in fact there is a path from Root to Parent<BaseElement> as Root inherits from Parent<Trunk> and Trunk is a BaseElement due to the fact that BaseElements inherits from ParentChild, which is a direct successor from BaseElement.

The other compilation errors are similar, but for the Branch type in Trunk and the Trunk and Leaf parameters of Branch.

Impelementing real life Command design pattern

Its not a duplicate, since it is a real life project. I have several Xml files. Every entry in all of them have id and name tags. Some others have extra like type, date and so on. I have a base parser class which makes objects form xml files. The example xml files are:

food.xml and some others just have id and name:

<foods>
    <food>
        <id>1</id>
        <name>bread</name>
    </food>
</foods>

some files have extra tags:

<treatments>
        <treatment>
            <id>1</id>
            <name>pill</name>
            <type>daily</type>
        </treatment>
</treatments>

The base parser class that extracts id and name for xml files is:

public class PreDefinedEffectiveParser extends XmlHelper {
    public PreDefinedEffectiveParser(String xml_string) {
        super(xml_string);
    }

    protected <T extends PreDefinedEffectiveDataModel> List<T> parse(Class<T> cls, String tag_name) {
        List<T> result = new ArrayList<>();

        NodeList treatmentList = document.getElementsByTagName(tag_name);
        for(int i=0; i<treatmentList.getLength(); i++){
            Element element = (Element) treatmentList.item(i);

            try {
                T dataModel = cls.newInstance();
                try {
                    dataModel.setName(getValue(element, "name"));
                } catch (Exception ex) {
                }
                try {
                    dataModel.setId(Long.parseLong(getValue(element, "id")));
                } catch (Exception ex) {
                }
                result.add(dataModel);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        return result;
    }
}

and FoodParser which extends base parser is:

public class FoodParser extends PreDefinedEffectiveParser {
    public FoodParser(String xml_string) {
        super(xml_string);
    }

    public List<FoodDataModel> parse(){
        return parse(FoodDataModel.class, "food");
    }
}

For the parser classes which have extra tags, i rewrite the parse() method that takes a lot of time and is cumbersome and most of them are copy of base class's parse() method. like:

public class TreatmentParser extends PreDefinedEffectiveParser {
    public TreatmentParser(String xml_string) {
        super(xml_string);
    }

    public List<TreatmentDataModel> parse(){
        List<TreatmentDataModel> result = new ArrayList<>();

        try {
            NodeList treatmentList = this.document.getElementsByTagName("treatment");

            for (int i = 0; i < treatmentList.getLength(); i++) {
                Element treatElem = (Element) treatmentList.item(i);
                TreatmentDataModel dataModel = new TreatmentDataModel();

                try {
                    dataModel.setId(Long.parseLong(getValue(element, "id")));
                } catch (Exception ex) {
                }

                try {
                    dataModel.setName(getValue(treatElem, "name"));
                } catch (Exception ex) {}

                try {
                    TreatmentType type = TreatmentType.factory(getValue(treatElem, "type"));
                    dataModel.setTreatmentType(type);
                } catch (Exception ex) {}

                result.add(dataModel);
            }
        }
        catch (Exception ex) {}

        return result;
    }
}

Since I have lots of different xml files with variable number of tags, how can i use command pattern to faciliate setting Data model objects easily like this:

public class TreatmentParser extends PreDefinedEffectiveParser {
    List<String> tags = new ArrayList<>();
    List<FunctionPtr> methods = new ArrayList<>();

    public TreatmentParser(String xml_string) {
        super(xml_string);

        // The trick is hear
        tags.add("id");
        methods.add(TreatmentDataModel.setId);  // <== Excuse me!

        tags.add("name");
        methods.add(TreatmentDataModel.setName);

        tags.add("type");
        methods.add(TreatmentDataModel.setType);
    }

    public List<TreatmentDataModel> parse(){

    for ( int i=0; i < tags.size(); i++ ) {
        invoke_function( methods.get(i) ) with parameter getValue(tags.get(i));
    }

    return some result;
}

Note: I don't want to use lambda or reflection. I want to implement by Command pattern to deeply understand it. Thanks in advanced.

Singleton design pattern java idioma

I'm quite confused. I found many implementations of the Singleton Design Pattern in java. One of the implementations I found is the following:

public class MySingleton {

    private static class Loader {
        static MySingleton INSTANCE = new MySingleton();
    }

    private MySingleton () {}

    public static MySingleton getInstance() {
        return Loader.INSTANCE;
    }
}

as explained here: http://ift.tt/1jBnDYz. Now, if this implementation should work, why doesn't the following?

public class MySingleton {

    private static final MySingleton INSTANCE = new MySingleton();

    private MySingleton () {}

    public static MySingleton getInstance() {
        return INSTANCE;
    }
}

I searched around how java handles initializations, but couldn't find anything showing the latter code will not work. Instead, I found the following: stackoverflow.com, which points out that every static initialization happen before a static method of the class is invoked, so the static field holding the singleton instance should be initialized when the only method accessing INSTANCE (getInstance) is invoked. So yes, i'm really confused: if this code works, why not using this simpler version of the singleton design pattern?

How can the pattern (01001100011100001111...) be visually represented in Java (Or Elsewhere)?

I will start by describing how I discovered this pattern myself, but this information isn't directly relevant to understanding the pattern itself. If you prefer to skip the next paragraph that perfectly fine. So I was meditating under an apple tree in an orchard which is practically on my campus. There were many flies around. At first when they were flying around my nose I would shew them away, but eventually I decided to let them be. Why? Because I thought it would be a zen thing to do. At first the fly seemed to be crawling around my nasal area randomly, but then a pattern emerged. I noticed the fly went around my left nostril once, right once, left twice, right twice. At this point I decided to count these as 0's and 1's. Around this time the fly went in and out of the very edge of my left nostril three times and then the right three times. What message does the fly have for me? 010011000111... Allow that I chose to read these binary numbers from left to right in this regard. In thinking about this pattern I decided there were two main ways to interpret it. The first involves looking at the whole thing as one large number. The first 0 shows a 0 in the 1 place. The 1 place has a 1. Next is a 0 in the 4 and 8 place. And then a 1 in the 16 and 32 place. The second method involves looking at the numbers as a sequence. The first number is 01 in Binary or 2 in human. And then 0011 or 12. Next is 000111 or 56. On a graph every integer starting from makes up the X values. Using the last example allow 000111 and 56 to be Y. A third variable is Z. For any given X, Z=(The Y value of X+1)-(The current Y value associate with X). This allows one to track the rate of change. Just to see if there are more variables that may have something interesting to say, A=Z/X. B=Z/Y. C=X/Y. D=A/B. E=B/C. F=C/D. G=D/E. Etc. Attached are some images of some work I did with this pattern on a Whiteboard. You might be saying to your self, "but what exactly do you want from me?" Well I would like to see if some of these variables have interesting relationships when represented visually. I will add that the only reason I request Java is because I am most familiar with it. Does another language exist that might be more appropriate? Yes.enter image description here The first version or interpretation with a table of the data. The right side of the board. It shows the second interpretation's data and a chart.

Java Regex Match and Replace matched group with characters of same length

So I want to match credit card numbers and mask them in 6*4 format. So that only first 6 and last 4 characters will be visible. The characters between will be '*'. I tried to figure it out with a MASK like;

private static final String MASK = "$1***$3";
matcher.replaceAll(MASK);

But could not find out the way to give me back equal length of stars in the middle as the group $2.

Then I implemented the below code and it works. But what i want to ask if there is a shorter or easier way to do this. Anyone knows it?

private static final String HIDING_MASK = "**********";
private static final String REGEX = "\\b([0-9]{6})([0-9]{3,9})([0-9]{4})\\b";
private static final int groupToReplace = 2;

private String formatMessage(String message) throws NotMatchedException {
    Matcher m = Pattern.compile(REGEX).matcher(message);

    if (!m.find()) throw new NotMatchedException();
    else {
        StringBuilder maskedMessage = new StringBuilder(message);
        do {
            maskedMessage.replace(m.start(groupToReplace), m.end(groupToReplace), 
                    HIDING_MASK.substring(0, (m.end(groupToReplace) - m.start(groupToReplace))));

        } while(m.find(m.end()));

        return maskedMessage.toString();
    }
}

jeudi 24 août 2017

Is it better Step Builder pattern or a Builder pattern with overload constructor for mandatory parameters?

Is it better Step Builder pattern or a Builder pattern with overload constructor for mandatory parameters?

Hi, guys, I have the following scenario, I should do a refactor in a method, where the method receive a new parameter, in this case the method have 4 parameters, and some cases one of this parameters, it is sending null, and 3 are mandatory. I don't want to use in method with 4 parameters by readability, I think use a Builder for this case to build a Object like argument, and the method has 3 method mandatory, I have two alternatives:

1. Use a builder with overload constructor, like this:

new Builder(param1, param2, param3).text("hello").build()
new Builder(param1, param2, param3).build()

2. Use a Step Builder, where the builder can create the object only if the 3 parameter mandatory were implemented, another case it can't build the object. like this:

new Builder().param1(param1).param2(param2).param3(param3).text("hello").build()
new Builder().param1(param1).param2(param2).param3(param3)..build()

But never it can't build the object if it don't implement the 3 parameters mandatory:

new Builder().param1(param1).param2(param2).build() ( invalid execution in IDE)

what is the better option?

thank for your attention.

Compatible code of format function in Java

How Can I replace this line String str = String.format("%d\t%f", count, total); Actually this is a Reducer class of a MapReduce join. I want to replace this line with any other compatible code like simple assignment of two strings count and total. Is it possible?

public static class ReduceJoinReducer extends Reducer<Text, Text, Text, Text> {
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
    String name = ""; //For Cust ID
    double total = 0.0; // For Amount Count
    int count = 0; // For Visit Count
    for (Text t : values) {
        String parts[] = t.toString().split("\t");
        if (parts[0].equals("tnxn")) 
        {
            count++;
            total += Float.parseFloat(parts[1]);
        }
        else if (parts[0].equals("cust")) 
        {
            name = parts[1];
        }
    }
    String str = String.format("%d\t%f", count, total);
    context.write(new Text(name), new Text(str));
}
}

CoreData - Making Objects That May Or May Not Be Stored

I have an existing iOS project which I'm trying to change to use CoreData instead of Keyed Archiving. In my existing project, I often create objects when the user closes a modal view. Then I do some validation on that object, and if all is well I go ahead and store it. But if the object is determined to be invalid, I simply throw it away and throw up a validation message to the user.

I got nervous about this pattern when I started using Core Data. I didn't want to keep creating "temporary" objects in my database only to turn around and delete them. So instead I create the objects without assigning them to a NSManagedObjectContext. Then later when I determine things are valid, only then do I assign it to a context.

At last here's the question: Is this a valid approach? Are things commonly done this way? I'm worried as my use of managed objects gets more complicated, with more relationships between entities, that I may regret this choice. Am I unnecessarily making things harder for myself?

divide list of sublist based on patter in sublist[0]

I have 2 lists of int and sparse matrix : list_index = [1,1,2,3,3,4,4,5] and matrix_user = [sparse1, sparse2, sparse3, sparse4, sparse5, sparse6]

I want to have a list of sublist, each sublist is made of a list of int and a sparse matrix : [ [[1,1,2,3,3],[sparse1, sparse2, sparse3, sparse4]] , [[4,4,5],[sparse5, sparse6]] , ......] of length ~ 90 (to run in parallel later one) whith each sublist[0] containing not overlapping value.

To cut the 2 input lists into 90 sections I do the following :

        # cut the data into chunk to run in parallel
        list_index = dfuser['idx'].tolist()
        matrix_user = encoder.fit_transform(dfuser[['col1','col2']].values)
        sizechunk = 90
        sizelist = int(len(list_index)/sizechunk)
        if len(list_index)%sizechunk!=0 : sizelist += 1

        list_all = []
        for i in range(sizechunk) :
            if i*sizelist > len(list_index) : continue
            if (i+1)*sizelist < len(list_index) : list_all.append(  [list_index[i*sizelist:(i+1)*sizelist] , matrix_user_encoded.tocsr()[i*sizelist:(i+1)*sizelist] ]  )
            else : list_all.append( [list_index[i*sizelist:] , matrix_user_encoded.tocsr()[i*sizelist:] ])

This give me a list of 90 chunks : [ [[1,1,2,3],[sparse1, sparse2, sparse3]] , [[3, 4,4,5],[sparse4, sparse5, sparse6]] , ......]

Then I filter in order each sublist have different index value :

        i=0
        size_list = len(list_all)
        while i<size_list-1 :
            last_elem = list_all[i][0][len(list_all[i][0])-1]
            first_elem = list_all[i+1][0][0]
            first_sparse = list_all[i+1][1][0]
            while first_elem==last_elem :
                list_all[i][0].append(first_elem)
                list_all[i][1] = sp.vstack((list_all[i][1],first_sparse))
                list_all[i+1][0] = list_all[i+1][0][1:]
                list_all[i+1][1] = list_all[i+1][1][1:]
                if len(list_all[i+1][0])==0 :
                    list_all.remove(list_all[i+1])
                    size_list -= 1
                    if i+1==size_list : break
                first_elem = list_all[i+1][0][0]
            i +=1

It works but as I have lots of input (~18 millions entries) it takes 6h !!!!!

I need my program to run in less than 2h as it needs to be called multiple times a day. Does a python command exists to cut my 2 lists depending on the pattern of the first sublist ?

Thank you for your help!

Floyd's triangle with a twist

The program is to print a floyd's triangle(right angled triangular pattern with natural numbers) but the alternate rows should have the numbers in reverse ie In the second row 2 3 should become 3 2 The fourth row will have 10 9 8 7 instead of 7 8 9 10. The odd rows will have the numbers printed in the expected order only . please help


Design pattern in RESTful Android applicaton

In my app, which has tabbled activity with four tabs [ tab1 | tab2 | tab3 | tab4 ]. Pic shown is not of my app, but to get a feel how it might look similar to although there are differences as mentioned here.

enter image description here

  1. Each tab is associated with a fragment. Each fragment is list, either in vertical list or grid.
  2. Tab1 and Tab2 has list of similar objects(X), restaurants.
  3. Tab3 has different class object list (Y), friends.
  4. Tab4 has object list and each object is superset of object(X) + object (Y). Restaurants and my friends who visited there.
  5. Each of these tab content are different and obtained through RESTful http call.

Now, my query is:

  1. Should I put all view class, X, Y, X+Y in factory pattern?
  2. Should I put REST api call into observer pattern with callback on data receive?

Am I correct with this approach or should I chose different pattern to make things even improved?

How to implement Memento Pattern in Kotlin

I am currently trying to implement some design patterns in Kotlin as an exercise and I'm a bit stuck with the 'Memento' pattern. My reference resource is SourceMaking: Memento.

I want to implement this structure:

Class diagram of 'Memento' Design Pattern

While following their "Checklist"

  1. Identify the roles of “caretaker” and “originator”.
  2. Create a Memento class and declare the originator a friend.
  3. Caretaker knows when to "check point" the originator.
  4. Originator creates a Memento and copies its state to that Memento.
  5. Caretaker holds on to (but cannot peek into) the Memento.
  6. Caretaker knows when to "roll back" the originator.
  7. Originator reinstates itself using the saved state in the Memento.

I can't get step 5 to work. How do I make a Memento object whose fields can be read from inside the Originator instance but that is completely opaque to the Caretaker?

I have successfully implemented this in Java as follows:

public class Originator {

    private final int id;
    private String title;
    private String description;

    public Originator(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Memento saveState() {
        return new Memento(new State(id, title, description));
    }

    public void restore(Memento memento) {
        id = memento.state.id;
        title = memento.state.title;
        description = memento.state.description;
    }

    private class State {
        private final int id;
        private final String title;
        private final String description;

        public State(int id, String title, String description) {
            this.id = id;
            this.title = title;
            this.description = description;
        }


    }

    public class Memento {

        private final State state;

        public Memento(State state) {
            this.state = state;
        }
    }
}

And a Caretaker

public class Caretaker {

    public Originator originator;

    public Caretaker(@NotNull Originator originator) {
        this.originator = originator;
    }

    public Originator.Memento save() {
        return originator.saveState();
    }

    public void restore(@NotNull Originator.Memento memento) {
        originator.restoreFromState(memento);
    }
}

Because they are inner classes I can read the private fields of Memento and State from my Originator instance, but to the Caretaker my Memento instance is completely opaque (only showing Objects member functions).

Now how do I implement this exact behavior in Kotlin? Basically I am missing the functionality of reading private fields of inner classes.

The closest thing I could think of was this:

class Originator(id: Long) {

    private var id: Long = id
    var description: String = ""
    var title: String = ""

    fun saveState() = Memento(State(id, title, description))

    fun restoreState(memento: Memento) {
        id = memento.state.id // <-- cannot access 'state': it is private in 'Memento'
        title = memento.state.title // <-- cannot access 'state': it is private in 'Memento'
        description = memento.state.description // <-- cannot access 'state': it is private in 'Memento'
    }

    inner class State(private val id: Long,
                  private val title: String,
                  private val description: String)

    inner class Memento(private val state: State)
}

This has the desired effect of Memento being completely opaque to my Caretaker instance, but I can't read the fields from within Originator either.
This code by the way is almost exactly the same as the generated code produced by the 'Convert Java to Kotlin' feature of IntelliJ applied to my Java code (and it obviously doesn't compile either).

So is there something obvious (or magical) I am missing here? Maybe something other than the structure displayed in the class diagram? Or can these exact specifications just not be implemented in Kotlin?

And on another note: Is the requirement of opaqueness for the Memento object actually a colloquially accepted property of the Memento Pattern or did SourceMaking come up with this requirement?

Looking for a systematic method of efficiently abstracting inline styles

I am a junior-mid level developer.

I recently started a new job and I am tasked to essentially scrape an entire CRM project that has a huge majority of its styling done inline.

Objective: Clean out the inline styling to a shared folder that contains the .css file.

Problem: 50-100 of files that contain components with inline styles.

Goal: Adopt a systematic method to efficiently abstract the inline styles. While bringing some structure to this project.

Thoughts on any good methods of doing this?

How to better specify kindo fo ID in RESTful service

I'm looking for an opinion about defining contract for standard GET/PUT/POST/DELETE methods.

We have resource, let's say Client, so route will be /clients

However, we have two types of id for the client. One is the ID generated by our system. On top of that we want optionally allow customers use external id, generated by customer themselves.

So, if customer never going to add clients to the system, don't really interested about integration, and need only use method GET to read customer, endpoint will be:

/clients/{id}

However, if they want full integration, with ability to add clients, and use some their id, we want give them ability to use their own id.

We considered four possible solutions:

1. /clients/external/{externaId}
2. /clients/ext-{externalId}
3. /clients/{externalId}?use-external-id=true
4. /clients/{externalId} with additional header -"use-external-id": true

We are leaning to options 3 and 4 (can be supported simultaneously) but concerns about "restfulness" of such approach. Any opinions on this? What would you choose and why?

best way to deal with drupal custom field language when using services

Drupal custom field structure accepts the values as a language field object that contains and array of the actual field and when using drupal as a backend for example and the typescript as a front end, the language field structure will make a real challenge to set/get the values from the object which you must send to drupal. for example drupal accepts the node object this way :

{
  title: "my title",
  type: "article",
  field_myfield:
  {
    und:
    [
      {
        value: "test value",
        format: "filtered_html" 
      }
    ]        
  }
}

so the language field "und" will be changed to match the language key that you need to create the node for.

The question is: What is the best OOP design pattern to dynamically change the language key, setting, getting the field values and support for multi values fields?

Multiple properties in same ECS component

I understand the ECS pattern and what it aims to solve. However I'm struggling to find the best way to identify the components.

For example, I'm working on a game where you have a ship and you can attack other players/npc and collect resources.

Do I need to have a component for each property or can I group apparently unrelated properties in the same component?

E.g, with a component per property it would look like this:

// Components
Position {
    int x, y;
}
Velocity {
    int speed;
    double direction;
}
Sprite {
    Image[] images;
}
Health {
    int health;
}
Name {
    String name;
}
Resource {
    // Tag for resources.
}

// Entities
MapEntity {
    Position position;
    Sprite sprite;
}
ResourceEntity {
    Position position;
    Sprite sprite;
    Resource resource;
}
ShipEntity {
    Position position;
    Sprite sprite;
    Velocity velocity;
    Health health;
    Name name;
}

With multiple components per property it would look like this:

// Components
MapObject {
    int x, y; // Position
    Image[] images; // Sprite
}
Resource {
    // Tag for resources
}
Velocity { // separated component for static map entities
    int speed;
    double direction;
}
Ship {
    int health
    String name;
}

// Entities
MapEntity {
    MapObject mapObject;
}
ResourceEntity {
    MapObject mapObject;
    Resource resource;
}
Ship {
    MapObject mapObject;
    Velocity velocity;
    Ship ship;
}

I don't think it will make a difference, but I'm using LibGDX's Ashley framework.

What's the best practice to structure exception messages?

When something goes wrong in your program, you can throw an exception in your code with a message that describes a problem. Typical example:

throw new Exception("Houston we have a problem");

Is it a good practice to pass a hardcoded string into an exception constructor? Maybe I should hold all of exception messages in a one place. Please tell me what's the best practice to solve a problem of exception message structuring.

How to avoid duplicate code with generated classes from different packages

We generate Java classes based on two XSD files. The classes land in their package respective to the XSD file (a and b). The methods we would like to use of the generated classes are the same. But they don't implement an interface or a super class. We do not have control over the XSD, it's provided.

Example:

package code.generated.a;
class X {
  void do() {...}
}

package code.generated.b;
class X {
  void do() {...}
}

We would now like to use those classes in our own written code, but would not like to duplicate it.

So as of now we have to consume the interfaces by duplicating the code:

package code.ours.a
class Consumer {
  void use(code.generated.a.X x) {...}
}

package code.ours.b
class Consumer {
  void use(code.generated.b.X x) {...}
}

What is the recommended way of resolving the duplicate code?

Implicit interfaces of Go come to mind, but we're dealing with Java. Is there a way to this with generics?

Factory Method pattern - what for this pattern is necessary?

I have abstract class-factory Factory with factory-method getProduct() and his child classes.

I have abstract class-product Product and his child classes.

Classes-factories created objects of classes-products.

abstract class Factory {
    abstract function getProduct();
}
class FirstFactory extends Factory {
    public function getProduct() {
        return new FirstProduct();
    }
}

abstract class Product {
};
class FirstProduct extends Product {
}

In result I can use this client code:

$factory = new FirstFactory();
$firstProduct = $factory->getProduct();
$factory = new SecondFactory();
$secondProduct = $factory->getProduct();

Question: what for this pattern is necessary? Because in client code I just can use direct classes:

$firstProduct = new FirstProduct();
$secondProduct = new SecondProduct();