samedi 31 mars 2018

Not sure how to implement this interface

So I'm a little confused about how to implement this interface the right way:

A MasterMind computer player must, at a minimum, return a valid Guess:

public interface MasterMindAI
{
   public Guess nextGuess();
}

MasterMindAIRandom The simplest way to implement the interface is to populate the List of color ids with four random integers from 1 to 7 and to return the associated Guess. This is actually a useful class as it allows you to find bugs related to incorporating the AI into the MasterMind game rather than bugs in the AI itself.

So I understand everything about the list and how to populate it. I'm just confused about how to implement the interface the right way. So my MasterMindAIRandom class has to have a method called Guess nextGuess that creates a List of random numbers, yes? But the return type is of type Guess and the List is a list of ints. How exactly am I suppose to return the Guess?

UML diagram diamond arrow

I do not have much experience with UML diagrams and was coming across a diagram which I didn't fully understood.

When I have the following UML diagram:

UML diagram

What my current understanding is about this UML diagram based on my research is that the observers are aggregated in the subject. And that concreteObserverA and concreteObserverB inherit from Observer.

Questions:

  1. Is my current understanding which I described correct?
  2. I saw in all sources from which I studies UML diagrams that they denote aggregation with an arrow. Is the relationship between Observer and subject still aggregation or is it something else?

Factory-pattern for superclass and its subclasses

I have 3 classes wich are one child of the other: Class C ->(subclass of)-> class B ->(subclass of)-> class A.

Every class is real and I want to choose wich one to instantiate by a method. Can I use Factory-method and so factory-pattern to choose wich class to create?

tank you.

Does adaptor patter is used in my class diagram?

I did my homework that makes some program which has to use adaptor pattern.

But I'm not sure about I used adaptor pattern in homework.

Can you check my diagram and adaptor pattern used?

enter image description here

I designed Car, Plane, Submarine as a adaptor classes which connect Vehicle super class and PrintStates interface.

Am I right?

vendredi 30 mars 2018

GNU Radio programming pattern / control flow graph

I’m about to start developing an application (probably in C#) that has similar mechanics to GNU radio but a totally different purpose.

GNU Radio has a GUI that is like your typical flowchart type editor / drawing tool, but each object displayed on the “canvas” is part of a reactive control flow graph (rather than a flowchart box).

Basically, they are black boxes each having a specific internal purpose and each also having input(s) and output(s) where required.

For the simplicity of explanation let’s say my scope is to create a GUI canvas that I can drag objects on to and a run / stop button (to run the “program”). I suppose in some ways a little like the GUI from programming Scratch the kids programming tool.

I initially have 3 objects.

1) Some type of keyboard input box where I will input some Base64 encoded text. This has only an output that goes into object number 2.

2) This object takes input fed to it (the above encoded text) and converts it back to UTF-8 (its only purpose) and outputs it to the object number 3.

3) This object takes the input fed to it (from object number 3) and outputs it to screen (in its little box).

What these objects do is not important this is simply for example. This is basically how GNU Radio works except its passing digital signal data around rather than text.

My question is what sort of programming patterns does GNU radio use (before I pull it apart) or what sort of OOP type patterns or ideas should I maybe by looking at for this type of application. Or even some good Google links.

I have tried for a few hours now trying to Google something but it’s really difficult to find the right words that don’t return x zillion adverts for flowchart software for sale and such like.

I should also add that new objects (black boxes) can be added later.

Business to DAO tier responsibility in design with JDBC

I have 2 entities: book and category when each book can have reference to its category, and the classical 3 tier architecture: presentation, business logic and DAO tier.

My question is how to implement BookDao.getAll() in terms of dependencies instantiation. Should I instantiate the category object each time for each book (sounds like a RAM wasting), of course I can create and reuse the same category objects inside the getAll(). For example I have 15 books equally divided into 3 category, so I instantiate only 3 redundant objects not 15. Nevertheless my problem is that I already have all those 3 categories in my business tier, it's a bad design decision to pass a reference on the categories collection to the method, because DAO mustn't call business. And I don't know how to avoid performance problems and Java Heap wasting on this categories if the app will scale to 250,000,000 books for example.

Nested loop patterns spaces proplem

So iam supposed to draw this pattern using nested loops

the pattern

And here is my output and code

output

my problem is i can't get the spaces between the stars properly what can i do to make the spaces like the example ?

Design pattern for replacing nested if statemenst (arrow antipattern)

i noticed my code looks really ugly, and is hard to maintain. Basicaly i need do to some person check. Pseudo code is like this (BTW i can't "cut" anything in query, and it's not realy the point of my question):

List<Person> persons = getPersonsBySomeQuery();

if (checkAnyPersonExists(persons)) {
  if (atLeastOneWithGivenNameExist(persons)) {
    if (noOneWithOtherNameExists(persons)) {
      filteredPersons = filterPersonsWithGivenName(persons);
      if (singleName(filteredPersons)) {
        // single person found
        if (someParameterFromQueryIsTrue) {
          if (someComplicatedLogicIsOK) {
            // found exactly one person, all OK!!!
          } else {
            // found exatcly one person with given name, but not OK
          }
        } else {
           // found exactly one person but parameter from query is not OK
        }
      } else {
        // found only persons with given name, but more then one
      }
    } else {
      // found person(s) with given name, but also some with different name
    }
  } else {
    // found person(s), all have different name
  }
} else {
  // noone found
}

So i don't have that much experience with design patterns, but i read about them, and i started thinking i could implement Chain of Responsibility pattern. Like, every if-else could be one element in chain, and also this filter element on line 6 could also be "Chainable".

In the end it could look something like:

AbstractChainElement getCheckChain() {
   return new CheckAnyExist(
          new CheckOneWIthGivenNameExist(
          new CheckNoOneWithOtherNameExist(
          new FilterOnlyGivenName(
          new CheckIsSingleName(
          new CheckOtherParameters(
          new CheckWithSomeComplicatedLogic()))))));          
}

getCheckChain().doChain(persons);

Do you think it's good way to do it or is there anything more elegant?

With this i could construct chain for checking for different check types also, using factory or even abstract factory pattern.

Something like:

FactoryCheckThesePersonsByTheseParameters implements AbstractFactory {

     List<Person> getPersons() {
       // get persons with THIS query
     }

     AbstractChainElement getCheckChain() {
       // check persons THIS way
     }
}

FactoryCheckThatPersonsByThatParameters implements AbstractFactory {

     List<Person> getPersonsBySomeParameters() {
       // get persons with THAT query
     }

     AbstractChainElement getCheckChain() {
       // check persons THAT way
     }
}

Which design pattern a composed object just for proxy purposes relates?

I have my object D which encapsulates different structs(A,B,C in this example). D is mostly for being passed as an parameter to an object called "RealClientInterface". Because D composed of A,B,C which "RealClientInterface" needs to run its functions.

My question if D relates to a design pattern? If it does which design pattern(s) D relates in this case?

Is it a composer since it is being composed of A,B,C? Or it is proxy or builder? Since it is there just as an proxy the real read/write is being done by RealClientInterface?

I need this information for giving a good name to my class D and also documentation purposes.

struct A
{
    //Some data
};

struct B 
{
    //Some data
};

struct C 
{
    //Some data
};

struct D 
{
   A a;
   B b; 
   C c;
};

struct RealClientInterface
{
    void foo ( D& d )
    {
        //reads d.a and inserts d.b
    }

    void foo2 ( D& d )
    {
        //reads d.c and inserts d.b and d.c
    }

    // Many other functions
} ; 

Decorator or Interpreter pattern

So I had an exam and in the question 2(b) was asked to identify which design pattern is this. I wrote Interpreter but I still has doubts it could be Decorator design pattern. My question is did I answer correctly and how do you identify and find the big difference between them? Question 2(b)

How to name factory that has multiple creation methods?

I have the factory with multiple creation methods in.

interface IProductFactory
{
     IProduct CreateX();
     IProduct CreateY(A a, B b);
     IProduct CreateZ(A a, C c);
     IProduct CreateAutoUpdatableProduct(
                  // Func<string, IProduct> is C# friendly type
                  // From abstract view it is
                  // single method that returns the product
                  // or interafcse with this single method
                  Func<string, IProduct> productFactory,
                  IEnumerator<string> configProvider)
}

In this level everything looks fine, but I have name conflict in implementation level.

class ProductFactory : IProductFactory
{
     ...
     IProduct CreateAutoUpdatableProduct(
                      Func<string, IProduct> productFactory,
                      IEnumerator<string> configProvider)
    {
         return new AutoUpdatableProduct(
                        productFactory,
                        configProvider,
                        this);
    }

    class AutoUpdatableProduct : IProduct
    {
        AutoUpdatableProduct(Func<string, IProduct> productFactory,
                             IEnumerator<string> configProvider,
                             IProductFactory productFactory)
        {
              // two parameters with name productFactory above
        }
    }
}

As you can see in code excuse, I have two parameters with the same name in the constructor of AutoUpdatableProduct. Obviously, there is necessary to rename one of them. And here I am stumbled upon the question: What is product factory in my case? Func or IProductFactory? Based on the classical factory pattern i think that true factory is Func. How to rename my interface IProductFactory? IProductCreationService?

jeudi 29 mars 2018

Unisex Bathroom: Threading in Python

Problem:

Males and Females can use a unisex bathroom.

The bathroom has infinite capacity but Males and Females cannot use the bathroom at the same time.

I'm having trouble enforcing the sex-segregation provision. I'm trying to use the LightSwitch design pattern from "Little Book of Semaphores" and I can't figure out why the pattern isn't excluding the opposite sex when a male or female is in the bathroom.

This isn't a homework problem. It's a problem I bombed on in an interview.

Users.py:

class User(object):

def __init__(self, cv, sex, line_full_event):
    self.cv = cv
    self.sex = sex
    self.line_full_event = line_full_event

def enter_bathroom(self, bathroom):
    with self.cv:
        bathroom.enter(self.sex, self.cv)

def leave_bathroom(self, bathroom):
    bathroom.leave(self.sex, self.cv)

class Male(User):

    def __init__(self, cv, sex, line_full_event):
        super(Male, self).__init__(cv, sex, line_full_event)

    def go(self, bathroom):
        logging.debug("Male queueing up")
        self.line_full_event.wait()
        super(Male, self).enter_bathroom(bathroom)
        super(Male, self).leave_bathroom(bathroom)

class Female(User):

   def __init__(self, cv, sex, line_full_event):
       super(Female, self).__init__(cv, sex, line_full_event)

   def go(self, bathroom):
       logging.debug("Female queueing up")
       self.line_full_event.wait()
       super(Female, self).enter_bathroom(bathroom)
       super(Female, self).leave_bathroom(bathroom)

LightSwitch.py:

class LightSwitch:

    def __init__(self):
        self.mutex = Lock()
        self.count = 0

    def inc(self, cv):
        with self.mutex:
            self.count += 1
            logging.debug("inc-ing! count == %d", self.count)
            if self.count == 1:
                cv.acquire()


    def dec(self, cv):
        with self.mutex:
            self.count -= 1
            logging.debug("dec-ing! count == %d", self.count)
            if self.count == 0:
                cv.notify_all()
                cv.release()

Bathroom.py

MALE = 1
FEMALE = 0

class Bathroom:

    def __init__(self):
        self.male_switch = LightSwitch()
        self.female_switch = LightSwitch()

    def enter(self, sex,  cv):
        if sex == MALE:
            self.female_switch.inc(cv)
        elif sex == FEMALE:
            self.male_switch.inc(cv)

    def leave(self, sex, cv):
        if sex == MALE:
            self.female_switch.dec(cv)
        elif sex == FEMALE:
            self.male_switch.dec(cv)

Main.py:

def Main():
    logging.basicConfig(format='%(threadName)s, %(asctime)s, %(message)s', datefmt='%M:%S', level=logging.DEBUG)
    # create Bathroom                                                                                                
    b = Bathroom()
    # create whatever threading objects we need                                                                      
    males_can_enter, females_can_enter = get_cvs()
    line_full = threading.Event()
    for i in range(10):
        if random.randint(0,1) == MALE:
            # create Male user                                                                                       
            user =  Male(males_can_enter, MALE, line_full)
        else:
            # create Female user                                                                                     
            user = Female(females_can_enter, FEMALE, line_full)
        t = threading.Thread(target=user.go, args=(b,))
        t.start()
    logging.debug("we're off to the races!")
    line_full.set()

def get_cvs():
    return (threading.Condition(), threading.Condition())


if __name__ == '__main__':
    Main()

A/B test clients from controller

I am currently using API's from client A in my controller. Sample definition of client A:

class A @Inject()(
    ws: WSClient)
{
  def createSession(request: CreateSessionRequest)
    : EitherT[Future, AppError, ResponseFromA] = 
 {
    //logic. Returns ResponseFromA case class
 }
}

My controller code is:

class MyController @Inject()(
    a: A) {
  def createSession(): Action[JsValue] =
    action.async(parse.tolerantJson) { request =>
      val requestValidation = for {
        request <- EitherT.fromEither[Future](
          checkRequest[CreateCheckout](request.body.toString, mapper))
      } yield {
        request
      }

      val createSessionResult = for {
        createCheckoutInput <- requestValidation
        createSessionResponse <- a.createSession(
          CreateSessionRequest(createCheckoutInput))
      } yield {
        createSessionResponse
      }

      // postProcessing creates a transfer object `SessionResult`
      // from `ResponseFromA`
      postProcessing(createSessionResult) 
}

Now I am planning to migrate to another set of API's which provide similar functionality but different response format. I have created a different client B as follows:

class B @Inject()(
    ws: WSClient)
{
  def createSession(request: CreateSessionRequest)
    : EitherT[Future, AppError, ResponseFromB] = 
 {
    //logic. Returns ResponseFromB case class
 }
}

Notice I have still used CreateSessionRequest in client B as well. This is because input to both set of API's is the same. I would like to A/B test both set of API's. Ideally I would like to use the same controller because controller has a lot of logic which I would need to replicate if I created another controller for client B. Response from my controller would also still be SessionResult because I want to keep these migration changes transparent to all clients using my service.

I was looking at different design patterns like the factory pattern to conditionally select the right client to call based on some rule (say a config value which says to use client B) but I am reaching a dead end because createSession from both clients have different return values. I was also thinking of creating a common business object which I could use to massage the ResponseFromA and ResponseFromB to the common business object but that means I would need to change postProcessing(createSessionResult).

Any tips or pointers on how I could conditionally use client of my choice without changing controller logic too much would be greatly appreciated.

How to sync actor flag with its components status

Game actor is created and initialized with many game state flags. And it takes a few more frames to load actor's components. What's the proper way to sync all these components' working status with this actor's flags.

How to split procedural code in python

I am doing a machine learning program and I am not sure how to split all the code. The program I am making takes two files and outputs a classificator. The steps that are performed are:

  1. Read two files into 2 dataframes
  2. Merge dataframes
  3. Fix columns, preprocess some strings and datetimes
  4. Extract features from objects
  5. Mark these features
  6. Drop infrequent features
  7. Perform feature selection and get ranking of features
  8. Mark left features after feature selection
  9. Drop not needed objects
  10. Build a model
  11. Check accuracy, if ok then return model, if not go back to step 6. and select other features.

This is quite a lot of code and I am not sure how to split it into files/classes.

I though about creating a file such as "preprocessing" where I put steps 1-5, "feature_selection" for steps 6,7, 8, 10 and "model_builing" for step 9. Do you think that it is ok?

Are there any patterns or techniques for designing such a procedural code?

Code is written in python using panas dataframes.

design patterns used by Android components

Last time when I was giving an interview the interviewer asked me the question that What are the design patters used by Android components? so I answered it by mentioning design pattern names like MVP, MVC, MVVM, etc so He interrupted me and told that this is the wrong answer and asked me to find out the answer so I googled it but it will show same as I told in the interview room, So anybody know the correct answer, If yes then please help me with this, Any help regarding this is appreciated.

Is java Runtime class is proper example of Singleton?

I have been reading about singleton pattern for a while now and when I searched for Singleton classes in Java language I found Runtime as an example but when I looked into the source I found very basic Singleton implementation:

private static Runtime currentRuntime = new Runtime();
public static Runtime getRuntime() {
    return currentRuntime;
}
private Runtime() {}

Where as on internet there is a lot written about how a singleton class should be so basically what I wanted to know is which of the Java language class is best fit as a Singleton class example and why?

OOP PHP: How to avoid ORM situation during class design?

Currently, I am working on a project of an online service provider.But I am really confused on class designing.

I have tables for actors like admin, customer, agent and tables for data storage like city, services, category, sub-category, gender.

I have created classes for the admin, customer and agent. But should I create classes for city, services, category, etc. tables which look like an ORM design as well?

Is it good to have one class for each table in a database? If not then please explain how to avoid this situation?

mercredi 28 mars 2018

TypeScript pattern to pass options while creating singleton instance

I have a TypeScript singleton class

Class MySingleton {
    private static _instance: MySingleton;

    private constructor();

    public static getInstance() {
        if (!MySingleton._instance) {
            MySingleton._instance = new MySingleton();
        }

        return MySingleton._instance;
    }

}

Now, I would like to pass some options while creating this singleton instance.

E.g an option that sets the mode of the instance to production mode.

So, that could be implemented by having getInstance accept an options object that gets propagated to the constructor. Then the usage becomes like

MySingleton.getInstance({
    prodMode: true
});

Is this the best way to do this? I feel kind of icky about doing this because when the consumer of MySingleton executes getInstance by passing an options object, there is no way for him or her to know that the passed options object will be used or just disregarded.

I got confused while studying the Statergy pattern, i.e What is the Relationship between Runtime Polymorphism and Strategy Pattern?

I got confused while studying the Strategy pattern, i.e What is the relationship between Runtime Polymorphism and Strategy Pattern?

If there is any relationship please explain with an example.

Fluent interface coding style with standard Python 3 functions? [duplicate]

This question already has an answer here:

I came to Python from Ruby, where OO is baked deeply into the language and coding in a fluent-interface style comes very naturally. Things that seem like they should work in Python 3 just don't. For example, I can fire up iPython and do:

In [21]: foo = list(range(1,11))

In [22]: type(foo)
Out[22]: list

In [23]: foo
Out[23]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [24]: foo.append(11)

In [25]: foo
Out[25]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

But trying to condense this doesn't work:

In [26]: foo = list(range(1,11)).append(11)

In [27]: foo

In [28]: type(foo)
Out[28]: NoneType

Am I missing something, or does OO in Python just not run that deep? I also notice that writing len(foo) is preferred over foo.len() which doesn't exist and has to be written foo.__len__(), which is ugly enough that nobody is going to write it.

What are the Software Architecture patterns and system Architecture patterns?

kindly give me some examples for the both and kindly point out in which systems we are using those patterns?

for which kind of system we can use those patterns?

Android MVP How to get data back from model to presenter

After some time developing personal Android Applications I found that usually Activities get really big and have both logic and UI operations quite mixed up.

So looking for a way to separate logic from UI I came across MVP pattern and now I'm trying to implement it in the application I'm going to develop.

So basically this would be my approach:

enter image description here

The issue I'm facing now is that in order to get data back from model to presenter I'd do something like this:

public static ModelManager (OnePresenter presenter)
{
    localPresenter = presenter
}

And then:

public onReturnData(){
    localPresenter.returnData();
}

The issue is that Model Manager could be called from any presenter at any time so how could I pass a reference of a Generic Presenter?

Thanks a lot.

SVG Scaling the filling-pattern of an path to the paths size

I'm trying to apply a pattern to a few paths. And I'm failing at the fact, that the image, that is contained in the pattern, is 1000px x 500px and the paths I'm trying to apply this pattern to, have different, smaller sizes. I need the pattern to be applied at the size of the containing path.

If it is scaled down and, for example, the width of the pattern is not big enough, I need it to be repeated..

Example Code:

<?xml version="1.0" encoding="UTF-16"?>
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" class="svg" viewbox="0 0 463.99999 611.67727">
    <defs>
      <image id="_TEST_{84F53B36-9301-4E21-BE8C-B33492D12FB3}" x="0" y="0" width="1000px" height="500px" transform="rotate(0) translate(0,0) scale(1, 1)" 
       xlink:href="data:image/png;base64, HERE GOES THE BASE64-STRING OF MY IMAGE...."/>
      <pattern id="TESTID" patternUnits="objectBoundingBox" x="0" y="0" width="1" height="1" preserveAspectRatio="xMidYMid slice">
        <use xlink:href="#_TEST_{84F53B36-9301-4E21-BE8C-B33492D12FB3}" x="0" y="0"/>
      </pattern>
      <pattern id="TESTID_90" patternUnits="objectBoundingBox" x="0" y="0" width="1" height="1" preserveAspectRatio="xMidYMid slice" patternTransform="rotate(90)">
        <use xlink:href="#_TEST_{84F53B36-9301-4E21-BE8C-B33492D12FB3}" x="0" y="0"/>
      </pattern>
    </defs>
    <path d="M 379.20854, 526.88581  L 234.64025, 526.88581 L 234.64025, 537.76729 L 390.09002, 537.76729 L 379.20854, 526.88581" style="stroke:rgb(1,0,0);stroke-width:0.1mm" fill="url(#TESTID)"/>
    <path d="M 390.09002, 351.22757  L 390.09002, 1.46559 L 379.20854, 12.34707 L 379.20854, 351.22757 L 390.09002, 351.22757" style="stroke:rgb(4,0,0);stroke-width:0.1mm" fill="url(#TESTID_90)"/>
</svg>

Result of this

When I change the width and height of the image OR the scale of the pattern, it is not visible in some paths anymore and in some other it translates...

Has anybody an idea how this could be possible, and: Is my question comprehensible? :-D

Greets and Thx :-)

Spark ETL Unique Identifier for Entities Generated

We have a requirement in Spark where the every record coming from the feed is broken into set of entites example {col1,col2,col3}=>Resource,{Col4,col5,col6}=> Account ,{col7,col8}=>EntityX etc.

Now i need a unique identifier generated in the ETL Layer which can be persisted to the database table respectively for each of the above mentioned tables/entities. This Unique Identifier acts a lookup value to identify the each table records and generate sequence in the DB.

1.First Approach was using the Redis keys to generate the keys for every entities identified using the Natural Unique columns in the feed. But this approach was not stable as the redis used crash in the peak hours and redis operates in the single threaded mode.It woulbe slow when im running too many etl jobs parallely. 2.My Thought is to used a Crypto Alghorithm like SHA256 rather than Sha32 Algorithm has 32 bit there is possibility of hash collision for different values.were as SHA256 has more bits so the range of hash values = 2^64 so the Possibility of the HashCollision is very less since the SHA256 uses Block Cipher of 4bit to encryption.

But the Second option is not well accepted by many people. What are the other options/solutions to Create a Unique Keys in the ETL layer which can looked back in the DB for comparison.

Thanks in Advance, Rajesh Giriayppa

which design pattern is best for chat apps for android. mvc or mvp or mvvm. which one is widely used by developers nowadays

which design pattern is best for chat apps for android. mvc or mvp or mvvm. which one is widely used by developers nowadays.

Adobe experience design supports sketch file? Can I open Sketch file in XD?

Is it possible to open sketch source file in adobe experience design. Does XD support sketch file?

What are the Forces or Constrains in Adapter Pattern?

I am just designing a Adapter pattern report.But I don't have any knowledge of Forces or Constrains of Adapter Pattern. So, what are the Forces in Adapter Pattern?

How a pattern that force super class to init all subcasses is called?

I've a super class

class Super
{
    public function __construct(array $params = [])
    {
        if ($params === []) {
            return;
        }

        $this->init();
    }

    abstract public function init();
}

And few sub classes

class SubClass extends Super {
    public function init() { ... }
}

class AnotherSubClass extends Super {
    public function init() { ... }
}

Unable to overwrite decorator pattern method

I'm learning Decorator pattern and I couldn't wrap my brain around the method overwriting.

I have a Phone.ts class that has phoneDescription and cost getter. The cost getter should be overwritten with the cost of the phone brand class that extends to it.

Phone.ts

export default class Phone {
  private description: string;

  constructor(description = 'Default description') {
    this.description = description;
  }

  get phoneDescription() {
    return this.description;
  }

  get price(): number | void {
    throw new Error('This method must be overwritten!');
  }
}

I have a model-specific class. In this example, Pixel.

Pixel.ts

import Phone from './Phone';

export default class Pixel extends Phone {
  get cost(): number {
    return 800;
  }
}

So far so good. I am able to instantiate the Pixel class. And I'm able to get the the cost from the object.

PhoneDecorator.ts

import Phone from './Phone';

export default class PhoneDecorator extends Phone {}

But phone screens are pretty fragile. We need a screen protector. So,

ScreenProtector.ts

import PhoneDecorator from './PhoneDecorator';

export default class ScreenProtector extends PhoneDecorator {
  phone: any;

  constructor(phone: any) {
    super();
    this.phone = phone
  }

  get cost(): number {
    return 50 + this.phone.price;
  }
}

This screen protector should add 50 to the current price of the phone supplied in the constructor.

But I'm getting the error This method must be overwritten!

index.ts

import ScreenProtector from './ScreenProtector';
import Pixel from './Pixel';

let pixel = new Pixel();

pixel = new ScreenProtector(pixel);

console.log(pixel.cost)

C# Method Chaining for Email

I have been looking into stuff like method chaining, Cascade-Lambda pattern etc.

I have created a class which seems to work fine. However, I just wanted to confirm if this is the best way and the right way to implement this.

For the cascade lambda pattern I was unable to use Action<MailManager> action as a parameter to the Send() method. I couldn't figure out how would I use it Any suggestions are welcome.

Here is the code:

 public class MailManager
{
    MailMessage _mail { get; set; }
    SmtpClient _smtp { get; set; }

    public MailManager To(string address)
    {
        _mail.From = new MailAddress(address);
        return this;
    }

    public MailManager From(string address)
    {
        _mail.To.Add(new MailAddress(address));
        return this;
    }

    public MailManager Subject(string subject)
    {
        _mail.Subject = subject;
        return this;
    }

    public MailManager Body(string body)
    {
        _mail.Body = body;
        return this;
    }

    public MailManager IsBodyHtml(bool isBodyHtml = true)
    {
        _mail.IsBodyHtml = isBodyHtml;
        return this;
    }

    public MailManager AlternateViews(AlternateView alternateView)
    {
        _mail.AlternateViews.Add(alternateView);
        return this;
    }

    public MailManager Host(string host)
    {
        _smtp.Host = host; return this;
    }

    public MailManager Port(int port)
    {
        _smtp.Port = port; return this;
    }

    public MailManager Credentials(NetworkCredential credentials)
    {
        _smtp.Credentials = credentials; return this;
    }

    public MailManager EnableSsl(bool enableSsl = true)
    {
        _smtp.EnableSsl = enableSsl; return this;
    }

    public static void Send(MailMessage mail, SmtpClient smtp)
    {
        using (smtp)
        {
            smtp.Send(mail);
        }
    }

    public void Send()
    {
        using (_smtp)
        {
            _smtp.Send(_mail);
        }
    }
}

Android MVP architecture proposal

After some time developing personal Android Applications I found that usually Activities get really big and have both logic and UI operations quite mixed up.

So looking for a way to separate logic from UI I came across MVP pattern and now I'm trying to implement it in the application I'm going to develop.

So basically this would be my approach:

enter image description here

I will have a presenter for each view in the application and then every presenter will call the interface model manager to get the data from different classes.

Some of the model classes need a context, for example FilePicker needs ctx to get a file OnActivityResult. For this I would pass Context from View to Presenter and the to ModelManager.

Do you think it's a good approach or it is not MVP at all?

Thanks in advance.

mardi 27 mars 2018

Non-exhaustive patterns in function (Haskell)

I have two code snippets that throw the same error:

Prelude> sum' [] = 0
Prelude> sum' (x:xs) = x + sum' xs
Prelude> sum' [1,2,3,4,5]
*** Exception: <interactive>:142:1-25: Non-exhaustive patterns in function sum'

and the following as well:

Prelude> prod [] = 1
Prelude> prod (x:xs) = x * (prod xs)
Prelude> prod [1,2,3,4,5]
*** Exception: <interactive>:139:1-27: Non-exhaustive patterns in function prod

I must be missing a pattern, but what is it? Also, how do I such errors? How should I think when defining a function using pattern matching? (I'm asking for a methodolgy/technique)

php the chain of responsibility design pattern

i was learning design patterns. Now i understand the concept of chain of responsibility design pattern. i know how to implement it , but i could not find any useful resource of a practical examples.
All the examples were just about the code
I could not find a practical usage where i can implement this is real life application. I want to know in what kind of senarios this pattern is most likely to be used..

Any one can help describing a real life Solution using this pattern

Software Method invocation tracing

i'm working on a project for my University and i need some help. My aim is to analyze the flow of a software through it's method invocation. I'll try to explain it better with an example. I got a software and i need an output like this: 1) Method A invokes method B 2) Method A invokes method T 3) Method C invokes method A

and so on. I don't know where to start my research. I tried some Reverse Engineering tool, but they tend to give Exa or Binary output, and it's not what i need. Any idea? If possibile, i'd like to have some link with "simple" opensource projects that i could trace (i mean projects with 4-5 classes and less than 20 methods) i can' finde those either.

Thanks in advance.

Strategy Pattern : Same group of function but takes different numbers of parameter

My post's title may not be the appropriate one anyway, I came across a design problem recently and though I think it's a very common but yet I'm not very sure how to solve it.

I have tow type of command sets.

Example for first type:

create_room 4

In the above command create_room is the command and 4 is the data on which the operation will be performed.

Example for second type:

exit

Which does not take any data to operate on.

My strategy is:

public interface ICommandExecutor
{
    stirng Execute (string command);
}
public class CreateRoom : ICommandExecutor
{
    public string Execute (string command)
    {
        //do the job
    }
}
public class Exit : ICommandExecutor
{
    public string Execute (string command)
    {
        //do the job
    }
}

Before that I have a factory to decide which version of implementation to be called based on command input.

ICommandExecutor executor = null;
if (command.Contains("exit"))
{
    executor = new Exit();
}
else if (command.Contains("create_room"))
{
    executor = new CreateRoom();
}

Now my problem here is with the implementation of the class Exit. The method public string Execute (string command) takes a parameter. Which is the command itself; in case if we have any data to operate on (like create_room 4). Command exit takes no data to operate on, so it is totally not necessary to pass the parameter. But my design forces me to pass it. What would be a better way to solve this problem.

Make PHP Storm Aware of inherited Singleton Classes

I have following Code in the Parent Class:

class parent {
    /**
     * Memory of the instances of the classes.
     * @since  1.0.0
     * @access protected
     * @static
     * @var array
     */
    protected static $instances = [];

    /**
     * Singleton
     * Thanks to: https://stackoverflow.com/a/45500679/8148987
     * @since  1.0.0
     * @access public
     * @static
     * @return object
     */
    public static function instance() {

        if ( empty( self::$instances[static::class] ) ) {
            $instance                       = new static();
            self::$instances[static::class] = $instance;
        } else {
            $instance = self::$instances[static::class];
        }

        return $instance;
    }
}

The Child Class:

class child extends parent {

    public function test() {

    }

}

I can do following with this code:

$class_child = child::instance();

But PHP is not aware of the method test().

If I write $class_child-> no proposals are listed. What canI do? The solution mentioned here https://stackoverflow.com/a/32014968/8148987 will not work in my case.

Did I architected my PHP Unit Tests and Code in a bad way?

Good day, since I'm still new to Test-Driven Development I would like to know if the way I structured my Code files and tests acceptable. I created an app for a take-home examination for a job I'm applying to. First, I thought since I'm not sure how to architect my codes (app code not test code) yet.. I placed them in lib/test directory then did automation tests for them (placed the test code at app/tests). Then when they passed I copied the app codes in the app directory well refactored. Is that approach okay or bad? Anyway I removed the lib/test directory and linked tests cases directly towards the app directory.

You can see my re-architected code here => https://github.com/hxhkings/sorterApp

How to include properties via composition?

After having to refactor the inheritance chain in my current project for the third time I typed "Inheritance sucks" into google and found that the problem I'm having is not uncommon and composition is a recommended alternative solution.

I understand how you can use composition to add behavior in form of functions, but I'm having problems to come up with ways to add properties by the same means.

Let's say I want to model tree nodes. Every node has at least the properties name and description.

class Node {
   public string Name { get; set; }
   public string Description { get; set; }
}

Other more specific nodes would inherit those properties, like so:

class StructuredNode : Node {
   public List<Node> Children;
}

How could I archive similar re-usability of the property code without relying on inheritance and the problems that come with it?
Is there a design pattern for this or do I have to use inheritance in such a case?

Thanks in advance!

Understanding MVVM Architecture in iOS

I have few questions in order to understand the MVVM architecture for ios as below -

  1. How Is Model different from the view-model? The model also has the data and why do we need to write and update the same properties in view-model (Repetitive code)?
  2. Creating two-way data binding between view and view-model can be good in form validation. Any other application except it?
  3. Should we use KVO to create 2 binding between view and view-model? Any disadvantages anyone experience so far?
  4. Should we put Networking(API data fetch) Code inside view-model?

Is there a term for when two methods of the same object are on the stack, with a method of a different object in between?

I'm working on a best practices guide, and there's a particular (anti)pattern I want to mention; unfortunately, I don't know the official name for it. Here's an example:

Suppose we have two objects, master and slave, whose basic interface looks like this:

class Master {
    Slave slave;

    public void startSlave() {
        slave.doWork();
    }

    public void onSlaveFinished() {
        slave.dispose();
    }
}

class Slave {
    Master master;

    public void doWork() {
        // ...do some work

        master.onSlaveFinished();

        // ...maybe do something here?
    }

    public void dispose() {
        // dispose of all resources held by this object
    }
}

In this arrangement, when master.startSlave() is called, the stack will end up looking like this:

slave.dispose()
master.onSlaveFinished()
slave.doWork()
master.startSlave()

The problem here is that when slave.dispose() finishes, slave.doWork() is still running, and it might try to do something with the resources that slave no longer holds.

So, my question would be, is there a name for when the stack ends up looking like this? Specifically, I mean that object A calls a method of object B, which ends up calling another method of object A, which can then leave object A in an inconsistent state.

I've tried googling a few terms I could think of ("stack overreach", "stack interleaving", "stack sandwich") but none of those seem to be recognized.

C# best pattern to change target respository implementation through configuration

I am not very experienced in design patterns. I am creating an webapi application using asp.net core 2.0. I want to implement a design pattern so that i can configure whether to use database repository to save to sql database or file repository for saving to file or i will use messaging service to send as a message to a queue.

Can anyone suggest me what is the best pattern to achieve this?

Thanks

Python application build

I am building an application for data processing and wonder what is the best approach / design pattern to use to let user to decide what application features to run

e.g. to decide what data source to choose, to decide about the data output destination if there are multiple options.

I have solved it by creation of settings.py module with a dictionary in which I set right items to 1 and I read the variable storing the dictionary and run functions with globals() depending on settings dictionary item selection.

What is the standard approach to solve such application design problem? What is the good practice?

lundi 26 mars 2018

C# Update Modified properties in database

I have a class having a lot of properties which can be modified from outside. At the end of setting all the properties I wanted to update only the modified fields in database, so what would be the efficient way?

Eg. Let say below is my class

public class SomeClass {
    private int field1;
    private string field2;
    private string field3;
    private byte field4;

    public int Field1 {
        get { return field1; }
        set { field1 = value; }
    }

    public string Field2 {
        get { return field2; }
        set { field2 = value; }
    }

    public byte Field4 {
        get { return field4; }
        set { field4 = value; }
    }

    public string Field3 {
        get { return field3; }
        set { field3 = value; }
    }

    public SomeClass() { }

    public bool FillClassVariablesWithCurrentDatabaseValue() {
        //Fill the class variables with current database values
    }

    public bool UpdateModifiedFields() {
        //Only update the modified fields in database
    }
}

Now to know whether the field has been updated or not, I will have to add that many boolean variables in the class as below

public class SomeClass {
    private int field1;
    private string field2;
    private string field3;
    private byte field4;

    private bool field1Updated;
    private bool field2Updated;
    private bool field3Updated;
    private bool field4Updated;

    public int Field1 {
        get { return field1; }
        set {
            if (field1 != value) {
                field1 = value;
                field1Updated = true;
            }
        }
    }

    public string Field2 {
        get { return field2; }
        set {
            if (field2 != value) {
                field2 = value;
                field2Updated = true;
            }
        }
    }

    public byte Field4 {
        get { return field4; }
        set {
            if (field4 != value) {
                field4 = value;
                field4Updated = true;
            }
        }
    }

    public string Field3 {
        get { return field3; }
        set {
            if (field3 != value) {
                field3 = value;
                field3Updated = true;
            }
        }
    }

    public SomeClass() { }

    public bool FillClassVariablesWithCurrentDatabaseValue() {
        //Fill the class variables with current database values
    }

    public bool UpdateModifiedFields() {
        //Only update the modified fields in database
        string parameters = string.Empty;
        if (field1Updated)
            parameters += "field1=@field1";
        if (field2Updated)
            parameters += "field2=@field2";
        if (field3Updated)
            parameters += "field3=@field3";
        if (field4Updated)
            parameters += "field4=@field4";

        //code to update these fields
    }
}

But since my class has a lot of variables, I don't think this approach is good. Any suggestion will helpful.

Can I somehow trigger an "event" when a property changes?

I have a property class

class Prop
{
public:
   Prop(const std::string &key);

private:
   std::string Key;
   std::string Value;

public:
   void Prop::operator=(const std::string &value) 
   {
      this->Value = value;
   }
};

Then I have a user class

class User
{
public:
   User();

public:
   Prop Name;
};

So let's say I use it.

User user;
user.Name = "Suzie";

When I set the Name property, is there a way for the User object to know that a change was made to one of its Prop's?

Is it solid design practice to mix 2 different js frameworks in one website?

For example, put both angular logic and vue logic in one project, 2 separate js files?

Or is it better to stick with one approach coming from one framework?

Does observer design pattern method violate SRP when do 2 things: setting and notifying

I just read this sample code from the observer design pattern from this link. However, could anyone please explain whether the setState method is doing 2 things (setting the state and notifying the observers)?

If Yes, then does the method setState violate the single responsibility principle (SRP)?

If No, then how we could understand the SRP correctly? Thank you in advance.

public class Subject {
   private List<Observer> observers = new ArrayList<Observer>();
   private int state;

   public void setState(int state) {
     this.state = state;
     notifyAllObservers();
   }

   public void notifyAllObservers(){
     for (Observer observer : observers) {
        observer.update();
     }
   }

   // [...omitted other unrelated methods...]
}

How to match a model to it's closed generic validator. Is service locator the only answer?

I have a base class of type Car:

public abstract class Car
{
{

And around 50 derived types of Car e.g:

public class CarA : Car
{
}

public class CarB : Car
{
}
// etc ...

To make things trickier the base class has several properties which are also abstract types. These abstract types have varying numbers of derived types:

public abstract class Car
{
    public abstract Engine Engine { get; set; }
    public abstract ICollection<Seat> Seats { get; set; }
}

public class CarA : Car
{
    public Engine Engine { get; set; }
    public ICollection<Seat> Seats { get; set; }

    public CarA()
    {
        // Setting defaults.
        Engine = new EngineA();
        Seats = new List<Seat> { new SeatA(), new SeatA(), new SeatB(), new SeatC() };
    }
} 
// etc ...

These objects are passed into an api and are deserialised at runtime. My controller accepts a base type of Car and what I want to do is validate the car and all of it's properties. In the past I would have added an IsValid() method to each car and called an IsValid() method on the class. This is nice and clean.

public class CarsController : ApiController
{
    [HttpPost]
    public IHttpActionResult AddCar(Car car)
    {
        car.IsValid();
        // Save car to store
    }
}

Now to the problem.

Calling IsValid() doesn't allow me to do dependency injection and I would like to be able to separate out the model from the validation logic.

This introduces lots of validation classes:

public class CarValidator : IValidator<Car>
{
    public bool IsValid(Car car) { // validation logic here }
}

public class CarAValidator : IValidator<CarA>
{
    // The probelm with validating the seats is the same problem as with validating the car.
    // In this case there is only a small number of seat validators so I have injected them all in.
    private readonly ICollection<IValidator<Seat>> seatValidators;

    public CarAValidator(IValidator<Car> baseValidator, ICollection<IValidator<Seat>> seatValidators)
    {
        Include(baseValidator);
        this.seatValidators = seatValidators;
    }

    public bool IsValid(CarA car) { // validation logic here }
}

I would like to be able to get the validator that matches the derived type in a clean way. Some suggestions I have seen online include:

  1. Inject the IOC container into the controller and use the service locator pattern to find the correct validator.
  2. Create a factory that uses the service locator pattern inside it and inject this into your controller.
  3. Inject a collection of all of the validators and search through them to get the correct type. This is the appraoch I have gone with but I have concerns about having to create 50 validators per request when in reality only one is needed. Bear in mind that each validator can have lots of other collections for validating.

Is there a clean pattern I can use to get the correct validator for the correct type or should I just resort to using the Service Locator (anti) pattern?

Communication between microservices / responsibilities

I'm new with microservices, and after reading many documentation, I'm still having some doubts about many things. I'm putting an example of what I want to achieve now:

Scenario:

  • Microservice architecture.
  • The FileServer will store files from several sources.
  • Each microservice has its own database.

TemplateService database:

  • TemplateId (PK): guid
  • FileId (~FK): guid
  • TemplateName

FileService database:

  • FileId (PK): guid
  • FileName
  • Path

Use case: A user wants to upload a template to the application.

Questions: (and my ideas)

enter image description here

Who creates the GUID (FileId)?

  1. UI creates the GUID, and calls both, Template Service and File Service.
  2. UI calls Template Service and this service creates the GUID, and then call the File Service

Who deals with the File Server?

  1. UI sends the File directly to the FileServer (or maybe to another service such as FileManager?)
  2. UI sends the File to FileService, and this service store it in the FileServer.

Implicit use of symbol from a static library

I come to submit a problem I have while trying to import symbols from static library implicitly.

Let me set up the problem with a peace of simplified code:

I have 3 projects: - a static plugin handler project that defines a registry class, it is linked in the other two projects - a static plugin project - a final project that has a plugin handler and "load statically" the plugin.

first, the static plugin handler project:

struct PluginType
{
    virtual void doMyStuff() = 0 ;
};

typedef PluginType* (*PluginCreator)();

struct Registry
{
      std::map<std::string, PluginCreator> _item_list;
      static Registry& instance()
      {
            static Registry singleton;
            return singleton;
      }
      static PluginType* create(std::string const& name)
      {
      // call the creator function that returns an PluginType*
        return instance()[name]();
      }
};

struct RecordInRegistry
{
     RecordInRegistry(std::string const& key, PluginCreator new_item_creator)
     {
          Registry::instance()._item_list[key] = new_item_creator;
     }
};

Now, a static plugin project

struct ADerivedItem : public PluginType
{
    virtual void doMyStuff() override
    {
        //some really interesting stuffs
    }
    static PluginType* create() { return new ADerivedItem() ; }
}


export "C" const RecordInRegistry i_record_derived_item_class("derived_item", &ADerivedItem::create);

Then, the final project where i use the plugin. This project links the two other porjects !

int main()
{
    PluginType*  my_instance = Registry::create("derived_item");

    return 0;
}

What I hope is that I will be able to register my static plugin just by linking the static library plugin to the project.

It almost worked ! The only problem I got is that the symbol "i_record_derived_item_class" from the static plugin is not explicitly used in the final project, thus this symbol is not imported from the static plugin lib !

I work on visual studio, i found a simple fix that consists in forcing the symbol import, something like /INCLUDE:i_record_derived_item_class, and everything works fine.

I want to know if you see a work around to this, what I would like is to be able to add this kind of static plung just by linking it, without having to add anything more than /LINK:myStaticPlugin.lib

Any idea ?

Moreover it would be really nice to avoid MSVC-specific solution.

Thanks in advance !

dimanche 25 mars 2018

How to Search and count pattern from list of files in java

I have a list of files in a folder and need to search 3 patterns/words and count no. Of occurences of specific types. Example, in these 3 patterns I will a colors (Red, Blue, Green etc..) and each of these colors has START (First index) and END(last Index). I need to fetch the count each of these indexes for each colors. Hope my question is clear, please let me know How can i achieve it

Broadcast or Multicast Pattern (SQS and SNS)

Following is a message design pattern :

enter image description here

Step 1- Application sends message to SNS Topic

Step 2- SNS publishes message to subscribed SQS queue .

As per following definitions :

Broadcast : Message is published to all end points.

Multicast : Message is published to selected endpoints.

Above diagram can be interpreted as Option 1 - Message is published to selected SQS queues which are subscribed to SNS topic , multicast pattern

OR

Option 2 - Message is published to all subscribed end points,broadcast pattern

how should this design pattern be interpreted ?

Bomberman-like game in java

I'm trying to develop a Bomberman-like game for my programming course project.I have to do it in 5 different parts(phaze) and it should be well designed.I have no idea about architecture?!and i don't know where to start? first part is about map and gui of it.please help me with your tips.

Laravel job for Mailables, common object

I create Laravel Job for sending emails and I have multiple Mailable classes. Can I create object whose point to my Mailable classes?

My Job class:

class SendMail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $emailObject;

    public function __construct($emailObject)
    {
        $this->emailObject = $emailObject;
    }

    public function handle()
    {
        \Mail::to($this->emailObject->user->email)->queue($this->emailObject);
    }
}

I execute this with:

 $this->dispatch(new SendMail(new Profile($user)));

or

$this->dispatch(new SendMail(new Newsletter($user)));

I would like to create object or pattern which will allow me to create constructor with object in my job. Like this:

class SendMail{

        public function __construct(CommonMailObject $emailObject)
        {
            $this->emailObject = $emailObject;
        }
}

It's a good way?

eg. Profile class:

class Profile extends Mailable
{
    use Queueable, SerializesModels;

    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }


    public function build()
    {
        return $this->from('', '')
                    ->subject('')
                    ->view(EmailType::PROFILE);
    }
}

Which design pattern is used in try catch ?

Which design pattern is used in try and catch? In java, we use try catch block mention above.

try{
    //code
}catch(Exception ex){
   //handle exception
}

samedi 24 mars 2018

Designing model in REST API [duplicate]

This question already has an answer here:

I am working on a web project (joined to a team) where there is one model used to persisting data and exchanging data with clients (both receiving and sending) (15-20 different types). Due to this, in single model class we have properties ignored by ORM (like collection of many-to-many connected resources) and ignored by response serialization (like implementation of many-to-many with linking class). Also we have some other problems emerging from this like model validation.

So I tried to decouple this to DTOs used in receiving data from clients and data model used in ORM and sending data back. But I encourage some design problems.

  1. How should I rewrite data from DTOs to data model. Is it responsibility of data model or DTO or something third (like some kind of rewrite service which received both DTO and data model instance?

First:

class DTO 
{
    void Update(Model model) {}
}

class Model
{
}

Second:

class DTO 
{
}

class Model
{
    void Update(DTO dto) {}
}

Third:

class DTO 
{
}

class Model
{
}

class RewriteService
{
    Update(Model model, DTO dto) {}
}

  1. Should I separate domain model from data model and then domain model should base on data model?

Example:

class Data
{
}

class Model
{
    private Data _data;

    Model(Data data)
    {
        _data = data;
    }
}

  1. Should I use DTOs also to sending data to user? If so where is best place to put invocation of rewrite logic? In controller action? Or during response processing (like JsonConverter)?

I am trying to implement this as good as possible and learn how generally this should be designed.

Can I use Command design pattern for operations with different number of parameters and different return types?

I work on a project which has many different operations like file operations, registry operations, process operations, finding minimum requirements etc. All these classes are getting injected into one class , thereby, making it's coupling very high. I came across command pattern which seemed like a good idea for this project. But my operations take different parameters and have different return types. Command pattern had only one execute method with void as return type. Is there a way I can use this pattern for this project to reduce coupling or should I use some other design pattern?

Class instance stored in static field - Java

1) what's the purpose of storing a class instance into a static variable (INSTANCE)

2) why do we have 2 cascade static methods main and start?

3) why o we do lazy init in controller()

thanks

code below is taken from Interactive Brokers ApiController

public class ApiDemo implements IConnectionHandler {

static {
    NewLookAndFeel.register();
}
public static ApiDemo INSTANCE;

private final IConnectionConfiguration m_connectionConfiguration;
private final JTextArea m_inLog = new JTextArea();
private final JTextArea m_outLog = new JTextArea();
private final Logger m_inLogger = new Logger(m_inLog);
private final Logger m_outLogger = new Logger(m_outLog);
private ApiController m_controller;
[...]

ILogger getInLogger() {
    return m_inLogger;
}

ILogger getOutLogger() {
    return m_outLogger;
}

public static void main(String[] args) {
    start(new ApiDemo(new DefaultConnectionConfiguration()));
}

public static void start(ApiDemo apiDemo) {
    INSTANCE = apiDemo;
    INSTANCE.run();
}

public ApiDemo(IConnectionConfiguration connectionConfig) {
    m_connectionConfiguration = connectionConfig;
    m_connectionPanel = new ConnectionPanel(); // must be done after connection config is set
}

public ApiController controller() {
    if (m_controller == null) {
        m_controller = new ApiController(this, getInLogger(), getOutLogger());
    }
    return m_controller;
}

private void run() {
    m_tabbedPanel.addTab("Connection", m_connectionPanel);
    m_tabbedPanel.addTab("Market Data", m_mktDataPanel);
[...]

}

vendredi 23 mars 2018

Design architecture of an application that match customer signature

Needed architecture guidence for the appropriate plateform to create an applications which will match input signature of a customer on the basis of initially given 5 samples.

For example at the time of onboard we have taken 5 samples of customer signature after that on each transaction match input signature with initial samples.

Java - Managing multiple asynchronous servlet requests and placing them in a queue to perform tasks

I'm using a Bootstrap Krajee FileInput widget on a webpage. Hundreds of photos are uploaded to the server through this widget and they are all sent individually as a set of asynchronous calls. The issue is that our server is having difficulty handling hundreds of photos at once. It isn't a network issue. I'm leaning more toward it being a file IO/database performance issue.

I need a way to put these photos all into one queue on the server side and then pop them off, do the work, and send a JSON response back with the servlet.

Can anyone point me to a pattern (or implementation of a pattern that would work well here? Am I completely off base?

I included a quick drawing illustrating what I think should happen.

drawing

Develop a basic game using design patterns to enhance the usability of a game

I was tasked with creating a system that takes advantage of design patterns in order to improve the usability of the system (does not have to be a game). Additionally, we also have to create the system twice using two different design patterns.

I decided to create a game of tic tac toe. The first design pattern that will be implemented is the command design pattern, which will give the player the ability to undo his/her move.

The issue is I cant think of how a second design pattern would help improve the usability of a game of tic tac toe. What design pattern would be best suited towards the problem. (keeping in mind that it has to in some way improve directly the usability of the system).

I think the task is a bit weird. My understanding of design pattern is that you should not aim towards it, rather use it to improve the overall quality of your code. That being said, the question states that I have to put it as a primary goal.

Controlling service flow from the Caller method

Is it correct to control how the service works from the caller of this service? I had such a problem today, and don't know if my solution is good or not. Hope someone more advanced can give me a feedback. Here is my problem:

I have got a service with method Foo:

public class Service
{
    public int? Foo(int? number, bool throwException)
    {
        int? result = number;

        if (result == null)
        {
              var result = ...
              if (result == null && throwException)
              {
                    throw new Exception("ZZZZ");
              }
        }

        return result
    }
}

Now in Caller class I got 2 methods where I invoke this Service:

public class Caller
{
    public void Test1()
    {
        ...         
        Service.Foo(number, TRUE);
        ...
    }

    public void Test2()
    {
        ...         
        Service.Foo(number, FALSE);
        ...
    }

As you can see for Test1 im sending flag throwException TRUE, and for Test2 FALSE, is it good practice to control how the Service's flow go from the Caller's methods?

Practical (from the Industry) usage of Java 8 features [on hold]

My company has been using the Java 8 JDK for quite some time now, however almost all of our developers are continuing to use the older java 6/7 coding techniques.

I am trying to motivate the R&D group to step out of their comfort zone and use the many goodies Java 8 provides, by creating a presentation of practical usage of the Java 8 features.

A classic example from my experience is using a lambda operation when instantiating an anonymous inner class:

// using an anonymous class
Runnable r = new Runnable() {
  @Override
  public void run() {
    System.out.println("Hello");
  }
};

// using a lambda expression
Runnable r2 = () -> System.out.println("Hello");

My planned presentation will not show 'Hello World' examples, but rather more common issues encountered during SW engineering which can be solved rather easily using the Java 8 features.

My questions is this : Can you provide an actual, practical example of using a Java 8 feature (code snippet included) which showcases the benefit of the feature using an actual, non trivial (ie - hello world) example?

A few words on what the actual benefits were (better performance, improved code readability, less boilerplate code, better implementation of design patterns, etc...) would be greatly appreciated

State Design Pattern Usage In Tennis Kata

I am solving the famous Tennis Kata Problem

I have a basic question around state design pattern. The programme needs to output the score for a tennis game.

Below enum represents the different scores a player in tennis game can have :

public enum Score{
Love,
Fifteen,
Thirty,
Fourty,
Deuce,
Advantage,
Game
}

Typical classes I am planning to use here are : TennisGame (main class for handling logic), Player (will maintain its own Score), ScoreCalculator (have Score manipulation logic based on Rules) The scores will be changed when an external event happens which indicates which user has scored the point.

The question here is - how the logic to track score changes should be handled ?

Very naive approach will be :

if(score == Love){
  score = Fifteen; //move score to Fifteen 
}else if(score == Fifteen){
  score = Thirty; //move score to Thirty
}

But this will lead to a lot of if else conditions. I am thinking to use a state pattern for this.

But the question here is , the context here (e.g: TennisGame class) which will encapsulate State won't be doing anything based on State changes.

It is just returning the score once a point is scored by a player.

Can anyone please advice what should be the correct design using State pattern here ?

Why are there language-specific "js\java\python deisgn patterns? Should they be universal?

Or do those design patterns address some specific things, nuances related to each language's grand philosophy, idea that it has?

This is not subjective, question, languages do have different design patterns.

Can I have my core logic to update object status in Aspect


I have a requirement where I will be performing a set of operation in a chain pattern ClassA->ClassB->ClassC by invoking common method action(). Ideally ClassA, ClassB and ClassC implements interface IClass having method action().

At the end of action() method, its status(failed/success) should be updated in the Database.
So my doubt is,
- Is it a good design to leverage Aspect's around advice for method "action" and update the status in Aspect class once the action got executed.
- Our since it is core logic to update the action status, it shouldn't be part of cross-cutting framework like aspect?

How to implement patches for a project?

I am working on a NodeJs, AngularJs and MongoDB app. Every time I made some changes in the existing DB design I create a new route to update the existing records. I am new in web development and still learning new ways to improve my skills.

In my current issue, I made few changes in the Model design by introducing new fields and removing few other fields. I got the solution to update the DB design by mongoose for each or async for each.

But I want to implement a solution in which when an admin login he can see the new patches available and the old one installed.

Any suggestion which can point me into the right direction will be really helpful.

jeudi 22 mars 2018

Design patterns for finding a match

Need assistance in structuring my code with design patterns.

So I have a single method in service class that looks like this. The constructor loads a json file into a List<Option> of Option class instances. Finally when the service method is called it does some logic to find the Option match based on the parameter values and returns a new instance of 'Tool' class with the configured "options".

public Tool BestOptionFinderService.FindBestMatch(string value 1, int value2, int value3, .. bool value20, etc...) {..}

I'm not sure if I a "service" class is correct for this versus a "factory" or something else. I would appreciate your thoughts and suggestions on how you would design your code for this problem or similar.

Pyramid pattern inside pyramid using for loop

I was going through simple pyramid pattern code and i got stuck on this one file]1

how can i achieve this in any language possible. thank you for your help in advance.

How to model and apply four different types of discounts on items bought by User?

I am working on an Online store in Scala. I want to apply discount on items added to the Cart by User. The discounts are of following types:
1) Buy some get some items free
Example: Buy 3 T-shirts Get 2 Free
2) Buy some get some percentage discount
Example: Buy 3 T-shirts Get 10% discount
3) Buy some get some items free - Applies on whole category
Example: Category: T-Shirts
Item1 : TShirt One
Item2 : Tshirt Two
Now the discount should get applied on all the items under "T-Shirts" category
4) Buy some get some percentage discount - Applies on whole category Same as 3. , just we need to give some percentage discount, example 10% discount on all T-Shirts

Can someone tell how to model and how can we handle to apply these discounts?

Very simple event driven jQuery plugin design pattern

Sometimes I have multiple elements which need a click callback function with some common functionality, and have implemented doing so as the following:

function deleteRecord(elem, url, type) {
    if (confirm("Are you sure you wish to delete this "+type+"?")) {
        $.ajax({
            type:'DELETE',
            url: url,
            dataType: 'json',
            success: function (rsp){
                $(elem).closest('tr').remove();
            },
            error: function (xhr) {
                alert('Error: '+xhr.responseJSON.message);
            }
        });
    }
}

$("#manual-list img.delete").click(function() { deleteRecord(this, '/1.0/manuals/'+$(this).closest('tr').data('id'),'manual')});

Instead of using a function, I've been trying to create a very simple plugin. I've successfully created flexible jQuery plugins as described by https://learn.jquery.com/plugins/advanced-plugin-concepts/, however, I think doing so for these types of applications is overkill, and wish to use a drop-dead plugin design pattern. My latest attempt is below, however, I have been unsuccessful passing it the url argument which is derived by the element to which the plugin is applied.

What options are available for a very simple and concise jQuery event driven plugin?

(function( $ ){
    $.fn.deleteRecord = function(url, type) {
        console.log('init', url, type, this, url.call(this, url, type));
        this.click(function(){
            //Confirm that this.each(function(){...}) is not required
            console.log('onClick', url, type, this, url.call(this, url, type))
            if (confirm("Are you sure you wish to delete this "+type+"?")) {
                console.log('onConfirm', url, type, this, url.call(this, url, type))
                var e=this;
                $.ajax({
                    type:'DELETE',
                    url: url.call(this, url, type),
                    dataType: 'json',
                    success: function (rsp){
                        $(e).closest('tr').remove();
                    },
                    error: function (xhr) {
                        alert('Error: '+xhr.responseJSON.message);
                    }
                });
            }
        })
        return this;
    };
})( jQuery );


$("#manual-list img.delete").deleteRecord(function(){'/1.0/manuals/'+$(this).closest('tr').data('id')},'manual');

Reference the constructor caller in the constructor signature (bad pattern ?)

I often bump on problems like the ones in these examples :

The Game class instantiate the class GamePhysics.

But I need to have access to some Game properties inside GamePhysics.

I would say the straightforward design would be to have a GamePhysics(Game game) constructor and call it inside Game class using this.

//Game class code
physics = new GamePhysics(this);

This simple way to solve the problem seams to be poor up to me.

Are there patterns that handle these kind of issues that would be more elaborated ?

Another example (which is the one I am currently bumping on) : Orchestrator class contains a list of ActionBase with different derived classes Action1, Action2... Depending on logics in action methods, Orchestrator must register the action to a new list. Using the instance of Orchestrator referenced inside ActionBase, I could call orch.Register(this) inside ActionBase code.

class Orchestrator
{
  List<ActionBase> startActions;
  List<ActionBase> registeredActions;

  public void Register(ActionBase action)
  {
    //some custom logic related to orchestrator
    //...

    registerdActions.Add(action);
  }

  //instantiate actions
  public void CreateStartActions()
  {
     startActions.Add(new Action1(this)); //Do I need to have 'this' ?
     startActions.Add(new Action2(this));
     startActions.Add(new Action1(this));
  }
}

And :

class ActionBase
{
  private Orchestrator orch;   

  public ActionBase(Orchstrator orchestrator) //I am unhappy with this signature
  {
    orch = orchestrator;
    //...
  }

  //...
  //somewhere in the relevant place
  orch.Register(this);
}

It seams odd to me that what is "inside" points towards what contains it. Is there a turnaround ?

Optimiziation of overlapping 2D-point-patterns

A brief overview of what already exists:

I have a set of hundreds or thousands of 2D-points (x and y) where i should find all occurences of a given pattern. The pattern is also a set of 2D-points (x and y), but significant smaller. The first set is called "point-cloud" and the second just "pattern".

Again, to clarify: I really need to find all occurences/matchings, even if it is just rotated or covers the same points that are already included in another matching. In a big set of points there are thousands or even millions of matchings that can be found.

I have already a working solution / algorithm for this - it work fine.

Where is the problem / challenge now?

I now have to find/filter out a set of matchings that perfectly fits the point-cloud - ideally without overlapping. The result should be a (nearly complete) covered point-cloud.

Does someone know interesting research-area, that focus on this problem? Is it even solvable at the moment (without an unrealistic amount of calculation power)? Are there papers covering this problem? Or maybe a heuristic that delivers "good" results?

mercredi 21 mars 2018

Hierarchical Tree view Using JSON in MVC

Can you help me to complete the code.

Need to use the JSON data for showing their Hierarchical view.

Need to use composite pattern in MVC.

could you please help me ?

i tried searching internet for composite pattern but i got like adding and removing the data from the object. as already have data in the object after reading the JSON using java deserializer . but i want to display the data from the object.

Regards, Jayson.

c++ Circular includes (implementing component pattern) [duplicate]

This question already has an answer here:

Implementing the Component pattern in C++, I came upon a problem related with includes.


I have an Entity class, which has the following components: Renderer, Physics and Collider. They inherit from Component, which has a single virtual method Component->update(elapsedTime) and a reference to the Entity it belongs to.

Each time an Entity is updated, its components are updated too. As the components alter the Entity's state, I thought it would be a good idea making them have a reference to the Entity they belong too (I could pass the Entity as a parameter in the Component->update() call but for performance I prefer not doing so).

Now I must include Renderer, Physics and Collider from Entity, and include Entity from Component. Luckily, Entity calls methods from the above but Component just stores a reference to Entity, so I should include normally Renderer, Physics and Collider from Entity, and forward declare Entity from Component. After doing so, I found a problem which I cannot solve or know how to investigate. So I tried the other way around, and other problems risen up.

  • Including normally Renderer, Physics and Collider from Entity, and forward declare Entity from Component:

A class which includes Entity would complain saying that Entity is ambiguous. This is due to (I think) that class loading Entity, then loading its Components which forward declare Entity. How can I forward declare Entity without having other classes complaining about this ambiguity?

  • Including normally Entity from Component, and forward declaring Renderer, Physics and Collider from Entity:

In my Entity->update() method I do this->collision->update() which breaks, by saying that pointer to incomplete class is not allowed.

How can I solve this without changing my class structure or behavior?

Here are the files, using the first example (including the components and forward declaring Entity from Component:

Entity.h

#ifndef ENTITY_H

#define ENTITY_H

#include "Collision.h"
#include "Physics.h"
#include "Renderer.h"
#include "TextureRenderer.h"

using namespace Components;

namespace Entities
{
    class Entity
    {
        public:

            Entity();

            Collision* getCollision();

            virtual void update(float elapsedTime);

        protected:
            Collision* collision;
            Physics* physics;
            Renderer* renderer;
    };
}
#endif

Entity.cpp

#include "Entity.h"

namespace Entities
{

    Entity::Entity()
    {
    }

    Collision* Entity::getCollision()
    {
        return this->collision;
    }

    void Entity::update(float elapsedTime)
    {
        collision->update(elapsedTime);
        physics->update(elapsedTime);
        renderer->update(elapsedTime);
    }

}

Component.h

#ifndef COMPONENT_H

#define COMPONENT_H

namespace Components
{
    class Component
    {
        public:
            Component(Entity* entity);

            virtual void update(float elapsedTime) = 0;
        protected:
            Entity* entity;
        private:
            friend class Entity;
    };
}

#endif

Component.cpp

#include "Component.h"
#include "Entity.h"

namespace Components
{
    Component::Component(Entity* entity)
    {
        this->entity = entity;
    }
}

Collision.h

#ifndef COLLISION_H

#define COLLISION_H

#include "Component.h"

namespace Components
{
    class Collision : public Component
    {
        public:
            void collide(Entity* entity);

        protected:
            virtual bool collidesWith(Entity* entity) = 0;
    };
}

#endif

Collision.cpp

#include "Collision.h"

namespace Components
{
    void Collision::collide(Entity* entity)
    {
        if (this->collidesWith(entity))
        {
            ...
        }
    }
}

Renderer.h

#ifndef RENDERER_H

#define RENDERER_H

#include "Component.h"

namespace Components
{
    class Renderer : public Component
    {
        public:
            Renderer(Entity* entity);

            virtual void update(float elapsedTime) override;
    };
}


#endif

Renderer.cpp

#include "Renderer.h"

namespace Components
{
    Renderer::Renderer(Entity* entity) : Component(entity){ }

    void Renderer::update(float elapsedTime){}
}

And Physics is pretty much empty and I don't feel like adding it right now.

Thanks a lot


I'm having way to much problems with includes. My code does a lot of double referencing for performance reasons, and each pair of classes accesses the methods of each other. C++ hates this, and defining which class should forward declare the other is a pain in the ass.

Object Models as Graphs for a Domain

This is a modeling question that may be open ended, if this is the wrong place I apologize.

If you have a 'complex' domain, and you need to loosely model relationships so objects can be rebuilt if their hierarchy changes or differs between different contexts...how would you model this in a strongly typed language such as c#?

For example, if I need to swap the following: Location has a PolicyIdentifier to Policy as a Location Identifier

But...but both scenarios are valid depending on the context. Inheritance models are ok but what would be another approach that is not as explicit/concrete? If the entire domain was modeled as a graph with entities as nodes, it seems like this would allow for multiple hierarchical configurations.

Design Pattern Usage: Firefox versus Chromium

I'm looking for similar patterns between Chromium and Mozilla Firefox but am having a difficult time finding comparisons. Yes I'm new to Design Patterns, please forgive me for my ignorance. Can anyone point me into the right direction? I am currently looking through both projects with difficulty.

Using wrapper around a generic object, instead of specific objects

I have a design question im not too sure on. Say i have this "policy" sort of like a someone have car insurance or something.

There are tons of different kinds of policies that pop up all the time, so like earthquake, or trucking, or like drone, etc. I want this to be generic so they all sort of fit into this object. I was thinking of storing most of the details in a string hashmap.

public class Policy
{
    static final long serialVersionUID = 20130901L;

    private String policynumber;
    private int policyId;
    private String pendingDocType;
    private int transactionTypeId;
    private List<Integer> lobs;
    private List<Integer> markets;
    private Insured insured;
    private Agent agent;
    private Map<String, Location> locations;
    private Map<String, String> details;
}

Then for each different type, i create a wrapper class that extends policy with methods for accessing fields according the the type that it is. So if its a drone, i would have methods like

getAnnualFlightDistance()
{
    return details.get("flightdistance");
}
getAnnualPremium()
{ 
    // Some method to calculate the current money spent on policy
}

But just have helper methods around the main Policy class.

I would make them member variables for each field attached to it, but they're always changing variables a new things being added, i thought having just like a bin for the terms would allow for a constant evolving object.

Looping over heterogeneous collection

The example is as follows: I have a Box that needs to be filled with some Things. I'm interested only in weight of each thing. Also, beside weight, I need to correctly identify the thing that I'm measuring. Each thing type has different Id type. In this case I have toys and fruits, which have ToyId and FruitId respectively. In the end, I need to be able to print thing identifier and thing weight.

Question: Is it somehow possible to access specific methods on ThingIds without using instanceof operator (as in example)?

class Color{}
interface ThingId {}

class FruitId implements ThingId {
    String name;    //"apple", "orange", ...
    FruitId(String name){  this.name = name; }
    String getName(){ return this.name; }
}

class ToyId implements ThingId {
    String shape;   //"square", "circle", ...
    Color color;    //"red", "blue"...
    ToyId(String shape, Color color){ this.shape = shape; this.color = color; }
    String getShape(){ return this.shape; }
    Color getColor(){ return this.color; }
}

class Thing{
    ThingId thingId;
    Integer weight;
    public Thing(ThingId thingId, Integer weight){
        this.thingId = thingId;
        this.weight = weight;
    }
    ThingId getThingId(){ return this.thingId; }
    Integer getWeight(){ return this.weight; }
}

class Box {
    Set<Thing> things = new HashSet<>();

    void addThing(Thing thing){
        this.things.add(thing);
    }

    Collection<Thing> getThings(){
        return this.things;
    }
}

class Program {
    public static void main(String[] args) {
        FruitId appleId = new FruitId("apple");
        Thing apple = new Thing(appleId, 1);
        ToyId cubeId = new ToyId("square", new Color());
        Thing cube = new Thing(cubeId, 22);

        Box box = new Box();
        box.addThing(apple);
        box.addThing(cube);

        for(Thing t : box.getThings()){
            System.out.print("Thing Id is: ");
            if(t.getThingId() instanceof FruitId) { //any other possibility than using instance of?
                process((FruitId)t.getThingId());
            }
            if(t.getThingId() instanceof ToyId){    //any other possibility than using instance of?
                process((ToyId)t.getThingId());
            }
            System.out.println("Weight is : " + t.getWeight());
        }
    }

    static void process(FruitId fruitId){
        System.out.println(fruitId.getName());
    }

    static void process(ToyId toyId){
        System.out.println(toyId.getShape() + toyId.getColor());
    }
}

Is this a design pattern? How to avoid a switch statement here

A picture is worth a thousand words hopefully

The bottom rectangle holds a bunch of child classes and a single base class. The top rectangle holds bits of logic

Each child class needs to run 1 or more bits of the top logic, there's no base class type commonality here

There are other 'top squares' of logic.

At present this is implemented using a switch statement (I know). The only alternative I can think of is a class with one method per piece of logic in and then each class can call the appropriate methods

The real life example is is for a bunch of reports and each report needs different gui elements on the page, but as I say there's no common behaviour that could be extracted into common base classes

enter image description here

how to approach refactoring interleaving logic?

I want to refactor this code to be clean and solid. Currently I'm a bit stuck how to do this.

Imagine a price calculation: (I simplified the code, I put the elseif just make it clearer)

class Prices {

    function generatePrices($dataSource1) {

        $dataSource2 = $dataSource1->getDataSource2();
        $cases = $dataSource2->getCases();

        foreach($cases as $case) {

            if($case->isCaseA()) {
                $fee1 = $dataSource2->getFee1();

                if($dataSource1->isCaseA_1()) {
                    $fee2 = $dataSource1->getFee('caseA_1');

                    if($dataSource1->isCase1()) {
                        return $fee1 + $fee2;
                    } elseif($dataSource1->isCase2) {
                        return $fee1 + $fee2 + $dataSource2->getFee3() + $dataSource2->getFee4();
                    }

                } elseif($dataSource1->isCaseA_2()) {
                    return $fee1 + $dataSource2->getFee('caseA_2') + $dataSource2->getFee4() + $dataSource2->getFee5();
                }

            } elseif($case->isCaseB()) {

                if($dataSource1->isCaseB_1()) {
                    $fee = $dataSource2->getFee('caseB_1');

                    if($dataSource1->isCase1) {
                        return $fee;

                    } elseif($dataSource1->isCase2) {
                        $return $fee + $dataSource1->getFee6();
                    }

                } elseif($dataSource1->isCaseB_2()) {
                    return $dataSource2->getFee('caseB_2') + $dataSource1->getFee6();
                }

            }
        }
    }
}

So I thought about making a Fee factory which gets all data sources. Depending on the case it will instantiate a concrete FeeCase class that then will return the appropriate fee. But I don't like how I have to pass all data sources. Yet if I would pass all data needed for all cases I'd have to pass like 10 or more variables.

Any input on this is highly welcome. I'd prefer a path to get to my own solution. But of course if you have a solution at hand I'm grateful about that too.

mardi 20 mars 2018

Python: designing a Container class

I'm designing a Python library and need to define two classes: Container and Item.

Container contains multiple instances of Item.

Each Item instance inside a Container must be identified by name.

Item instances need not to be of the same type: Item is just a base class.

The same is true for Container: being a library, it is expected that other developers subclass both Container and Item so that SomeCustomContainer contains multiple instances of ManyCustomItem's.

As such, the main responsibility of Container and Item is to implement the basic logic to describe the "contains" relationship between some Container and its Item's.

Container has some properties that apply to all of its Item's: to avoid repeating stuff, an Item may define only Item-specific data and receive full information once it's added to a Container.

Moreover, an Item can exist of its own: it needs not to be associated with a Container. As such, an Item may define informations that would otherwise be provided by a Container.

The first draft is something like this:

class Container(object):

    def __init__(self, base, delegate):
        self._base = base
        self._delegate = delegate
        self.items = self._add_items()

    def _add_items(self):
        return []

    @property
    def items(self):
        return self._items.values()

    @items.setter
    def items(self, items):
        _items = {}
        for item in items:
            item.delegate = self.delegate
            item.info = self.base + item.info
            _items[item.name] = item
        self._items = _items

    def get_item(self, name):
        return self._items[name]

class Item(object):

    def __init__(self, info, delegate=None, name=None):
        self.info = info
        self.delegate = delegate
        self.name = name

Use Case 1:

class MyContainer(Container):

    def _add_items(self):
        return [
            SomeItem('info', name='some item'),
            SomeOtherItem('other info', name='another item')
        ]

c = MyContainer('some ', some_delegate)
assert c.get_item('some item').info == 'some info'
assert c.get_item('another item').delegate is c.delegate

Use Case 2:

c = Container('some ', some_delegate)
c.items = [
    SomeItem('info', name='some item'),
    SomeOtherItem('other info', name='another item')
]
assert c.get_item('some item').info == 'some info'
assert c.get_item('another item').delegate is c.delegate

Should "_add_items()" be public instead?

The second draft is something like this:

class Container(object):

    def __init__(self, base, delegate):
        self._base = base
        self._delegate = delegate
        self._add_items()

    def _add_items(self):
        pass

class Item(object):

    def __init__(self, info, delegate=None):
        self.info = info
        self.delegate = delegate

Use Case 1:

class MyContainer(Container):

    def _add_items(self):
        self.some_item = SomeItem(self.base + 'info', delegate=self.delegate)
        self.another_item = SomeOtherItem(self.base + 'other info', delegate=self.delegate)
        self.a_third_item = SomeOtherItem("I don't have common info", delegate=self.delegate)

This second implementation does not allow simply instantiating the base Container and adding items directly to the instance, but I don't expect that use case to be much useful. On the other hand, this second version greatly simplifies Container, but puts the responsibility of injecting common data into the items to the user of the library.

Third draft: declarative style using descriptors:

class Container(object):

    def __init__(self, base, delegate):
        self._base = base
        self._delegate = delegate

class Item(object):

    def __init__(self, info, delegate=None):
        self.info = info
        self.delegate = delegate

    def __get__(self, instance, owner):
        # I can think of two possible implementations
        if i_need_the_same_item_instance_for_a_given_container_instance:
            if self not in instance._items:
                copy = type(self)(instance.base + self.info, instance.delegate)
                instance._items[self] = copy
            return instance._items[self]
        else:
            copy = type(self)(instance.base + self.info, instance.delegate)
            return copy

Use Case 1:

class MyDeclarativeContainer(object):

    some_item = SomeItem('info')
    another_item = SomeOtherItem('other info')

c = MyDeclarativeContainer('some ', some_delegate)
assert c.some_item.info == 'some info'
assert c.another_item.delegate is c.delegate
if i_need_the_same_item_instance_for_a_given_container_instance:
    assert c.some_item is c.some_item
else:
    assert c.some_item is not c.some_item

This is my favourite implementation, because it minimizes boilerplate code and appears to be simple and readable, allowing library users to focus on adding items rather than complying to Container requirements for adding them. On the other hand, I'm pretty new to Python's descriptors and would like to know if this is a good use case for them.

  • Any drawbacks I am overlooking?
  • I am quite doubtful about the line "instance._items[self] = copy": is it sane? Is there a better alternative? What about Container having a protected "_items" attribute for the sole purpose of providing a cache to support Item's __get__ implementation?