mercredi 31 janvier 2018

Square pattern java

Create void method that will put on screen square with patern like that :

  xoxo  
  xoxo   
  xoxo   
  xoxo

First argument of the method will define amount of characters used to create a square side, second which character is first.

This is my solution but im wondering if i can do it with less code.

static void square(char a, int b) {
 if (a == 'x') {
        for (int i = 0; i < b; i++) {

            int sum = 0;
            do {


                System.out.print("x");
                sum++;
                if (sum == b)
                    break;
                System.out.print("o");
                sum++;

            }
            while (sum != b);

            System.out.println();
        }

    } else {
        for (int i = 0; i < b; i++) {

            int sum = 0;
            do {


                System.out.print("o");
                sum++;
                if (sum == b)
                    break;
                System.out.print("x");
                sum++;

            }
            while (sum != b);

            System.out.println();
        }
    }
}

Routing Logic/Design Patten In REST API where Multiple Admin Systems Exist

My organization is moving to a REST architecture and I have a small problem to solve. I'm sure it's been solved a million times so thanks in advance for sharing your experience.

I have two admin systems that host products/resources of the same type and so I use a common pattern of an aggregator collection resource with each element of the payload containing a HATEOS link to the instance resource from that element. Here is the URI pattern in the current design.

Collection Resource URI v1/line-of-business/product-line/business-process/product-resources

Instance Resource URI v1/line-of-business/product-line/business-process/product-resources/resource-uuid/product-resource

Using this URI pattern, the resource will make a call to a uuid Mgmt service to decrypt the resource id to use as a query parameter in the back end to build the resource object. The problem is, the instance resource API doesn’t have any context to know which admin system the resource is hosted on. A couple of other work streams made the following suggestions to resolve this issue and route the instance resource to the correct admin system:

  1. query system A first and if the result is empty, then make a call to system B but we agree this is an bad practice that I don’t want to implement this as a strategic solution.

  2. Create a convenience service that will lookup the admin system and based on results route to appropriate data layer. This is a lot of Extra DB traffic.

  3. one idea was to concatenate the admin system with the UUID and have some parsing logic on the service to know which admin system to point to. to me, that's bastardizing the UUID which is intended to obfuscate the resource id which is the key to my backend system and not be a catch all for meta data to control some switch logic. It also tightly couples us to that UUID mgmt backend. I think UUID should live in the source system.

FYI, system A will be retiring but not for a few years and we all know how those plans go. It could be around for many years when they start estimating the cost of the data conversion and retirement and further, our business is looking at going with some third party distribution models that could potentially introduce new backend admin systems that we'll have to code for. Using the above routing logic, if we add a third admin system, we’d have to modify our routing logic to check the new system as well.

I can’t find any examples of this problem but I know it’s been solved many times. Are the above lookup/routing solutions common? Even if the answer is "yes, they are common", does that make them best practice or utilization of good design principals? Anyone have any best practices they've executed to solve this issue? I’m new to REST design patterns and with my limited experience I proposed the solution below but it wasn’t received well. I proposed to add an admin system identifier as a path parameter in the URL. For example:

Instance Resource URI v1/line-of-business/product-line/business-process/product-resources/{admin-system}/{resource-uuid}/product-resource

I thought by adding the admin system as a path parameter in the URL, we don’t have to make any extra DB calls. The resource mediator can route to the appropriate data layer based on path parm. This also allows us to add new admin systems on the fly. After all, it is the "Unified Resource LOCATOR."

I know this would work but can anyone explain why this would be bad design or poke holes in it? Our clients don't need to know the admin system because we provide it in a HATEOS link from the collections resource. They always call the collections resource first using some header context to get the UUID of the resource they need. And these are all private APIs (internal to organization but exposed to other enterprise and customer facing applications).

sorry for the long explanation/question. Interested in discussing this if you need any more details.

multilevel inheritance - use without casting

Below is the class structure to check the Rule.

RuleBase, RuleResultBase, and IDisplayType are the base classes and interfaces.

RuleTypeA, RuleResultTypeA, and DisplayTypeA are always used together.

When implementing the Run function of RuleTypeA, always use Casting to use DisplayType. I think something is uncomfortable structure. Is not there a good way?

public interface IDisplayType
{
}

public class DisplayTypeA : IDisplayType
{
}

public class DisplayTypeB: IDisplayType
{
}

public abstract class RuleBase
{
    public RuleResultBase Result { get; set; }

    public abstract void Run();
}

public class RuleResultBase
{
    public IDisplayType DisplayType { get; set; }
}

public class RuleResultTypeA: RuleResultBase
{
    public RuleResultTypeA()
    {
        DisplayType = new DisplayTypeA();
    }
}

public class RuleTypeA : RuleBase
{
    public override void Run()
    {
        base.Result = new RuleResultTypeA();

        /// Should I always use this Casting?
        var displayType = base.Result.DisplayType as DisplayTypeA;            
    }
}

public Main()
{
    var rules = new List<RuleTypeA>();
    rules.Add(new RuleTypeA());
    rules.Add(new RuleTypeA());
    foreach(var rule in rules)
    {
        rule.Run();
    }
}

In addition, I've thought of using Generic, but in actual implementation, RuleBase has many variables besides DisplayType. So it does not look good.

public abstract class RuleBase<TDisplayType>
{
    public RuleResultBase<TDisplayType> Result { get; set; }

    public abstract void Run();
}

public class RuleResultBase<TDisplayType>
{
    public TDisplayType DisplayType { get; set; }
}

public class RuleResultTypeA: RuleResultBase<DisplayTypeA>
{
    public RuleResultTypeA()
    {
        DisplayType = new DisplayTypeA();
    }
}

Is it a good practice to preallocate an empty dataframe with types?

I'm trying to load around 3GB of data into a Pandas dataframe, and I figured that I would save some memory by first declaring an empty dataframe, while enforcing that its float coulms would be 32bit instead of the default 64bit. However, the Pandas dataframe constructor does not allow specifying the types fo multiple columns on an empty dataframe.

I found a bunch of workarounds in the replies to this question, but they made me realize that Pandas is not designed in this way.

This made me wonder whether it was a good strategy at all to declare the empty dataframe first, instead of reading the file and then downcasting the float columns (which seems inefficient memory-wise and processing-wise).

What would be the best strategy to design my program?

Interface with DB Facade in Laravel

First, I apologize if this is a stupid question. I recently read an article about repository design pattern and I have a problem when making interface implementation for Laravel Query Builder (Illuminate\Support\Facades\DB).

DatabaseService.php

use Modules\Core\Interfaces\IDatabase;
use \DB;

class DatabaseService implements IDatabase
{  
  protected $db;

  public function __construct(DB $db)
  {
    return $this->db = $db;
  }

  public function select($str)
  {
    $this->db::select($str);
    return $this->db;
  }

  public function table($tableName)
  {
    $this->db::table($tableName);
    return $this->db;
  }

  ...
}

IDatabase.php

<?php namespace Modules\Core\Interfaces;
interface IDatabase
{
  public function select($str);
  public function table($tableName);
  public function raw($rawQuery);
  public function transaction($callback);
  public function first();
  public function get();
}

CoreServiceProvider.php

...

public function register()
{
  ...
  $this->app->bind('Modules\Core\Interfaces\IDatabase', function($app) {
    $db = $app->make(DB::class);

    return new DatabaseService($db);
  });
  ...
}

And this is my query:

$badges = $this->db->table('mailbox as a')
          ->select($this->db->raw(
            "SUM(a.type = 'inbox') as inbox, 
             SUM(a.is_read = 0 AND a.type = 'inbox') as unread,
             SUM(a.type = 'sent') as sent,
             SUM(a.type = 'draft') as draft,
             SUM(a.type = 'outbox') as outbox,
             SUM(a.type = 'spam') as spam,
             SUM(a.type = 'trash') as trash,
             SUM(a.is_starred = 1) as starred"
          ))
          ->first();

With error message :

[2018-01-31 13:45:04] local.ERROR: Call to undefined method Illuminate\Support\Facades\DB::select() 
{"userId":1,"email":"info@narpandi.com","exception":"[object] 
(Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call 
to undefined method Illuminate\\Support\\Facades\\DB::select() at 
/var/www/personal-
website/app/Modules/Mailbox/Repositories/MailboxRepository.php:86)

How to do this correctly? Thank you for your kind help.

Suitable design pattern for event management

We have a modular architecture, in which every module works as an event generator as well as event observer. It is possible that a module can generate multiple events at same time.

We can have two architecture for handling events:

  1. Maintain an observer list for different type of events and call their handlers one by one.

    class Module{
        vector<Module*> event_observer_list[CNT_OF_EVENTS];
        int register(Module* observer, int event_type){
            event_observer_list[event_type].push_back(observer);
        }
        void generate_event(list_of_event_indices){
            for(auto event_index : list_of_event_indices){
                for(auto i : event_observer[event_index])
                    event_observer_list[event_index][i]->handler(some_params);
            }
        }
        int handler(some_params){
            ...
        }
    };
    
    

    In this case we will have to call same observer function handler() multiple times for multiple events. Even if we write separate handlers for each event, we may have to perform some common task (like getting an object from a synchronized map) in each call, which makes this architecture enefficient.

  2. Maintain an observer list common for all events. We will call each module's handler one by one. If a module is not looking for some specific event then it will just skip the processing.

    class Module{
        vector<Module*> event_observer_list;
        int register(Module* observer){
            event_observer_list.push_back(observer);
        }
        void generate_event(list_of_event_types){
            for(i = 0 to event_observer_list.size()){
                event_observer_list[i]->handler(some_params, list_of_event_types);
            }
        }
        int handler(some_params, list_of_event_types){
            ...
        }
    };
    
    

    This architecture is also enefficient because, it is making us to call some unnecessary handlers.

Please provide any possible optimization in the existing architectures or give a totally different design solution.

Patterns with special characters in Microsoft.VisualBasic.CompilerServices.LikeOperator.LikeString does not work

I have tried to use the LikeOperator.LikeString functionality for pattern matching as shown below:

    // Usage: bool matchValue = LikeOperator.LikeString(string, pattern, CompareMethod);
    bool match = LikeOperator.LikeString("*test*/fe_quet", "(*)test(*)/*", Microsoft.VisualBasic.CompareMethod.Text);

The above should return true as per the documentation, but it simply returns false. I tried to escape the (*) with the brackets, but it does not seem to work in that way. Could anyone please help me to define the pattern string with the special characters?

Thanks

Designing a Core Data model to remember previous object states

Let's say we have a simple Core Data model which keeps track of transactions a bunch customer makes, but for some reason, when we look at transactions, we want to know the customers address at the time the transaction was made.

If the customer changes their address, what is the best way to store the old state of the customer?

Data model design

One way might be to store the customer's address on the transaction, but that wouldn't work with to-many relationships, e.g. if prices of multiple products in a previous transaction changed, how would we record that?

Another option would be to just duplicate the objects, but then we need some way of knowing which is the current one. Would It be better to create intermediary entities which are related to both the transaction and the customer/product?

C++ Model View Design

I am currently struggling with the design of an application of the visualization and manipulation of sensor data. I have a database that contains several STL-containers with measured data in it.

std::unordered_map<std::string, std::array<uint16_t, 3366>> data1;
std::unordered_map<std::string, QImage> data2;
std::unordered_map<std::string, std::vector<Point3D>> data3;

I also have different Views (mostly Qt-based) and each view should be associated with a model which is specific to one of the data sets. So data1 is supposed to be processed and manipulated in a class called model1 which is then displayed by means of a class view1 and so forth.

But I cant seem to find a suitable design structure to incorporate this idea. the models grant access to their processed data, but that data is contained in different container structures as given above. That makes it unfeasible to use inheritance with a pure virtual function in the base class like

std::map<...,...> getModelData() = 0;

The initial idea of this inheritance was to avoid code duplication but that doesnt seem to be the right solution here. I know that Qt in their "Model-View" concepts makes use of their QVariant class to have maximum flexibility in terms of types being returned. However, I am wondering, what is the best solution with standard C++ here? I read a lot about striving for loose-coupling, code reuseability, Dependendy Inversion and how to favour composition over inheritance but I do have problems putting these theoretical advise into practice and end up with code bloat and repetitive code most of the times. Can you help me?

mardi 30 janvier 2018

Computation Classes in MVC Architecture

I am trying to build an command-line menu based application base to attempt to implement MVC architecture.

The "application" I am trying to build is based around cryptography. At its core features include the ability to display the original text and modified text in alternating line. e.g

originaltext originaltext oringaltext
modifiedtext modifiedtext modifiedtext

originaltext originaltext oringaltext
modifiedtext modifiedtext modifiedtext

Currently, I have created a number of Cipher classes that all contain an encrypt and decrypt() function that takes in 2 strings - an input and output. I have also created a Project class that holds 2 pieces of information - the originalstring and modifiedstring.

In this case, I understand that the View should display the Menu that users will see, and that the Project class belongs in the Model. However, where do classes that contain computation (my Cipher classes) belong?

Best architecture for Android project "back-end" using service/dao layer pattern

Im trying to start a project using Spring Boot (REST) as the backend and Android as frontend. The problem is in the android project, because I want to use the Service - Controller pattern.

When I put the code destined to manage the http requests/response in other class, for example UserService, is outside the main thread and this can't manipulate the UI.

I was reading about "runonuithread" but the elements of the UI are not in the Service class... What can I do in this case? Add the elements to the class or manage the context inside the UserService?

This is for asyncronous calls.. But when I wan't to make synchronous calls this is neccesary?

Where should I put service components while using Redux?

In my app I got service classes like SpeechRecognizer, VoiceRecorder ... I wonder should I put them into the state of application, my personal opinion that they don't form the state, so then where to put them.
Also to notice, SpeechRecognizer is initialized with callbacks that are called when certain event occurs, so who shall subscribe to them and how to implement that subscription ?

Android - Apply texture on bitmap (mask)

im trying to fill bitmap with pattern.

pattern pattern

shirt shirt

This is result what i expect. Shirt with filled pattern.

This is what i get with this code: result img

Can you tell me, what im doing wrong and if you suggest me some approach.

public  Bitmap applyMask(Context context, int resOriginal, int maskToBeApplied) {

    Bitmap original = BitmapFactory.decodeResource(context.getResources(), resOriginal);

    int width = original.getWidth();
    int height = original.getHeight();

    // decode mask
    Bitmap mask = BitmapFactory.decodeResource(context.getResources(), maskToBeApplied);

    // create output bitmap
    Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

    // create canvas
    Canvas canvas = new Canvas(output);

    // draw original (shirt)
    canvas.drawBitmap(original, 0, 0, null);

    // draw mask on shirt
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));

    // draw mask
    canvas.drawBitmap(mask, 300, 400, paint);

    // recycle used bitmaps
    original.recycle();
    mask.recycle();

    return output;
}

How best practice with if statement loop?

I have code:

if(conditional)
{
   var r1 = dosomething();
   //do more here

   if(r1 > something)
   {
      var r2 = dosomething();
      //do something
      if(r2 > something)
      {
         ....
         //n if
      }
   }
}

I need help for this code is better. Can you show for me some suggestion? Thanks all!

What is good practice to change the center pane from different controlles in javafx

I created an app with a BorderPane and want to change the content of the center from different fxml controllers, so I don't want to change the whole scene. I have a RootLayoutController that created the Menu bar and the Header, but I am not sure about the best practice to change the content from outside. Would you suggest a MVC-Pattern or should I try to get the BorderPane by the event. Getting BorderPane by event seems not like a clean solution here, but it's just a feeling. Also creating the controllers as singletons was an idea but it's not working with the instantiation (produces NPEs). Any advice would be great because I am lack off experience.

(No code here because I am asking for a general advice.)

Is std::queue or std::stack an implementation of Adapter or Proxy pattern?

std::queue and std::stack are called STL adapters. But are those Adapter patterns or those are more Proxy pattern implementations, as they restrict/control the access to the surrogate object.

Java EE Application Design with Java 9

What is the best way to design (Structure) a JAVA EE Application with Java 9.

I have tried to search for compatible answers but had no luck.

Current Structure contains the following

  • Parent with

    <modules>
      <module>Proj-ear</module>
      <module>Proj-ejb</module>
      <module>Proj-entities</module>
      <module>Proj-web</module>
    </modules>
    
    

I have several entity groups relating to each other that i want to use in a modular way. Any advice and guidance will be appreciated.

Researched Materials

Expose function within service and locally as class library

I am attempting to determine if this specific problem has a common design pattern. (I am using c# but can understand any language you wish to use)

Class library exposes a function add(int x, int y) : int.

Client application references class library and can call said function.

WCF service references the class library and exposes the add function through the server.

Client application is updated to subscribe to the service contract and proxy classes are generated.

Client now has the ability to call the service function which is executed on the server for computationally expensive tasks.

Client continues to use the local reference to the class library for cheap tasks.


This is the problem I am trying to tackle, I am specifically interested in including some logic to decide if the service instance or local instance should be called.

The logical factors that could decide this are, time complexity, force override from user (via client) to perform task on server. Finally, if the task is being called is via Iron Python then the pre-compiler statement for specific clients will state if they are capable of handling iron python calls locally, if they are not then the service should be used.

MY QUESTION: where should this logic be carried out? I can't decide if the service or local reference should be called from within either the server or local class library reference. So it must be called from the client. It does not feel right to put this responsibility on the client as each client will gain access to this functionality, so should I create a separate layer (like the data access layer) that wraps this functionality?

SECOND QUESTION: Is this a common problem? Can any one direct me to some design patterns for this specific problem.

Client - > Wraps add(int,int) decides which instance to call (server or local version) -> Service -> Class library add(int,int) [runs on server] -> Class library add(int,int) [runs locally]

PHP Web-Application auto refresh Observer Pattern

I am programming web applications for a while now and over the time they became more sophisticated, but sometimes I am not sure if the ways I go are common. Now I am diving into design pattern and thinking about ways to dynamically refresh the contents of the page if the data has changed.

Typically this would be the observer pattern. Now my question. What are the professional ways to automatically load the new data in an open web application? It would work with javascript and a refresh of the page, sure. But what if javascript is not available?

The observable should notify the observers and force them to update it's data. I would really appreciate a conversation about this topic to get some ideas for future projects.

Extending/overriding Django TestCase class

My application has three levels of access (i.e. User, Manager, Admin). In my unit tests I have something like this:

from django.test import TestCase

class DocumentViewTest(TestCase):
    def setUp(self):
         # Create 3 users

    def test_view_url_exists_at_desired_location(self):
         self.client.login(username='manager', password='xx')
         resp = self.client.get(reverse('view_upload'))
         self.assertEqual(str(resp.context['user']), 'manager')

Testing all three levels could be defined by the same routine:

  1. login user
  2. post/get to some url
  3. create assertions to check the post/get response

I wanted to encapsulate all the steps in some wrapper class or extend the TestCase, so that redundancy is avoided. I was thinking about something like this:

from django.test import TestCase

class DocumentViewTest(TestCase):
    def setUp(self):
         # Create 3 users

    def test_view_url_exists_at_desired_location(self):
         self.client.login(username=['manager','admin','simple_user'], password=['xx','x','xxx'])
         resp_manager, resp_admin, resp_simple_user = self.client.get(reverse('view_upload'))
         self.assertEqual(str(resp_manager.context['user']), 'manager')
         self.assertEqual(str(resp_admin.context['user']), 'admin')
         self.assertEqual(str(resp.resp_simple_user['user']), 'simple_user')

Does anyone have suggestions how I could override get/post/login methods? Would creating a wrapper class around TestCase be easier? Any other suggestions?

Thanks!

lundi 29 janvier 2018

How to architecture a "plug-in" kind design pattern in JS?

I am building a JS application and I was wondering how to architecture a part of it. Here is my problem, I have to call some API's that will: - check and email address - check an address - check some numbers - etc...

For each of these checks, two different API's from different services will be called. How can I architecture my application so that I can have a "plug-in"/"module"/"adapter" kind of code, so that if one day I decide to change the third party API service I just have to write a specific class for that API and let the rest of the code as it is?

I also imagined to do something like: I create a function called checkEmail(email) and behind scenes he's going to call the different API's.

React Native and Realm - Architecture

So I'm building a React Native application where I'll need to have my data stored on the device offline, only syncing the data in the morning and evening.

The solution I've is Realm. My question is about the structure of the application. As far as I can tell using a Realm database removes the need to have a flux architecture manage my state as this is what Realm would be doing no?

I wanted to see what people are doing in terms of structure or design patterns. Would I implement some sort of ad-hoc mvc? Or mimic redux somehow?

I am asking about the app's possible design pattern but also about the physical folder structure. The app has the potential to be quite complex so I need to plan this thing out before I start.

Thoughts?

What design pattern to apply for case?

I have a table with over 100 columns. Clicking on each column header I can filter by provided parameters.

For example, clicking over header: name the input field is appeared allows to filter by name.

So, it can be different filter, by one field and some composite fields.

I tried to avoid linear case using if conditions like:

if($type == "name") {
   //
} else if ($type == "age") {
  //
}

I think it should be strategy and factory pattern to create instance of concrete search class? What do you think?

How to model data for similar requests?

I have an issue, I'm not sure how should I model the data from the backend when I have some really similar views on the front, particularly some forms.
For example in one of them the user sends an id for a seller and a product code, but in another one the inputs ask for an id seller, a product code, and two dates.
This is silly case probable but there are some others too, and I didn't know if I was supposed to duplicate data on the model or what.
Is there some design pattern one should follow or some convention? If it helps, I'm trying to use using Angular on the front and java for backend.

Is there a suitable design pattern to refactor this C# code

I have 2 different 3rd party assemblies that provide the same API for a business service and using the same class names (~40 classes/types/extensions) but located in different assemblies:

    Company.Assemply.V1
    Company.Assemply.V2

I reference both assemblies in the project.

There is no common interface for these assemblies, and no way for the 3rd party to provide a common interface

So, the c# compiler treat every type in the two assemblies as a different type.

I want to implement a class Myservice for every assembly to support both versions V1/V2.

I use the following code to implement Myservice.V1.Myclass

    //#define V1

    #if V1
       using  Company.Assemply.V1;
    #else
       using  Company.Assemply.V2;
    #endif

    #if V1
      namespace Myservice.V1
    #else
      namespace Myservice.V2
    #endif
    {
       //my implementation that use all classes /types in any v1/v2 assembly
        class MyClass {.... }
     }

Then i copy and paste the same code in other c# file MyClassV2.cs (about 400 lines) to get Myservice.V2.Myclass and uncomment the compiler flag #define V1

I can't use Generics

        MyClass  <T> where T:??

because there is no common interface for T

The two class are working fine

The problem is when maintaining v1, I have to copy/paste the code in the other file MyClassV2.cs and uncomment the compiler flag #define V1 to support V2

Is there a better way / suitable design pattern/refactoring technique that can solve such a problem. I want to use/maintain one code base and avoid copy/paste for the other class version.

Give me an example of refactoring the above code.

What to know of implementation besides contract?

Both L and D in SOLID encourage us to program against contracts, not actual implementations. But does that mean an interface consumer should not know the implementation, or just that he should not rely on implementation doing something not stated in a contract explicitly?

I mean, we can have a method to create a new NumericParameter in DB, but its interface only says that! It does not say that NumericParameter is actually an inherited entity spanning over 2 tables, or that the method also creates one more related entity to save some more data about the created entity. Those are implementation details.

It's very clear why one should not depend on implementation doing something. But maybe it's justifiable to depend on implementation NOT doing something (even if it's not stated in a contract?) Otherwise, how are you going to modify your code at all? Any time you add some activity, it can come to conflict with something that is happening in some of the other methods and services you call. Like, you read a DB row "for update", then call foo() and then write a row back with some modifications, but it appears that foo() already made some changes to the same row - in this very transaction - and they will be overwritten.

On the other hand, implementation can be changed. If some consumer depends on it NOT doing something, then at some moment that dependency may break. Meaning, not only have we to examine what code is called from the code being edited, but also possible callers of the code. Everything that may be happening in any transaction triggering this code, we must know in details.

Somehow I think that is a smell, but how do you live without it? I usually try to ignore implementation details, but on multiple occasions that ended up in some conflicts.

What kind of design pattern that differentiates between graphical models and stored models?

I am working on a software that preforms database forward engineering, from graphical shapes ( graphical tables and columns ) to a stored models ( physical database ).

Can it be PAC, MVC, MMVC, Blackboard,...? Or there's another convenient one?

Paging list of entities with restrcited access

We have client-server application. To reduce response time we want to add paging of request. But there is one pitfal - security policy. The visibility of the object and the list of allowed actions are determined by the user's rights, roles, and its belonging to a particular department in the company hierarchy. Of course, this all changes dynamically. Let's say we made a page request from 100 entities. None of them are available to us. Should we return an empty list? Or should we try to request next page automaticaly? What is the best practice for such scenarios?

Is there a pattern for writting telescopic configureable classes in Java?

I'm thinking at the moment about the solution of a problem which might be already solved by a pattern but I can not find the correct one. I'll try to explain what I would like to do with a simplefied example.

There is a class which handles to connection to a database, let's call it DatabaseManager.java. With this class I would like to handle the fetchment of data from a database and I also would like to apply filter.

public class DatabaseManager {

    DatabaseFilter databaseFilter = new DatabaseFilter();

    public DatabaseManager() {
        // Do some stuff to init db connection
    }

    public DatabaseFilter configureFilter() {
        return databaseFilter;
    }

    public String getStringDataset() {
        String dataset = null;
        // Fill dataset with applied filter data
        return dataset;
    }

}

With the method call configureFilter() on the databse object, I would like to get the DatabaseFilter which contains particular nested filter classes.

public class DatabaseFilter {

    int[] filteredIds = null;

    public IdFilter onId() {
        return new IdFilter();
    }

    public class IdFilter {
        private void exclude(int[] ids) {
            filteredIds = ids;
        }
    }
}

On this way, I could write the follwing nice syntax to configure a filter which excludes particular filter.

DatabaseManager database = new DatabaseManager();
database.configureFilter().onId().exclude(idArray);
// Get filtered dataset
database.getStringDataset();

Is this an appropriate way to solve problems like this and is this a particular pattern? Are there any disadvantages?

dimanche 28 janvier 2018

Interface-oriented: Fragmentized interfaces to represent a data structure

I'm inspired from encapsulation achieved by interfaces. Interface is a powerful tool when objects shares common properties and methods. Interface-oriented designs are designs that decouple entities and the manager that are managing them. They do not need to know any of the implementation details and the exact type, and a typical good interface design is that object that passed through the method call could be hot-plugged at runtime.

So I managed to turn my objects to expose through interfaces.

Suppose I have a LoginModule, which contains the business logic to handle the submitted Form by Client. For example, the client may either login through enter Username and Password or with their MobileNo

public class UserLoginForm
{
  public string Username { get; set; }
  public string Password { get; set; }
}
public class MobileLoginForm
{
  public string MobileNo { get; set; }
  public string Password { get; set; }
}

Then the business logic layer is going to take a look at the request.

public class LoginModule
{
  public int LoginByUsername(UserLoginForm form)
  {
    // DoSomething, such as CheckDbIfExist(form.Username);
    // return the result, e.g. -1 stand for wrong password
  }
   public int LoginByMobileNo(MobileLoginForm form)
  {
    // DoSomething, such as CheckDbIfExist(form.Username);
    // return the result, e.g. -1 stand for wrong password
  }
}

In this example, the two logics are so similar that LoginByMobileNo could eventually direct to call LoginByUserName after getting the Username by looking up MobileNo in the database.

But you know, it just couldn't because we need a UserLoginForm to call it, or we just create a separated method Login(string username, string password) to let both login method to call it.

The actual consideration is not on how to reconstruct these two methods, as there are many other types of request, something like CokeRequest that request a coke delivery to int RoomNo and int Count... ...

public interface ILoginModule
{
   void LoginByUsername(XXX xxx);
}

First Question: What is that XXX?

This interface have no access to UserLoginForm, he don't know the existance of that form anyway. If I am doing the interface design correctly, XXX should be an interface that he could know its existance.

public interface ILoginModule
{
   void LoginByUsername(IUserLogin login);
   void LoginByMobile(IMobileLogin login);
}
// LoginModule now implement ILoginModule

public interface IUserLogin
{
   string UserName { get; set; }
   string Password { get; set; }
}
public interface IMobileLogin
{
   string MobileNo { get; set; }
   string Password { get; set; }
}
// The the two Forms now implement the respective interface

By then the nightmare begun. I find to needing a dedicated interface for every Request that the client made

An interesting observation:

Service interfaces are Method-only interfaces

Request interfaces are Property-only interfaces

I do not believe it is the right way to do deal with interfaces.

Neither if we fragmentize the interfaces.

public interface ILoginModule
{
   void LoginByUsername(IUserLogin login);
   void LoginByMobile(IMobileLogin login);
}
// LoginModule now implement ILoginModule

public interface IPassword
{
   string Password { get; set; }
}
public interface IUserLogin : IPassword
{
   string UserName { get; set; }
}
public interface IMobileLogin : IPassword
{
   string MobileNo { get; set; }
}
// The the two Forms now implement the respective interface

Because we are still needing hundreds of interface (which is of same variety as the requests to be) Nor

public interface ILoginModule
{
   void LoginByUsername(IUser login1, IPassword login2);
   void LoginByMobile(IMobile login, IPassword login2);
}
// LoginModule now implement ILoginModule

public interface IPassword
{
   string Password { get; set; }
}
public interface IUser
{
   string UserName { get; set; }
}
public interface IMobile
{
   string MobileNo { get; set; }
}
// The the two Forms now implement the respective interface

It smells bad because we are no different from passing the string content one by one. If the request contains 8 param, then the method becomes DoWork(form,form,form,form,form,form,form,form)

I really can't figure out why I'm falling into this irony. If I have n types of requests, it is normal to give them to m modules to handle, it still n methods in total. If we use interface, it adds n interfaces to represent n request, and this didn't help to hot-plug data at anytime because each interface get only one single implementation.

In this situation the LoginModule can't even benefit from it: It could not call LoginByUsername after finding out the Username which corresponds to MobileNo at any circumstances...

Most interface tutorial is taking about car and bus and racecar in which they void StartEngine()...While seldom for architecture, or communication between layers, just for instance, the MVC model.

I'm not saying interfaces are bad, but I need a way to correctly implement it or should I implement it in this situation. Any misused patterns are antipattern with no single doubt. I hope to hear any voices.

suitable design pattern for an application

This is a question I encountered in a C++ test interview :

You are writing an application aiming at making cocktails. A cocktail contains several ingredients (according to the customer's order) and it can quickly become complex to prepare.

However, the different steps in the preparation process remain the same: adding an alcohol, adding a syrup, etc...

If you know a design pattern that would be appropriate to prepare these cocktails. type its name in the text field.

I think I gave an incorrect response (Decorator). I think the "Builder" pattern is the correct response.

samedi 27 janvier 2018

Recognizing C++ template code patterns

I was reading through a set of some library source files and after reading though the code I can see what it clearly does. That is not the issue. In fact there really isn't any issue, but the more I start to work with templates and read through these documents; some of the patterns are becoming visually recognizable.

The code has this kind of pattern...

template<typename T, typename U, 
    bool is_T_signed = integer_traits<T>::is_signed,
    bool is_U_signed = integer_traits<U>::is_signed>
struct foo_impl {};

template<typename T, typename U>
struct foo_impl<T, U, true, true> {
    static T run( U x ) {
        return ( (x <= /*some max value */ ) && 
                 (x >= /*some min value */ ) );
    }
};

template<typename T, typename U>
struct foo_impl<T, U, false, false> {
    static T run( U x ) {
        return x <= /*some max value*/;
    }
};

template<typename T, typename U>
struct foo_impl<T, U, true, false> {
    static T run( U x ) {
        if ( sizeof( T ) > sizeof( U ) )
            return 1;
        else
            return x <= U( /*some max value*/ );
    }
};

template<typename T, typename U>
struct foo_impl<T, U, false, true> {
    static T run( U x ) {
        if ( sizeof( T ) >= sizeof( U ) )
            return x >= 0;
        else
            return (x >= 0) && (x <= U( /*some max value*/ ));
    }
};

template<typename T, typename U> inline T foo( U x ) {
    return foo_impl<T, U>::run( x );
}


Where it is simply straight forward to understand what the code is intended to do.


  • An empty class template with <T,U,bool = default, bool = default> parameters
  • Specializations of all 4 combinations [t,t], [f,f], [t,f], [f,t].
  • They each return T and accept U as its member function's param and the function is of a static type.
  • These all have impl appended to the end of the struct which refers to the implementation that is abstracted away from the user.
  • Finally a function template that accepts <T,U> params and returns or invokes the struct's internal static method.

What I would like to know for better understanding so that when I begin to see and recognize patterns like this more often I then know what to call them. Is there a preferred common name for this type of pattern? I know that the class or struct is being specialized and invoked in a wrapper function template but this is not what I'm referring to. For example some types of patterns of code are called SFINAE or Tag Dispatching, etc. ... I know that this is probably something simple that I'm overlooking but don't know what to generally call this type of pattern when I see it. I'm not really concerned about the implementation details of the static methods themselves for this concerns the actual overall pattern of the template specialization and then being invoked by a function template wrapper that would be available to the user.

identifying the design pattern name used

I want to check if the examples below (from a test interview) corresponds to the correct design pattern name :

Example 1 : can that piece of code illustrate the "Builder" pattern or it might be the "Strategy" one ?

FileStream* files = new FileStream("my_file.zip");
BufferedStream* bufferds = new BufferedStream(files);
ZipStream* zips = new ZipStream(bufferds);

Example 2 : is the code below represent the "Strategy" pattern ?

struct UnixText {
void write(string str) { cout << str; }
void lf() { cout << "\n"; }
};

struct WindowsText {
void write(string str) { cout << str; }
void crlf() { cout << "\r\n"; }
};

struct Writer {
virtual void write(string str) = 0;
virtual void newline() = 0;
virtual ~Writer() {}
};

struct UnixWriter : Writer {
UnixWriter(UnixText* tx) { _target = tx; }
virtual void write(string str) { _target->write(str); }
virtual void newline() { _target->lf(); }

private:
UnixText* _target;
};

struct WindowsWriter : Writer {
WindowsWriter(WindowsText* tx) { _target = tx; }
virtual void write(string str) { _target->write(str); }
virtual void newline() { _target->crlf(); }

private:
WindowsText* _target;
};

int main()
{
Writer* writer = (g_IsUnix) ? (Writer*) new UnixWriter(new UnixText()) : (Writer*) new WindowsWriter(new WindowsText());

writer->write("Hello");
writer->newline();
writer->write("World");

}

Design pattern for slightly different functionality

I have a function that delete an order by its id. I have a business rule that transaction should not be deleted if this order have some related comments (for example...). In another use case I can delete such order (even the order have some related comments) but is applied another condition.

I want to follow DRY principle and do not duplicate my code, because these two use cases differ only very short part of my code. Do exist some suitable design patter for this use case?

Best model-vision pattern/approach for game

I'm making a game.

I have been using modified version of MVC to separate vision and logic, where controller sends a request to model, then sends its answer to vision. I've found this approach too complex, not letting me to make significant changes in the future.

So I wonder what is the best way to separate graphic/animation and logic parts in the game to make the code more clear and easy to understand while also less vunerable to changes in the algorythm steps or the algorythm itself.

Drawbacks of using singleton with models

So let's say I'm making a React Redux app for handling a library. I want to create an API for my backend where each model (book, author, etc) is displayed in the UI. Each model does not provide a public constructor, but a from static function which ensures that only one instance per id exists:

static from (id: string) {
  if (Books.books[id]) {
    return Books.books[id];
  }
  return Book.books[id] = new Book(id);
}

Each model provides an async fetch function which will fetch its props using the backend. The advantage is that there is no thousands instances, also I don't have to fetch twice (if two parts of my app needs the same model, fetch will actually be called only once). But I fail to find any drawbacks, except that there might be a discrepancy between a code that fetches its models and one that assumes they are still not fetched, but I still don't see when it would really be an issue

how to replace 2 diffrents strings in one url using matcher?

i'am beginner on android , i have an url and i want to replace two strings("/vp/" with "/" ) and ("/s150x150/" with "/s720x720/"..(if it's exist)) in this url using matcher and pattern!

this is my url : cd.com/vp/3070d0210e464e/5AEFB3ED/t51.2885/s150x150/24845474_1790806444289980_66798452736_n.jpg

any help please !

Dependency Injection through a setter

Does Laravel have the ability to introduce dependency through a method?
For example, I have a controller that implements the DoctrineWorkable interface:

interface DoctrineWorkable {
    public function setEntityManager(EntityManager $manager);
}

trait EntityManagerTrait {
   protected $manager;

    public function setEntityManager(EntityManager $manager) {
        $this->manager = $manager;
        // Other work with $manager
    }
}

class TestController implements DoctrineWorkable {
    use EntityManagerTrait;
}

How to use the setEntityManager method in the service container? To get something like this:

if ($class instanceof DoctrineWorkable) {
    $class->setEntityManager(new EntityManager());
}

p.s. Sorry for the bad English ))

Basic Entity Management System

How can I design an Entity Management system in Django which can be able to adapt to any kind of entity with minimal code changes (e.g. a product in a catalog, patient information in healthcare etc.).

  1. Adding, removing, modifying the attributes of an entity should be simple
  2. It should allow for nested attributes (sub-entities) e.g Patient -> Consulting doctor
  3. Each attribute or sub-entity in the entity can have a set of business rules

vendredi 26 janvier 2018

Component ID's created from object types passed through template in Entity Component System

So I've been learning about Entity Component Systems(ECS) and came across this method for creating unique ID's by passing the object as a template parameter. I was wondering how the line:

 static ComponentID typeID{getUniqueComponentID()};

is creating ID's without having a duplicate ID created again. I know it's probably glaringly obvious.

Here's the entire code that works and doesn't repeat any ID's

#include <iostream>

using ComponentID = std::size_t;

//Creates a unique ID for and component that is created
inline ComponentID getUniqueComponentID() noexcept{

    //states that the static ComponentID is going to start at 1
    static ComponentID lastID{1u};
    std::cout<< "Created ID: " << lastID << std::endl;
    return lastID++;

}

//gets the component ID of the Type that is being passed into template
template<typename T>
inline ComponentID getComponentTypeID() noexcept{

    //ComponentID is tied to the templated object type
    static ComponentID typeID{getUniqueComponentID()};
    return typeID;
}

struct A{};
struct B{};
struct C{};

int main(int argc, const char * argv[]) {

   std::cout << getComponentTypeID<A>() << std::endl;
   std::cout << getComponentTypeID<B>() << std::endl;
   std::cout << getComponentTypeID<C>() << std::endl;
   std::cout << getComponentTypeID<C>() << std::endl;
   /*
   Output:
   1
   2
   3
   3
   */

   return 0;
}

static factory methods inside interface

This is a design question regarding using static factory methods inside of static interface methods. I am looking for improvements or disadvantages of using this pattern.

public interface SampleService {

    // 1) do work
    void doWork();

    static SampleService create(final String service) {
        // 2)  Dispatch to factory method to get correct implementation
        return Factory.create(service);
    }

    class Factory {
        private static SampleService create(final String service) {
            // 3) return one of many possible implementations
            return new DefaultSampleService();
        }
    }

    class DefaultSampleService implements SampleService {
        @Override
        public void doWork() {
            // 4)  performs work
        }
    }
}

In original implementation, caller would call

SampleService.Factory.create

now they call it as

SampleService.create

Which looks to be cleaner and more readable. So what could we improve on this?

R create new variable from several columns if one satisfies condition

sorry for the very unspecific title. I really don't know how to name the problem... So I'm dealing with this data frame :

 C1 <- c("made in Italy", "100% silk", "dry clean only")
 C2 <- c("80% cotton, 20% polyester","made in France", "hand wash")
 C3 <- c("made in Italy", "Designer color : vanilla", " 100% nylon")
 eg <- as.data.frame(rbind(C1,C2,C3))

I'd like to add one veriable "composition" by extracting all the values containing "%" sign. As you can see, the composition values are not in the same column for each observation... I tried several methods but failed to achieve this. for example :

 fcompo <- function(x){
   if (grepl('%',x) = TRUE){eg$composition <- paste(x)}
 else {eg$composition=NA}
 }

then I got lost in the function... being very new to R language... I also tried :

  library(stringr)

  eg$composition <- str_extract(eg[,c(1:3)], "%$" )

thanks a lot for your generous help

Best way to pass data into plugin objects

I often have the problem that I have different plugins that all essentially perform the same task, but all in a different way. So each plugin needs different kinds of parameters, but how to pass them?

IMySpecificTask plugin = PluginResolver.Resolve(typeof(IMySpecificTask));

Each implementation of IMySpecificTask needs different objects of my domain which it needs to access. I could certainly use a service locator/singleton pattern to get the information which I need but isn't there a cleaner way?

Another way I could think of but which also seem fishy to me is something like this:

if (plugin is INeedsServiceA a)
    a.SetServiceA(myserviceA);
if (plugin is INeedsServiceB b)
    b.SetServiceB(myserviceB);
...

ASP.net RESTful Web API & SPA Angular JS app

Could someone suggest the best design pattern for the following scenario:

  • Single Page Application in ASP.net using angular JS
  • Needs Web API RESTful Interface
  • Needs to manage CRUD on SQL tables that change often (i.e. unable to generate models/ controllers that match the schema)
  • Need to be able to specify which CRUD options are available on a given schema.
  • Needs user management

I would normally use MVC, however I am not sure this is sensible or possible given the schema of the database can change from day to day. This isn’t too dissimilar to what I need to achieve: https://www.tablesmarteditor.com/ , however code wise is unsuitable to the above scenario.

Advice on how to tackle the above would be greatly appreciated.

Create object in function based on Class argument

I want to define a function that creates different type objects that share the same base class. I'd like to pass in the object type and have the function creating the object and then modifying its attributes. The problem is that the main class from which all these objects are created, does not have the object's attributes so the code fails to compile.

Example:

public void new_generic_report(Class report_class, String report_name) {

    Report new_report = this.reportManager.createReport(report_class);
    new_report.set_name(report_name);

}

Calling new_generic_report(GreenReport.class, "green_report"); fails because new_report is of the class Report instead of GreenReport so it does not have the .set_name method.

I know I could implement the .set_name method (and other common methods) in the main Report class but I am writing code to interface with an API that I cannot modify.

How to design a user permission handling database?

We have a little problem in one of our projects, where two investors are architects and... as it usually is in life, they don't really get along with some of the ideas. Both have different experiences with previous projects, and it seems they look down upon the ideas of the other one. Yep, I'm one of them.

We have an argument over how to define user permission handling in one our project.

One idea is to have table with permissions, roles which gather sets of permissions and then users who have a role defined.

User
user_id
role_id

Role
role_id
permission_id

Permission
permission_id

The other side would like to propose to do it using a table with columns defining permissions:

User
user_id
role_id

Role
role_id
can_do_something
can_do_something_else
can_do_something_even_different

My take on the first option is that it's far cheaper to maintain: adding a single permission means it's just one insert + handling of the permission in the code.

In case of the other (to me) it means that you have to alter the database, alter the code handling the database and on top of that, add code to handle the permission.

But maybe I'm just wrong, and I don't see some possible benefits of the other solution.

I always thought the former is the standard to handle it, but I'm told that it's subjective and that making a change in the database is a matter of just running a script (where for me it means that the script has to be added to the deployment, has to be run on every database and in case of migration has to be "remembered" etc.)

I know the question could be opinion based, but I'm kind of hoping, this really is a matter of standards and good practice, rather then subjective opinion.

Compiler error when trying to implement visitor design pattern

I'm trying to implement the Visitor Design pattern based on a class diagram from a training material. I've been to this training a while ago and I didn't save the code I implemented there. I am stuck at a compilation error and I can't figure out what I did wrong. Most likely I didn't understood the class diagram for this design pattern. Below I put the entire code and the compilation error I received.

    #define _USE_MATH_DEFINES
    #include <list>
    #include "math.h"

    class Cerc;
    class Dreptunghi;
    class Arie;
    class Perimetru;
    class Operatie;

    class Forma
    {
    public:
        virtual void accept(Operatie * op);
        Forma(void){};
        ~Forma(void){};
    };

    class Cerc : public Forma {
    protected:
        int raza;
    public:
        void accept(Operatie * op){op->vizitare(this);};
        int getRaza(){return raza;};
        Cerc(void):raza(3){};
        ~Cerc(void){};
    };

    class Dreptunghi : public Forma {
    protected:
        int lungime;
        int latime;
    public:
        void accept(Operatie * op){op->vizitare(this);};
        int getLungime(void){return lungime;};
        int getLatime(void){return latime;};
        Dreptunghi(void):lungime(3),latime(3){};
        ~Dreptunghi(void){};
    };

    class Operatie{
    public:
        virtual void vizitare(Cerc* obj) = 0;
        virtual void vizitare(Dreptunghi* obj) = 0;
        Operatie(void){};
        ~Operatie(void){};
    };

    class Arie : public Operatie {
    private:
        double arie;
    public:
        double getResult(){return arie;};
        void vizitare(Cerc* obj){arie = arie + M_PI*obj->getRaza();};
        void vizitare(Dreptunghi* obj){arie = arie + obj->getLungime() + obj->getLatime();};
        Arie(void): arie(0) {};
        ~Arie(void){};
    };

    class Perimetru : public Operatie {
    private:
        double perimetru;
    public:
        double getResult(){return perimetru;};
        void vizitare(Cerc* obj){perimetru = perimetru + M_PI*obj->getRaza()*obj->getRaza();};
        void vizitare(Dreptunghi* obj){perimetru = perimetru + 2*(obj->getLungime() + obj->getLatime());};
        Perimetru(void):perimetru(0){};
        ~Perimetru(void){};
    };

    class Editor{
    private:
        std::list<Forma*> forme;
    public:
        Editor(void){};
        void insert(Forma obj){forme.insert(forme.end(), &obj);};
        double calculeazaArieTotala(){
            Arie arie;

            for(std::list<Forma *>::iterator it = forme.begin(); it != forme.end(); ++it){
                (*it)->accept(&arie);
            }

            return arie.getResult();
        };

        double calculeazaPerimetrulTotal(){
            Perimetru permietru;

            for(std::list<Forma *>::iterator it = forme.begin(); it != forme.end(); ++it){
                (*it)->accept(&permietru);
            }

            return permietru.getResult();
        };
        ~Editor(void){};
    };


    int main(void){
        Editor editor;
        cout << editor.calculeazaArieTotala() << endl;
        cout << editor.calculeazaPerimetrulTotal() << endl;
    }

The compiler error I get:

    visitordesignpattern.cpp(23): error C2027: use of undefined type 'Operatie'
    visitordesignpattern.cpp(23) : see declaration of 'Operatie'
    visitordesignpattern.cpp(23) error C2227: left of '->vizitare' must point to class/struct/union/generic type
    visitordesignpattern.cpp(23) error C2027: use of undefined type 'Operatie'
    visitordesignpattern.cpp(23) see declaration of 'Operatie'
    visitordesignpattern.cpp(23) error C2227: left of '->vizitare' must point to class/struct/union/generic type

Thank you!

jeudi 25 janvier 2018

Vuex or not Vuex

I just starts learning Vue.js (awesome framework), and I get into Vuex. I don't understand the real use-case why I should prefere using it.

I mean I have a simple counter (like in the Vue doc):

Why should I use the Vuex syntax:

    const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        increment: state => state.count++,
        decrement: state => state.count--
      }
    })

    new Vue({
      el: '#app',
      computed: {
        count () {
            return store.state.count
        }
      },
      methods: {
        increment () {
          store.commit('increment')
        },
        decrement () {
            store.commit('decrement')
        }
      }
    })

While I can use:

 class Store  {
 constructor(){
  this.state = {
    count: 0
  }
  }
  /* mutations: { */
    increment = state => this.state.count++;
    decrement = state => this.state.count--;
  /* } */
}


let store = new Store();
new Vue({
  el: '#app',
  data: {
  state: store.state
  },
  computed: {
    count () {
    debugger
        return this.state.count
    }
  },
  methods: {
    increment () {
    debugger;
      store.increment()
    },
    decrement () {
        store.decrement()
    }
  }
})

Both works, and IMO the second one is much more simple??

does 10 types of pizza requires 2 power 10 methods If I use decorator pattern?

I started understanding decorator pattern, It flows something like this

Main(){
chikenChillyCheesePizza = new chicken(new chilly(new cheese(new pizza())));
chikenCheesePizza = new chicken(new cheese(new pizza()));
}

The question I would like to ask is when I want a specific flavor of pizza I need to pass those objects in the constructor injection right? Instead I would like to have class that has these methods

static class pizzaMaker{
static chikenChillyCheesePizza() => new chicken(new chilly(new cheese(new pizza())));
static chikenCheesePizza() => new chicken(new cheese(new pizza()));
}

If I have 10 types of pizza then do I need to have 2 power 10 combination of methods in my pizzaMaker class? How would I solve this in a simpler way. Decorator stops creating permutation of objects but does it solve permutation of methods also? How would I achieve this. Any help is greatly appreciated.

PHP : same functionality design pattern

Hi I am using repository pattern PHP and from the controller or the service I need to call 1 after 1 to different repository function

$lists is a list of list objects that comes from DB. the repository pattern is the sample Repository pattern

like :

        $lists = $this->_listRepo->findAllX($this->config["same_config_param"]);
        $arrayToUpdate = $this->someProcess($lists , $statusA);
        $this->updateDBStatus($arrayToUpdate , $statusA);


        $lists = $this->_listRepo->findAllB($this->config["same_config_param"]);
        $arrayToUpdate = $this->someProcess($lists , $statusB);
        $this->updateDBStatus($arrayToUpdate , $statusB);


        $lists = $this->_listRepo->findAnotherCase($this->config["same_config_param"]);
        $arrayToUpdate = $this->someProcess($lists , $statusC);
        $this->updateDBStatus($arrayToUpdate , $statusC);

is there a design pattern to handle it differently and nicely? maybe should I use FACADE?

thanks

Working with subclasses that have dissimilar methods without violating SOLID principles

//interfaces

public interface Singer{
    void sing();
}
public interface SongWriter{
    void writeSong();
}

//Implementations

public class PureSinger implements Singer{
    void sing(){}
}
public class SingerSongWriter implements Singer, SongWriter{
    void sing(){}
    void writeSong(){}
}

//Client code

void methodA(){
    Singer objPureSinger = new PureSinger();
    Singer objSingerSWer = new SingerSongWriter();

    doSomething(objPureSinger);
    doSomething(objSingerSWer);
}

public void doSomething(Singer obj){
    obj.sing();
    obj.writeSong();    //<--- this does not work.
}

In order to acheve this type of code, how should I design the class structure?

Laravel Model Inheritance through Polymorphic Relation

I was searching a way to implement Laravel Model Inheritance and I was inspired by the Multi Table Inheritance described at the accepted answer here: How can I implement single table inheritance using Laravel's Eloquent?

@lukasgeiter ends with: "So as you can see, a clean database comes with it's price. It will be a bit more complex to handle your model. However you can put all these extra logic (e.g. that's required to create a model) into a function in your model class and don't worry about it too much."

I did it using Laravel's Polymorphic Relations and an abstract subclass of the father class, from which to have all the children inherit, using PHP magic methods.

My concern is if by chance I stumbled into a sort of antipattern or bad practice, so I would like to hear some expert opinion about it.

I did not use the *able convention, since I'm implementing a father/child schema using morphOne, not a standard polymorphic Relation. Laravel version in 5.2, a little bit old, but right now I can't upgrade it.

The DB is composed of many salable parts, all of which are coded. All codes have common behaviors, while the parts differ from one another. Following a db sample:

code table:
id | code   | child_id | child_type | other_code_fields
1  | XXX123 | 1        | BrakePad   | ...
2  | YYY987 | 1        | BrakeShoe  | ...


brake_pads table:
id | length | width | other_brake_pads_fields
1  | 10     | 20    | ...


brake_shoes table:
id | material | other_brake_shoes_fields
1  | xyzacb   | ...

The Father class inherit directly from Model, implements the morphTo relation and the __get magic method in order to access children properties directly like $code->length, instead oh passing through $code->child->length.

<?php
class Code extends Model {

    protected $child_fields = [];

    public function child() {
        return $this->morphTo();
    }

    public function __get($name) {
        $ret = parent::__get($name);

        if ($ret === null) {

            if (isset($this->child_fields[$name])) {
                $ret = $this->child_fields[$name];
            } else if (array_key_exists('child', $this->getRelations())) {
                $ret = $this->child->{$name};
            }
        }

        return $ret;
    }

    public function __toString() {
        return $this->code;
    }

}

The Child abstract class is where the bulk logic is implemented, mostly by implemnting PHP magic methods and overriding Model::save() and Model::delete(). Thanks to this implementation it is possible to access the properties of the parent class (Code) directly from the child class (eg BrakePad) via the PHP Object Operator. For example it's possible to use $bp->code instead of $bp->father->code to access the 'code' property. The same technique allows both to read and write the properties, taking care to save the data in the appropriate tables.

<?php
abstract class CodeChild extends Code {

    protected $father_fields = [];

    public function father() {
        return $this->morphOne(Code::class, 'child');
    }

    public function __get($name) {
        $ret = parent::__get($name);

        if ($ret === null) {
            if (isset($this->father_fields[$name])) {
                $ret = $this->father_fields[$name];
            } else if ($this->father()->count() > 0) {
                $ret = $this->father->{$name};
            }
        }

        return $ret;
    }

    public function __set($key, $value) {

        if (!Schema::hasColumn($this->getTable(), $key)) {
            $this->father_fields[$key] = $value;
        } else {
            parent::__set($key, $value);
        }
    }

    public function __unset($key) {

        if (!Schema::hasColumn($this->getTable(), $key)) {
            unset($this->father_fields[$key]);
        } else {
            parent::__unset($key);
        }
    }

    public function __isset($key) {

        if (!Schema::hasColumn($this->getTable(), $key)) {
            return isset($this->father_fields[$key]);
        } else {
            return parent::__isset($key);
        }
    }

    public function save(array $options = array()) {

        $ret = parent::save($options);

        if ($ret) {

            $father = $this->father;
            if ($father == null) {
                $father = new \App\Code();
            }

            foreach ($this->father_fields as $key => $value) {
                $father->{$key} = $value;
            }

            $father->save();
            $this->father()->save($father);
        }

        return $ret;
    }

    public function delete() {
        $ret = false;
        if ($this->father->delete()) {
            $ret = parent::delete();
        }
        return $ret;
    }

}

Finally we have the "real" product class, with its own logic and all Code logic inherited:

<?php
class BrakePad extends CodeChild {
    /* Custom logic */
}

The inverse of the relationship, that is, access to the parameters of the child instances from an instance of the parent class, is available as read-only, as there could be a "Code" object unlinked from any children. It is therefore advisable, except in special cases, to use the CRUD functionalities of the ORM other than Read only on instances of the child classes.

Mine is not really a question, but a request for opinions about an advanced technique of data modeling about which I have found many questions on StackOverflow and on the internet, but few satisfactory answers. I hope I have not violated any rules.

Vistor pattern to visit super classes, interfaces and canceling decent

I'm working on a variation of the standard visitor pattern with the following three requirements:

  • For each node, all super classes of the node should be visited first
  • For each class, all implemented interfaces should be visited first
  • Each visit to a class or interface should be able to cancel the visit to subclasses/implementing classes

My question is twofold. 1) is this a known method or is there a similar pattern around with a different name? 2) are there any obvious improvements or problems with this approach?

I will here detail my approach with an abstract example.

The class hierarchy visited is a Collection of ConcreteItems. The ConcreteItem implements a CrossCuttingConcern and extends an AbstractItem class.

class Collection implements Visitable {
  public final List<ConcreteItem> concreteItems;

  public Collection(ConcreteItem ...concreteItems) {
    this.concreteItems = asList(concreteItems);
  }

  public Decent accept(Visitor visitor) {
    return visitor.visit(this);
  }
}

class AbstractItem implements Visitable {
  public Decent accept(Visitor visitor) {
    return visitor.visit(this);
  }
}

interface CrossCuttingConcern {
  default Decent acceptCrossCuttingConcern(Visitor visitor) {
    return visitor.visit(this);
  }
}

class ConcreteItem extends AbstractItem implements CrossCuttingConcern {
  public Decent accept(Visitor visitor) {
    // This will visit the abstract super type, interface, and concrete class in turn.
    // If any of those returns Decent.STOP, then the remaining ones are not visited.
    return Decent.allUntilStop(
        () -> super.accept(visitor),
        () -> this.acceptCrossCuttingConcern(visitor),
        () -> visitor.visit(this)
    );
  }
}

Now the Visitor and Visitable implementations are modified to return a type called Decent (yeah, maybe not the best name for it). A visit method returns STOP if it wants the visitor to stop descending down the class hierarchy. i.e. if you only want to visit AbstractItems you return Decent.STOP from visit(AbstractItem).

interface Visitor {
  Decent visit(Collection collection);
  Decent visit(AbstractItem abstractItem);
  Decent visit(CrossCuttingConcern interfaceItem);
  Decent visit(ConcreteItem concreteItem);
}

interface Visitable {
  Decent accept(Visitor visitor);
}

enum Decent {
  STOP,
  CONTINUE;

  public static Decent allUntilStop(Supplier<Decent> ...fns) {
    for (Supplier<Decent> fn : fns) {
      if (fn.get() == STOP) {
        return STOP;
      }
    }
    return CONTINUE;
  }

  public static BinaryOperator<Decent> product() {
    return (a, b) -> a == CONTINUE && b == CONTINUE ? CONTINUE : STOP;
  }
}

Now the default visitor adapter implementation returns Decent.CONTINUE and prints debugging information used in the example below.

class VisitorAdapter implements Visitor {

  @Override
  public Decent visit(Collection collection) {
    System.out.println("visiting Collection: " + collection);
    // iterate over all concrete items and return STOP if one of the visit(items) does so
    return collection.concreteItems.stream()
        .map(a -> a.accept(this))
        .reduce(Decent.product())
        .orElse(CONTINUE); // return CONTINUE if collection contains zero items
  }

  @Override
  public Decent visit(AbstractItem abstractItem) {
    System.out.println("visiting AbstractItem: " + abstractItem);
    return CONT;
  }

  @Override
  public Decent visit(CrossCuttingConcern interfaceItem) {
    System.out.println("visiting CrossCuttingConcern: " + interfaceItem);
    return CONT;
  }

  @Override
  public Decent visit(ConcreteItem concreteItem) {
    System.out.println("visiting ConcreteItem: " + concreteItem);
    return CONT;
  }
}

This example demonstrates the working requirements:

public static void main(String[] args) {
  Collection collection = new Collection(new ConcreteItem(), new ConcreteItem());

  System.out.println("Visit all");
  new VisitorAdapter().visit(collection);
  System.out.println("");

  System.out.println("Stop at AbstractItem")
  new VisitorAdapter() {
    public Decent visit(AbstractItem abstractItem) {
      super.visit(abstractItem);
      return STOP;
    }
  }.visit(collection);
  System.out.println("");

  System.out.println("Stop at CrossCuttingConcern");
  new VisitorAdapter() {
    public Decent visit(CrossCuttingConcern interfaceItem) {
      super.visit(interfaceItem);
      return STOP;
    }
  }.visit(collection);
  System.out.println("");
}

Providing the following output:

Visit all
visiting Collection: Collection@7f31245a
visiting AbstractItem: ConcreteItem@16b98e56
visiting CrossCuttingConcern: ConcreteItem@16b98e56
visiting ConcreteItem: ConcreteItem@16b98e56
visiting AbstractItem: ConcreteItem@7ef20235
visiting CrossCuttingConcern: ConcreteItem@7ef20235
visiting ConcreteItem: ConcreteItem@7ef20235

Stop at AbstractClass
visiting Collection: Collection@7f31245a
visiting AbstractItem: ConcreteItem@16b98e56
visiting AbstractItem: ConcreteItem@7ef20235

Stop at Interface
visiting Collection: Collection@7f31245a
visiting AbstractItem: ConcreteItem@16b98e56
visiting CrossCuttingConcern: ConcreteItem@16b98e56
visiting AbstractItem: ConcreteItem@7ef20235
visiting CrossCuttingConcern: ConcreteItem@7ef20235

So; does this look familiar, or is there a simpler way to achieve my requirements?

Refactor IF ... ELSE desing

I have legacy code and my task to refactor it.

  1. There is base class (ie vehicle)
  2. it's heirs (car, bus, motorcycle and so on)
  3. Service that has to choose and greate instance appropriate heir by parameter

So I've something like this:

...

   if (param == "car")
        result = new Car();
    else if (sectionType == "bus")
        result = new Bus();
    else if (sectionType == "motorcycle")
        result = new Motorcycle();

...

I think that code isn't productive and supported.

Q: My aim is founding out the better design solution.

Thx in advance

What are the examples of design patterns within the C# language [on hold]

I would like to gather examples of design patterns used by default in C# language. I want them to be language-level and C# / .Net only

For example:
foreach loop and IEnumerable - Iterator Pattern
events - Observer
"I/O streams in Java are the example of decorator".

This is really interesting and helps easily understand the structure and purpose of the patterns, but I am unable to google the right phrase for gathering a broad mass of such examples!

Legacy system has multiple representations of organizations and we need to merge them

Our customer owns several old applications. Each of them has tables to represents organizations, tables named like : “Customer”, “Supplier”, “Member”, “Dealer”, etc. I count about twenty of them. It poses a lot of problems for accounting, reporting, and basic consistency. We would like to merge all these this legacy tables in one table, with one service exposing them. What are the best practices for this matter ?

Answer object and Object Oriented Design

I have doubts about this design:

public abstract class Answer {

    private long id;

    private Question question;

    public Answer(Question question) {
        this.question = question;
    }

   abstract List<String> getAnswers(){
   }
}

And subclassed:

public class SingleAnswer extends Answer {
    private String answer;

    public SingleAnswer(Question question) {
        super(question);
    }

    public List<String> getAnswer() {
        return Collections.singletonList(answer);
    }

   public void setAnswers(Set<String> answers) {
        if(answers.size()!=1)
            throw new IllegalArgumentException("You have to provide only one answer");
        this.answers = answers;
    }

}


public class MultiAnswer extends Answer{
    private List<String> answers;

    public MultiAnswer(Question question) {
        super(question);
    }

    public List<String> getAnswers() {
        return answers;
    }

    public void setAnswers(Set<String> answers) {
        if(answers.isEmpty())
            throw new IllegalArgumentException("You have to provide at least one answer");
        this.answers = answers;
    }
}

MultiAnswer object can have more than one answer (like checkbox) and SingleAnswer object can have only single answer (like answer for open question, or single choice a,b,c,d question).

Now, I want get list of Answer objects and find out what answers they have and use them for some comparison. I make abstract method List getAnswers() for thast purpose but I have doubts if this is a good design, because SingleAnswer can hold only one value/answer and signature of method getAnswers indicated that SingleAnswer can return more than one answer.

Is it good solution or can it be solved in different way?

mercredi 24 janvier 2018

writing a custom get method for a scala map

I have a map which is something like

val m = Map("foo" -> "bar", "faz" -> "baz")

I need to write a custom get method, so that the key can be the key in the map with a number in the end.

So for example:

m.get("foo1") should return "bar"

I am looking for a good scala pattern to solve this problem.

Also I am generating the above map from a for loop using yield, so I can't do something like this

val m = CustomMap("foo" -> "bar")

Any solutions will be appreciated.

Thanks

OOP design - when to have a common base class [Flaw design?]

I have a simplified design as the following (basically a bunch of handlers to handle 2 different types of request: EventRequest and SpeechRequest). Below is the pseudocode:

class SpeechRequest {sessionId: String; slot: String}
class EventRequest {sessionId: String; event: String}

class SpeechRequestHandler; 
class EventRequestHandler;

class SpeechRequestHandler[A/B/C] extends SpeechRequestHandler {
    - handle(request: SpeechRequest) {      
        doSt(request.slot)
    }
}

class EventRequestHandler[A/B/C] extends EventRequestHandler {
    - handle(request: EventRequest) {       
        doSt(request.event)     
    }   
}

There is 2 different dispatchers to find appropriate handlers for each types of requests and forward them to handlers to handle:

class SpeechDispatcher {
    - handle(request: SpeechRequest) {
        handler: SpeechRequestHandler = findHandlerToHandle(request);
        handler.handle(request);
    }
}

class EventDispatcher {
    - handle(request: EventRequest) {
        handler: EventRequestHandler = findHandlerToHandle(request);
        handler.handle(request);
    }
}

Now, i want to refactor and create a base/common classes. Naturally, I came up with this:

class Request {sessionId: String}
class SpeechRequest extends Request {slot: String}
class EventRequest extends Request {event: String}

class RequestHandler {
    - canHandleRequest(Request): bool
    - handle(Request)
}

class SpeechRequestHandler extends RequestHandler {
    - canHandleRequest(request: Request): bool = request instanceof SpeechRequest
}

class EventRequestHandler extends RequestHandler {
    - canHandleRequest(request: Request): bool = request instanceof EventRequest
}

class SpeechRequestHandler[A/B/C] extends SpeechRequestHandler {
    - handle(Request: request) {
        //need to cast to specific type to extract a certain fields to do some operation
        //!! I feel something is not right because of that
        speechRequest:SpeechRequest = (SpeechRequest)request;
        doSt(speechRequest.slot)

        //other operation can work with base Request object; so it's OK
    }
}

class EventRequestHandler[A/B/C] extends EventRequestHandler {
    - handle(Request: request) {
        eventRequest:EventRequest = (EventRequest)request;
        doSt(eventRequest.event)

        //other operation can work with base Request object; so it's OK
    }   
}

The fact that for all SpeechRequestHandler[A/B/C]:handle functions, I now need to cast the Request object to (SpeechRequest) object specifically: speechRequest:SpeechRequest = (SpeechRequest)request;

I feel that there is flaw in my design. If every SpeechRequestHandler I need to cast the object to (SpeechRequest) so that I can do something with those info, does it means that it doesn't make sense to refactor a base class in this case ?

Please could you suggest a better way or a design pattern to handle this cleanly.

Thank you.

Does this class implement singleton design pattern? [on hold]

From Java in a Nutshell

package javanut6.ch01;

import java.io.IOException;

/*
 * A standard scratch pad class that I often use when exploring a simple
 * java library or reminding myself of how Java langauge features interact
 *
 */
public class ScratchImpl {

    private static ScratchImpl instance = null;

    // Constructor
    public ScratchImpl() {
        super();
    }

    /*
     * This is where your actual code will go
     */
    private void run() {

    }

    /**
     * @param args
     * @throws java.io.IOException
     */
    public static void main(String[] args) throws IOException {
        instance = new ScratchImpl();
        instance.run();
    }

}

I wonder the following questions:

why does it define a private field which is an instance of the class itself?

Does the class implement the singleton design pattern?

What is the purpose of not initializing the field in the constructor, but in main method?

Why does the constructor call super(), since there is no explicit super class?

What is the purpose of making main a method of the class, instead of a method of another class?

Thanks.

Service and DAO classes in JAVA

I have 3 DAO and service classes for project, customer, and issues. I have one more jiraService class in which I use the JIRA API. The use case is that I use APIs to create the issue in JIRA for a customer's project. Once the issue is created I store the customer info. in the customer table, the response info. from JIRA in issue table and then store the issue id, customer id in project table so that I know which issue is related to a which customer and project. Now I have some questions -

  1. How should I call the DAO classes from jiraService class? Is it good to directly call the required DAO class as I am in a service class or should I call it through the service class which I have created for that DAO class?
  2. DAO classes are supposed to contain CRUD methods only. But there can be variations in say READ operation. For example, I may want to get projects on the basis of customer name or on the basis of issue id or both. We cannot create a generic GET method for this. So is it considered a good practice to include all required variations of CRUD operations in DAO classes?
  3. How should one DAO class call methods within other DAO class? For example, I have the customer name and I am fetching all project info for that customer. In my project table I have customerId stored so I need to first get the customerID for that customer and then fetch all the projects from project table using customer ID. How should I call the getCustomerID method within customerDAO from projectDAO class?

Storing repeating field values from customizable form

I have a Laravel API + Vue FE app where a user can modify/create custom forms for different entities. The problem I'm facing is I don't know the best way to store and retrieve the "repeater" field type's children values. Ideally I would like to have the ability to have nested repeater fields.

A simplified form_fields table schema:

form_fields
------------------
id
name
type # like text, checkbox, repeater, etc
form_id # the form that this field belongs to
parent_id # the id of the repeater parent

For the form_field_values table, I'm thinking something like this:

form_field_values
------------------
id
form_field_id
value
parent_id # the parent if it's nested in a repeater
answerable_id # morph
answerable_type # morph

This object structure for the form is as follows

form = {
  id: 1,
  name: 'form name',
  fields: [
    {
      id: 1,
      name: 'text_field_name',
      type: 'text',
      value: 'Text value',
      value_id: null,
    },
    {
      id: 2,
      name: 'repeating_type_field',
      type: 'repeater',
      value: null,
      value_id: null,
      // This stores the form field structure
      // When a user adds a new repeating section,
      // This just gets copied into the `collections` property
      children: [
        {
          id: 3,
          name: 'child_field_1',
          type: 'text',
          value: null,
          value_id: null,
          parent_id: 2
        },
        {
          id: 4,
          name: 'child_field_2',
          type: 'repeater',
          value: null,
          value_id: null,
          parent_id: 2,
          children: [
            {
              id: 5,
              name: 'nested_child_field_1',
              type: 'text',
              value: null,
              value_id: null,
              parent_id: 4
            }
          ],
          // When creating values for an entity,
          // `collections` is build on the front end only
          // But when retrieving an entity's form values
          // I can't figure out how to populate this property
          collections: [
            [
              {
                id: 5,
                name: 'nested_child_field_1',
                type: 'text',
                value: 'nested value',
                value_id: null,
                parent_id: 4
              },
              {
                id: 5,
                name: 'nested_child_field_1',
                type: 'text',
                value: 'different nested value',
                value_id: null,
                parent_id: 4
              }
            ]
          ]
        }
      ],
      collections: [ 
        [
          {
            id: 3,
            name: 'child_field_1',
            type: 'text',
            value: 'some value',
            value_id: null,
            parent_id: 2
          },
          {
            id: 4,
            name: 'child_field_2',
            type: 'repeater',
            value: null,
            value_id: null,
            parent_id: 2,
            children: [
              {
                id: 5,
                name: 'nested_child_field_1',
                type: 'text',
                value: null,
                value_id: null,
                parent_id: 4
              }
            ],
            collections: [
              [
                {
                  id: 5,
                  name: 'nested_child_field_1',
                  type: 'text',
                  value: 'nested value',
                  value_id: null,
                  parent_id: 4
                },
                {
                  id: 5,
                  name: 'nested_child_field_1',
                  type: 'text',
                  value: 'different nested value',
                  value_id: null,
                  parent_id: 4
                }
              ]
            ]
          }
        ],
        [
          {
            id: 3,
            name: 'child_field_1',
            type: 'text',
            value: null,
            value_id: null,
            parent_id: 2
          },
          {
            id: 4,
            name: 'child_field_2',
            type: 'repeater',
            value: null,
            value_id: null,
            parent_id: 2,
            children: [
              {
                id: 5,
                name: 'nested_child_field_1',
                type: 'text',
                value: 'some value',
                value_id: null,
                parent_id: 4
              }
            ],
            collections: [
              [
                {
                  id: 5,
                  name: 'nested_child_field_1',
                  type: 'text',
                  value: 'nested value',
                  value_id: null,
                  parent_id: 4
                }
              ]
            ]
          }
        ]
      ]
    }
  ]
}

Creating the above json structure is easy on the frontend. However, I can't quite get the structure of collections right when retrieving an existing entity's values. I think it might be my form_field_values table design, but I'm not sure.

Here's a general idea of the function that I have for building out the collections property of a field.

$entity = Entity::find($id);
// Loads the morphable answers, and the nested answers from parent_id
$entity->load('answers', 'answers.children');

// I have it grouped by the form_field_id for easy retrieval
$answers = $entity->answers->groupBy('form_field_id');

$form->load('fields', 'fields.children');

// Create a fields collection keyed by id for easy retrieval
$fieldsByKey = $form->fields->keyBy('id');

// My thinking is that I'll store the built out 
// collection into this variable
$collectionsByParentId = [];

$valueBuilder = function ($field) use ($entity, $answers, $fieldsByKey, &$collectionsByParentId, &$valueBuilder) {
    // If this field has children it's a repeater type
    // All the children values need to be populated
    // Recurively call this function
    // We need to set $collectionsByParentId, using this field (child's parent) id
    // After the children have been processed it's just a matter of
    // setting the collection from $collectionsByParentId
    if ($field->children->isNotEmpty()) {
        // Recursively run this function on its children
        $field->children->each($valueBuilder);

        // // Set the field's newly created collection in $collectionsByParentId
        $field->collections = $collectionsByParentId[$field->id];
    }
    // If this field is a non repeater field
    // and it is a child of a repeater
    // add the values to $collectionsByParentId by its parent id
    elseif ($field->parent_id && isset($answers[$field->parent_id])) {
        // We need find this field's value info from $answers
        // We know the number of collections based on the count of answers
        // of this field's parent answers
        // If the parent of this field also has a parent,
        // We need to get the answers from the parent's answer's children
        $isSubChild = !isset($fieldsByKey[$field->parent_id]);
        $answerCollection = $isSubChild ? $answers[$field->parent_id] : $answers[$field->id];

        $numOfCollections = count($answerCollection);

        // Iterate the number of collections, correctly inserting the collection
        // at the appropriate index n
        for ($i = 0; $i < $numOfCollections; $i++) {
            // There seems to be a reference problem,
            // so replicate the field to prevent that
            $clone = $field->replicate();

            // If this field's parent doesn't have children answers
            // it is not a child of a nested repeater
            // Add the values from it's own offset the answers
            if (!isset($answers[$field->parent_id][$i]) || !$answers[$field->parent_id][$i]->parent_id) {
                $clone->value = $answers[$field->id][$i]->value;
                $clone->value_id = $answers[$field->id][$i]->id;

                // Add it to the parent's collection
                $collectionsByParentId[$field->parent_id][$i][] = $clone;
            }
            // If the collection values have children,
            // we need to add those children from its parent's child answers
            else {
                foreach ($answers[$field->parent_id][$i]->children as $j => $child) {
                    $clone->value = $child->value;
                    $clone->value_id = $child->id;

                    // Add it to the parent's collection
                    $collectionsByParentId[$field->parent_id][$i][$j] = $clone;
                }
            }
        }
    }
    // If this field is a non repeater field
    // and it isn't a child of a repeater
    // simply add the answer value and value_id
    elseif (isset($answers[$field->id])) {
        $field->value = $answers[$field->id][0]->value;
        $field->value_id = $answers[$field->id][0]->id;
    }
};

// Run all the fields through the function
$form->fields->each($valueBuilder);

I know there's recursion involved due to the nested nature, I just can't quite get the logic straightened out.

Should I change the table structure or am I just not getting the function logic right?

mardi 23 janvier 2018

Combining Composite and Mediator Pattern

I've seen few attempts of implementing such a combination. But my question is if combining these two Patterns is somehow recommended. As it seems to me that the Mediator, by controlling the behaviour of Conposite components, may disrupt the responsibilities logic of the Composite tree itself. May someone tell me if it is wrong and in case what is the good rationale of combining them?

how perl handle pattern with different quotation

As https://perldoc.perl.org/perlrun.html indicates,

-F option specifies the pattern to split on for -a. The pattern may be surrounded by // , "" , or '' , otherwise it will be put in single quotes. You can't use literal whitespace or NUL characters in the pattern.

I tried below commands on a text, but the result is totally the same.

So what's the difference of these pattern quotation in below example?

$ perl -aF"\|" -lne 'print $F[0]' input
Time
2018-01-11 00:00:00
2018-01-11 00:15:00


$ perl -aF'|' -lne 'print $F[0]' input
T
2
2


$ perl -aF/|/ -lne 'print $F[0]' input
bash: /: Is a directory

Design Pattern, OOPS

I have an interface, say IVehicle, which is implemented in 100s of classes, some of them are variety of 4 wheeler and some are two wheeler dervied types.

I need to introduce a new method for all the 4 wheeler classes, lets say there are 50 of them. My challenge is to reduce the effort as much as I can.

I suggested, to introduce a new interface / abstract class with a method definition. But this require to change every 4 wheeler class declaration and extend with an extra parent.

Is there any possible way?