dimanche 30 juin 2019

Implement the singleton pattern with a twist

This is a job interview question.

Implement the singleton pattern with a twist. First, instead of storing one instance, store two instances. And in every even call of getInstance(), return the first instance and in every odd call of getInstance(), return the second instance.

My implementation is as follows:

public final class Singleton implements Cloneable, Serializable {
    private static final long serialVersionUID = 42L;
    private static Singleton evenInstance;
    private static Singleton oddInstance;
    private static AtomicInteger counter = new AtomicInteger(1);

    private Singleton() {
        // Safeguard against reflection
        if (evenInstance != null || oddInstance != null) {
            throw new RuntimeException("Use getInstance() instead");
        }
    }

    public static Singleton getInstance() {
        boolean even = counter.getAndIncrement() % 2 == 0;
        // Make thread safe
        if (even && evenInstance == null) {
            synchronized (Singleton.class) {
                if (evenInstance == null) {
                    evenInstance = new Singleton();
                }
            }
        } else if (!even && oddInstance == null) {
            synchronized (Singleton.class) {
                if (oddInstance == null) {
                    oddInstance = new Singleton();
                }
            }
        }

        return even ? evenInstance : oddInstance;
    }

    // Make singleton from deserializaion
    protected Singleton readResolve() {
        return getInstance();
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Use getInstance() instead");
    }
}

Do you see a problem? The first call may enter getInstance and the thread get preempted. The second call may then enter getInstance but will get the oddInstance instead of the evenInstance.

Obviously, this can be prevented by making getInstance synchronized, but it's unnecessary. The synchronization is only required twice in the lifecycle of the singleton, not for every single getInstance call.

Ideas?

Which Design Pattern should i use for notifying changes ? Java/Kotlin Android

Here's the situation, I am building an SDK for customers to be notified of three different touch states:

  1. Object Touched

  2. Object Touched Outside

  3. Object Touched Exit

I tried using the Observer Design Pattern, where the Observable sends updates to all the Observers which are the customers. however there are a few problems.

https://stonesoupprogramming.com/2017/10/28/observer-pattern-in-kotlin/

Following this design guideline is see that in order for customers to subscribe they will need to code the following:

val bob = Bob()
bob.addObserver(Customer1())



 class Customer1: Observer{

    val name = "Customer1"

    override fun update(o: Observable?, arg: Any?) {
      // Do your logic here
    }
}

This means customer when they integrate the SDK need to both declare a Class file called Customer1 with extended Observer.

Is there a way to simplify the process of having customers register as an Observer for our SDK's Observable? I'm not sure what sort of abstraction to implement.

What's the best design pattern (MVC/MVP/MVVM) for an Android application for testability?

I've reading about design patterns lately and when planning my next application - I'd like to choose a good design pattern that would enable me to test my app's component easily and thoroughly.

Most design patters separate the data, business logic , and UI layers, that's clear but I'm getting a bit swamped with the nuances and details of each pattern and I'm a difficult time to choose the right one.

any suggestions?

what are a thin and a thick wrapper in wrapper pattern?

I was reading a document about sql Date and it said that sql Date is a thin wrapper around a millisecond value. I could not find a definition for a thin wrapper. Here is the link to the site. https://docs.oracle.com/javase/9/docs/api/java/sql/Date.html

Sequentially execute webhooks received in node application

I have a node application using koa. It receiving webhooks from external application on specific resources.

To illustrate let say the webhook send me with POST request an object of this type :

{
  'resource_id':'<SomeID>',
  'resource_origin':'<SomeResourceOrigin>',
  'value' : '<SomeValue>'
}

I would like to execute sequentially any resources coming from the same origin to avoid desynchronization of resources related to my execution.

I was thinking to use database as lock and use cron to sequentially executing my process for each resources of same origin.

But I'm not sure it's the most efficient method.

So my question is here :

Do you know some method/package/service allowing me to use global queues that I could implement for each origin insuring resources from same origin will be executed synchronously without making all webhooks processed sequentially ? If it do not use database it's better.

samedi 29 juin 2019

Grant special priviliges to user in RBAC

I am using role based access control for authorization in an enterprise software. I created three classes: User, Role and Privilege. User has a many to many relationship with Role and Role has a many to many relationship with Privilege. One of the customer's requirements is to add special privileges to a specific user. For example User u has a Role called r and according to that, u can only call foo service. But I want to add privilege p so he can call bar service too, even though that his role does not allow him to call bar. Only solution that comes to my mind is that User has a many to many relationship with Privilege as well. But I don't think that is a good idea.

manage create method of django when there are lots of fields

I am working on project where I have taken django in backend. I have a model call profile which is related to the user. A profile model has more than 10 fields and when trying to update the user profile, my code for updating all those fields would be something like this

class UpdateProfile(graphene.Mutation):
    class Arguments:
        input = types.ProfileInput(required=True)

    success = graphene.Boolean()
    errors = graphene.List(graphene.String)
    profile = graphene.Field(schema.ProfileNode)

    @staticmethod
    def mutate(self, info, **args):
        is_authenticated = info.context.user.is_authenticated
        data = args.get('input')
        if not is_authenticated:
            errors = ['unauthenticated']
            return UpdateProfile(success=False, errors=errors)
        else:
            profile = Profile.objects.get(user=info.context.user)
            profile = models.Profile.objects.get(profile=profile)
            profile.career = data.get('career', None)
            profile.payment_type = data.get('payment_type', None)
            profile.expected_salary = data.get('expected_salary', None)
            profile.full_name = data.get('full_name', None)
            profile.age = data.get('age', None)
            profile.city = data.get('city', None)
            profile.address = data.get('address', None)
            profile.name_of_company = data.get('name_of_company', None)
            profile.job_title = data.get('job_title', None)
            profile.zip_code = data.get('zip_code', None)
            profile.slogan = data.get('slogan', None)
            profile.bio = data.get('bio', None)
            profile.website = data.get('website', None)
            profile.github = data.get('github', None)
            profile.linkedin = data.get('linkedin', None)
            profile.twitter = data.get('twitter', None)
            profile.facebook = data.get('facebook', None)
            profile.image=info.context.FILES.get(data.get('image', None))
            profile.save()
            return UpdateProfile(profile=profile, success=True, errors=None)

so my question is, suppose, if there are even more than 20, 30 fields, how would you design your code on updating those fields? (considering only views part)

Simple Http Server Controller/Endpoint Pattern

I've built a simple HTTP server in c# using http listeners

It has about 10+ endpoints. Currently using if's and switches, it's getting really messy

Is there a design pattern that could solve this?

Splash screen using MVP design pattern in Android

I am doing some research about MVP design pattern in Android and got a question about splash screen. The app that i am developing with MVP design pattern does not have particular behaviors on the activity of splash screen.

In this situation, should I consider using MVP design pattern in building the activity of splash screen or just making in a simple way without MVP pattern on the activity of splash screen?

Could you give me some suggestion?

Thanks in advance.

Trying to understand SRP when we seggregate responsibilities into different classes

I'm trying to understand SRP principle and most of the sof threads didn't answer this particular query I'm having,

Use-case

I'm trying to send an email to the user's email address to verify himself whenever he tries to register/create an user-account in a website.

Without SRP

class UserRegistrationRequest {
    String name;
    String emailId;
}
class UserService {
    Email email;

    boolean registerUser(UserRegistrationRequest req) {
        //store req data in database
        sendVerificationEmail(req);
        return true;
    }

    //Assume UserService class also has other CRUD operation methods()    

    void sendVerificationEmail(UserRegistrationRequest req) {
        email.setToAddress(req.getEmailId());
        email.setContent("Hey User, this is your OTP + Random.newRandom(100000));
        email.send();
    }
}

The above class 'UserService' violates SRP rule as we are clubbing 'UserService' CRUD operations and triggering verification email code into 1 single class.

Hence I do,

With SRP

class UserService {
    EmailService emailService;

    boolean registerUser(UserRegistrationRequest req) {
        //store req data in database
        sendVerificationEmail(req);
        return true;
    }

    //Assume UserService class also has other CRUD operation methods()    

    void sendVerificationEmail(UserRegistrationRequest req) {
        emailService.sendVerificationEmail(req);
    }
}

class EmailService {
    void sendVerificationEmail(UserRegistrationRequest req) {
        email.setToAddress(req.getEmailId());
        email.setContent("Hey User, this is your OTP + Random.newRandom(100000));
        email.send();
    }

But even 'with SRP', UserService as a class again holds a behaviour of sendVerificationEmail(), though this time it didn't hold the entire logic of sending the email.

Isn't it again we are clubbing crud operation's and sendVerificationEmail() into 1 single class even after applying SRP?

vendredi 28 juin 2019

Does it make sense to create a `Copyable` type interface instead of using `Cloneable`?

I have a bit of code that requires a copy of an object be sent in. This requirement is because a service (runtime library) that is called modifies the object sent. This implementation is pending change, but does not have a reasonable expectation to be changed in the near future. My workaround is to provide a class that does as follows:

public class DangerousCallWrapper<T> implements DangerousCaller<T> {
  public T doThing(T dataObject) {

      T cloneOfDataObject = #Clone of dataObject

      // This service modifies the cloneOfDataObject... dangerous! 
      Optional<T> result = service.doThing(cloneOfDataObject);

      return result.orElseThrow(() -> new RuntimeException("No data object returned);
  }
}

public interface DangerousCaller<T> {

  /**
  * Performs the functionality of the DangerousService
  */
  public T doThing(T);
}

So the first line of that method is where I am stuck. It is a generic type, so I can't explicitly call some cloning utility like Jackson, or similar.

So I thought I would just add T extends Cloneable to the method... but I opened the can of worms that Cloneable is beyond taboo (https://www.artima.com/intv/bloch13.html). I have also read that copy constructors are probably the best way to handle this... However, I am unsure of how to denote that using the generics.

So my thought was to provide an interface Copyable that does what you would expect Cloneable to do: expose a method, copy() that will create a new instance of the class.

Does this constitute a viable approach?

Selection of design pattern(Gof) in below scenario

I need help with a Exam problem:

Let's suppose you are building an E-commerce web application which contains thousands of products in database. A web page displays 100 products in current view of products listing. Upon scrolling down event it loads next 100 products from database and displays. products listing web page shows product name, price and thumbnail image. Web page response gets slow on scrolling or refreshing due to fetching data from web server. Which design pattern strategy(GOF) you will chose to make your webpage loading fast every time when user refresh or scroll webpage?

Design patterns(Gof) based on open closed principle

My question is about Design patterns(Gof) which are based on open closed principle?

Design People Management System

I have been asked this question in an interview

A company developing its own people management system and want to migrate data to its own database. To achieve this there are 3 API(getPersonalInfo, getPayrollInfo, getDomainAssociationInfo) that can provide data, each API cost $1 per successfull response. The number of employees are 1 million(just the interviewer intention was to tell there is huge amount of data). As per my understanding what comes first in my mind -

Use executor framework to process the thread parallely and make the use of Spring batch, as huge amount of data is required to read and write.

Lets say for every id, three API need to give response, that need to be stored, so as to maintain an object lets say ProcessedData

ProcessedData {id, PersonalAPIResponse{responseCode, Data}, PayrollAPIResponse{responseCode, Data}, DomainAssociationAPIResponse{responseCode, Data}}, 

If for particular id, the response code in all three API would be 200 successfull response, this id would be added to the List, lets say, 'prepareWriteList'

otherwise if any API fails then it will be added in a queue, lets say, 'retryExecuteQueue'.

There is another exceutor framework that will pick the task from 'retryExecuteQueue' and then check the response code in API response object, if its not 200 means it assumes not successfull and retry to hit the APIs again to get the data.

If its passes then it will be added to 'prepareWriteList' otherwise again add to 'retryExecuteQueue'.

When the prepareWriteList size reached to max, the itemReader send the list to ItemWriter to write the data into the local DB.

I want to know, what could be the better approach. Also, didnot get any clue that why interviewer mentioned the cost for API, as per his clarification one id data can be fetched at once only, although it only been charged for successfull reponse and not for failure.

Any better approach, please suggest, Thanks in advance !!!!

Fill images with texture/pattern

i try to "translate" this into fabricjs code, but i do something wrong. Is there a way to use globalCompositeOperation in fabricjs?

https://stackoverflow.com/questions/28545747/fill-image-with-texture-pattern

What i am doing wrong?

  var canvas = this.__canvas = new fabric.Canvas('c');
  fabric.Object.prototype.transparentCorners = false;

  var padding = 0;

  fabric.Image.fromURL('https://i.imgur.com/8WqH9v4.png', function(img) {

    img.scaleToWidth(100);
    var patternSourceCanvas = new fabric.StaticCanvas();
    patternSourceCanvas.add(img);
    patternSourceCanvas.renderAll();
    var pattern = new fabric.Pattern({
      source: function() {
        patternSourceCanvas.setDimensions({
          width: img.getScaledWidth() + padding,
          height: img.getScaledHeight() + padding
        });
        patternSourceCanvas.renderAll();
        return patternSourceCanvas.getElement();
      },
      repeat: 'no-repeat'
    });


    fabric.Image.fromURL('https://i.imgur.com/8WqH9v4.png', function(img) {
       fill: pattern
    });

  });
})();```

How to design this component in Android

How to design a component in Android such that when click on the "Select a session" button, a form filled in will appear below, and if you click again, such form will disappear. Below is the link of how such component look like.

All of your linksenter image description here, tutorials or advices are welcome!

How this particular Builder pattern works

I am learning about design patterns and reached the Builder pattern. This is the UML that I have as an example: enter image description here

I understood how the car is made and the logic behind the builder but can't understand where the car manual is made in this example. The description says that it is made along with the car building. Is the UML not complete or I misunderstood something. Where is the CarManualBuilder initialization? How can I create a manual for a particular car in this particular pattern?

jeudi 27 juin 2019

what design pattern is spring batch and which category it belongs in Gang of four

what design pattern is spring batch and which category it belongs in Gang of four ?

I tried relating it with structural - though am not sure if it is correct.

If it is structural - what is the exact sub type of the under structural ?

Can some one help and explain ..

Is exporting a function just for testing considered a bad practice?

I have this question especially after reading the official redux documentation on testing React components:

https://github.com/reduxjs/redux/blob/master/docs/recipes/WritingTests.md

In order to be able to test the App component itself without having to deal with the decorator, we recommend you to also export the undecorated component

Even the famous https://www.reactboilerplate.com/ exports named unconnected components just to be able to test them without mocking a store.

But isn't it considered bad to export something just so it makes things easier to test?

There might be cases when a developer makes the wrong import and introduces a bug just because there are two things exported from a file.

So, the question essentially is:

Can we make changes to the actual code to make testing easier?

Although this question is specific to React, would be great to know if any other languages or frameworks have similar problems and how they are dealt with.

Variation of Java observer pattern or Publisher-Subscriber Pattern

What's the actual observer pattern from below 2 variations.

  1. In the first one, the Observer takes the responsibility of subscription.
  2. But in the second scenario, Publisher takes the responsibility to add a particular observer to the subscriber list.

Because, there are some implementations in the web, that take these both as observer pattern in java.

1.
    // Observer is taking the responsibility of subscribing 
    // Observer.java
    @Override
    public void subscribe(MessagePublisher publisher) {
        publisher.getObservers().add(this);
    }

2.

    // Publisher is taking the observer to subscribe
    // Publisher.java
     @Override
     public void addObserver(Observer observer) {
       observers.add(observer);
     }

multiple class inheritance vs layered model

Let's say I have class modules A, B and C. Each module has different job. Module A uses B and B uses C (A does not use C and vice versa), but all modules works with same resources (constructor arguments). Also A, B and C use same naming for some basic internal properties. With all these conditions, first that come into my mind is multiple inheritance.

class C {
  constructor(sources) {
    this.sources = sources;
  }
}

class B extends C {
  constructor(sources) {
    super(sources);
  }
}

class A extends B {
  constructor(sources) {
    super(sources);
  }
}

My consideration

Pros:

  • all accessible in one instance (less spaghetti code)
  • less duck typing

Cons:

  • all internal methods exposed to parent
  • possible naming collisions

There is also "default" option to create "property layers":

class C {
  constructor(sources) {
    this.sources = sources;
  }
}

class B {
  constructor(sources) {
    this.sources = sources;
    this.c = new C(sources);
  }
}

class A {
  constructor(sources) {
    this.sources = sources;
    this.b = new B(sources)
  }
}

My consideration: Opossite to above pros/cons

Maybe I miss something. I would like to avoid some coding pitfalls/bad practices so is there "better/proved solution" in terms of flexibility, maintainablity, duck typing etc?

Thanks

liskov substitution principle again - each method overriding violates the principle

I know there is many similar subjects but I need to ask because the rule is "If class S is a subtype of class T, then instances of T may be replaced by instances of S without altering any of the desirable behaviors of T itself." - so each method overriding violates the rule. Am I wrong? Because each method overriding alters base class. If not - please give the example.

Confusion regarding Entities in Clean Architecture

I am trying to come to a conclusion on whether an Entity-object (as defined in Uncle Bob's Clean Architecture) should be allowed to hold references to abstractions of various sorts. For instance IDataGateway, ILogger or IEventHandler.

My understanding up to this point is that the Entities should be pure application agnostic business logic. In my view this would not allow for the entities to hold such references. But I am now unsure if it should be a rule set in stone.

In his (Robert C. Martin) book p. 190 he states that:

"The Entity object either contains the Critical Business Data or has very easy access to that data".

Does this mean that under some circumstances, the entity can hold reference to a data source (for lazy loading perhaps)?

On the next page, however, he states that:

"This class (...) is unsullied with concerns about databases, user interfaces, or third-party frameworks. (...) The Entity is pure business and nothing else".

What is your interpretation of the term "Entities" in Clean Architecture with respect to abstract references?

Constants in Properties File

My team is new to Spring Boot and most members were previously working on a J2EE legacy application. I have previous experience with Spring Boot and microservices. My question is about a pattern they are using that I've never seen before and want to understand why this may or may not be a good idea.

They have been creating several properties files and adding key value pairs to these property files which get injected into object fields using @Value or ResourceBundle.

For example something I would normally think of as an Enum like color will be added to a property file, the same with constants.

#color.properties
color.r = red
color.b = blue
color.g = green

It seems like a lot of unnecessary code is getting written, like injecting all the values into a class then creating an array with the values in them. We are also battling to get this working.

I thought the point of the properties file was for externalized config. Why is my team doing this when Java provides data types and structures for these things?

mercredi 26 juin 2019

What's the best practice on async message handling

I'm implementing a websocket messaging client with netty and java8. Each message has a transactionId, correlate to its response.

I need to implement a send API. So I have a few options.

  1. send(message, Callback);
  2. CompletableFuture send(message);

Either way, I'm thinking to have a transaction map(hashmap), which contains transactionId to Callback or CompletableFuture mapping. My question is which one is a better practice? Or something else? Is it OK to put CompletableFuture into Map?

Any good design to solve a similar problem?

NodeJS (Javascript) Design Patterns to avoid async mess

I'm a bit new working on big projects with JS and I feel it's really hard to keep my code clean with almost everything being async.
I'm creating a lot of Promises and declared almost every function as async and using await on almost every line, and I feel this is not the correct way to manage it.
Example:

var mysql = require('mysql');
module.exports = class MyClass {

async constructor() {
    try{
        await this._initDbConnection();    
    }
    catch(e){
        console.log(e);
    }
}

_initDbConnection(){
    return new Promise(function(resolve, reject){
        this.db = mysql.createConnection({
            host: "localhost",
            user: "root",
            password: "",
            database: 'mydb'
        });
        this.db.connect(function(err) {
            if (err) {
                reject(err);
            }
            else {
                console.log("Connected to MySQL!");
                resolve();
            }
        });    
    });

}   
};

The same for every query, or anything executing async.
It's a really ugly solution.
I mean, if I need something from the DB, I want to connect to the DB in the first line, then execute the query in the second line and then process the results on the third line. With JS to do this I need to create a lot of callbacks or use await on every line???

Is broker a design pattern and mentioned in Design Patterns by Gamma et al?

Software Architecture, by Bass says

The broker pattern defines a runtime component, called a broker, that mediates the communication between a number of cllents and servers.

The original version of the broker pattern, as documented by Gamma, Helm, Johnson, and Vlissides [Gamma 94], is given in Figure 13.6.

I don't find the book by Gamma having a pattern called broker. Is broker mentioned in Design Patterns by Gamma et al?

I see broker is listed as an architectural pattern in https://en.wikipedia.org/wiki/Template:Design_Patterns_patterns. Is broker a design pattern or an architectural pattern?

Thanks.

Use a implementation of provider inside other implementation of same provider in Angular

I want to inject a provider implementation inside another other implementation of the same provider in Angular, but I could not achieve this. The idea is that I can specialize the second implementation with the data from first implementation As I read in angular documentation, is not possible use a second implementation of the same provider, but I want to know If someone has achive this in some way

Thanks

export abstract class Provider {
    abstract someMethod();
}

export class implProviderOne implements Provider{
    someMethod(){
    }
}

export class implProviderTwo implements Provider{
    constructor(private provider: Provider) {} // I DI injects implProviderOne in this implementation
    someMethod(){
    }
}

//This is what I try

//Main Module
//main.module.ts
@NgModule({
    ...
    imports: [InnerModule],
    providers:[
        { provide: Provider, useClass:implProviderOne}
    ], 
    ...
})
export class MainModule {}

//Inner Module
//inner.module.ts
@NgModule({
    ...
    {provide: Provider, useClass:implProviderTwo } // What I can do to achieve this?
    ...
})
export class InnerModule {}

How can i learn design patterns best ways using Java?

I want to learn design patterns using Java. I never used design pattern in any project so im new. I found a question like mine but this is old so i want to be sure. Do anybody know any tutorial, book, blog, video series about design-pattern??

Thank you.

How can I get by GROK differents kind of messages in this litte log file?

I am working with Logstash and I need to format my log file splitting each field.

The log has next format:

info: ::ffff:127.0.0.1 - ::ffff:127.0.0.1 [26/Jun/2019:11:52:36 +0000] "OPTIONS /api/categories/5ced18e2a0c9a01e879ce704 HTTP/1.1" 200 19 - 0.652

info: ::ffff:127.0.0.1 - - [26/Jun/2019:11:52:36 +0000] "GET /api/categories/5ced18e2a0c9a01e879ce704 HTTP/1.1" 304 - - 12.156

info: ::ffff:127.0.0.1 ::ffff:127.0.0.1 - [26/Jun/2019:11:52:36 +0000] "OPTIONS /api/twitter/5ced18e2a0c9a01e879ce704/1561463556535-1561549956535?from=0&size=10&orderType=desc&order=date&aggregations=true&timeSeriesInterval=1h HTTP/1.1" 200 8 - 0.874

error: ::ffff:127.0.0.1 ::ffff:127.0.0.1 ::ffff:127.0.0.1 [26/Jun/2019:11:52:36 +0000] "GET /api/twitter/5ced18e2a0c9a01e879ce704/1561463556535-1561549956535?from=0&size=10&orderType=desc&order=date&aggregations=true&timeSeriesInterval=1h HTTP/1.1" 400 43 - 9.044

This is the filter that I have been aplied for it in Logstash:

filter {
    grok {
      match => { "message" => "%{WORD:type}: %{IP:ipclient} - %{IP:ipuser} [%{HTTPDATE:datetime}] \"%{WORD:method} %{URIPATHPARAM:request} %{WORD:httpversion}\" %{WORD:status} %{NUMBER:bytes} - %{NUMBER:responsetime}" }
      add_field => [ "received_at", "%{@timestamp}" ]
      add_field => [ "received_from", "%{host}" ]
      add_field => [ "funcionaaaaaa", "ohoohoooh_yeeeeeeeeeeeeeeeeeeees" ]
    }
    date {
      match => [ "timestamp" , "dd/MM/yyyy - HH:mm:ss" ]
    }
  }

But this filter does not recognoise my log structure.

Any idea which pattern should solve the problem?.

Thank you.

Alternative to Observer Pattern where both Subject and Observer represent the same entity?

I basically have a node class in my project, to which other nodes can subscribe. As such, if I were to implement the observer pattern here, that would entail that this node class would end up being the subject as well as the observer. I looked at similar design patterns but I was unable to find something that suits my needs. Does the observer pattern work here, even though the node class will have to implement both subject and observer interfaces or is there a more adequate alternative that can be used? Thanks.

What are the differences between concurrency computational models and concurrency patterns?

Concurrent computational models includes actor model, CSP, Petri nets, etc.

Concurrency patterns includes active objects, barrier, reactor, monitor, scheduler, etc

What are the differences (and also maybe relations) between concurrency computational models and concurrency patterns?

It is interesting to notice that wikipedia's Design Patterns patterns template lists "Actor model" under concurrency patterns. That makes me even more unsure about the question I asked above.

Thanks.

How to be more specific on generic constraints? [duplicate]

This question already has an answer here:

I am having the following type where T should only be of int, double, string and datetime. However using a constraint on class would be too broad.

public class Field<T> where T : class 
{
    public int Tag { get; set; }

    public T Value { get; set; }
}

Possible solutions that come to my mind:

  1. Add a constructor that does a check (if ((typeof(T) != typeof(string)) ...)
  2. Change the class to be abstract and move Value to the concrete implementing class. This however would result in having several additional types, like StringField : Field, DateTimeField : Field, etc.

Also I would like to be more specific about the Tag property and replace it with an enum, which ensures that only values of predefined range can be used. This approach however would result in a (tiny) overhead, as I need to instance representation of Field as a string.

What would be the best model to choose? Anything I am missing? Thanks in advance

Versioning approach - Numbers vs Adjectives

Mostly this question has no certain answer, but I wonder the opinion of the community. We're going to implement a new version of data models (we're going to support existing one for a while). And currently, we have a few options to implement naming:

1) Use some implementation sign (like User -> gmUser). I don't like it first because it doesn't give us a solution for future changes. Plus I don't want to link interface name to an implementation

2) Use numbers for versioning (like User -> v2User / User2 , User3 and so on) - this is more widely spread approach. But such naming looks strange for me. Plus there is a sub-proposal to rename User3 -> User as soon as no one uses original User

3) Use prefixes for versions (like User -> AwesomeUser, Application -> AwesomeApplication). Under the hood, it supposed to follow an alphabetic order, but in general, such naming just says that User and AwesomeUser are different entities.

I'm personally for the 3rd option. But my counterparts say that no one uses that option. And there is a reason for it. I know that those who use such naming mostly do it for marketing. But for me, it makes the code more readable.

I wonder about community opinions and some profs for best practices.

Thanks in advance

How to create a permission model with geo/location?

I am working on a system which will be used internationally. I have a fairly standard permission based access that I will put in place.

  • Permissions give access to different features
  • Roles are sets of permissions assigned to users

My problem is that there is an extra dimension that I do not know how to work with.

Basically, the system will be used in different countries. In each country there can be multiple offices. If somebody has access to the country, he should have access to all offices but if he has access to an office, he should not have access to the country.

Getting more complex, there could be multiple levels of offices. (for example : an office contains multiple sub-offices).

Finally, somebody could have some access to the whole country but more accesses to one specific office.

I have worked in the past with systems like this which were incredibly messy to handle and do not want to make the same mistake.

Is there some good practices/readings out there you recommend ? How would you implement such a system ?

mardi 25 juin 2019

How to refactor service methods that just forward request to DAO?

I have a spring mvc project ,there is quite a lot of code in service layer that just forward request to DAO layer, just as in this example.

https://www.journaldev.com/3531/spring-mvc-hibernate-mysql-integration-crud-example-tutorial

    @Override
    @Transactional
    public void updatePerson(Person p) {
        this.personDAO.updatePerson(p);
    }

    @Override
    @Transactional
    public List<Person> listPersons() {
        return this.personDAO.listPersons();
    }

And according to A Philosophy of Software Design, it is not good.

So what is a better way to refactor service layer and DAO layer?

Avoiding breaking the SOLID principles while tryning to make a composite class methods visibile to another package class

I'm preparing a university project for my java exam, the project consists of creating a network of Routers and to send packets to each other until the packet arrive to his destination following the shortest path.

The project requires to adehere to SOLID principles, and I am actually in a stall situation, probably because it's my first time with java.

I've created a NODE class representing the generic network node which has the only responsability to hold a name associated with a IP and nothing else, then I create a ROUTING class, it's responsability is to hold all known network route in a HashMap( the integer represent the traffic load and it's random) including showing and adding entries to the map with methods.

The NODE class incorporates the ROUTING class as a protected internal class object.

Now these classes are stored in the ROUTER package, for creating a network I've created another package called NETWORKSTARTER and a class in it called STARTER, this class purpose is to create a network and connect(add nodes to the router table) other entities of the network to each other.

As I was coding the connection method I've stumbled upon the fact that I cannot call the internal methods of NODE.ROUTING even if it's a protected class within the NODE class.

Trying to solve this setback I've tought of creating three methods into the NODE class that "wraps" the methods of ROUTING class, basically calling them with other name, this way the STARTER methods can call the methods of ROUTING trough NODE methods for adding nodes to the HashMap.

The question is this: Is this design breaking the SOLID principles?In particullary does the NODE class design break the single responsability principle?

public class NODE{
private String nodeName;
private int nodeIP;
protected ROUTING nodeRoutingModule;

public NODE(String x,int y){
this.nodeName=x;
this.nodeIP=y;
this.nodeRoutingModule = new ROUTING();
}

// setter and getters for name and IP

public void addRoute(NODE node){
this.nodeRoutingModule.addToMap(node);
}

public void showTable(){
this.nodeRoutingMdoule.showMap();
}
}

public class ROUTING{
private HashMap<NODE,Integer> routeTable;

public ROUTING(){
this.routeTable = new HashMap<>();
}

public void addToMap(Node node){
int load = ThreadLocalRandom.current().nextInt(0,11);
routeTable.put(node,load);
}

public void showMap(){
routeTAble.forEach.((t,u) -> {
system.out.println(t.getIp+" "+t.getName);
});
}

}

Should I put command bus between controller and domain service?

I am working on a backend and try to implement CQRS patterns. I'm pretty clear about events, but sometimes struggle with commands.

I've seen that commands are requested by users, or example ChangePasswordCommand. However in implementation level user is just calling an endpoint, handled by some controller.

I can inject an UserService to my controller, which will handle domain logic and this is how basic tutorials do (I use Nest.js). However I feel that maybe this is where I should use command - so should I execute command ChangePasswordCommand in my controller and then domain module will handle it?

Important thing is that I need return value from the command, which is not a problem from implementation perspective, but it doesn't look good in terms of CQRS - I should ADD and GET at the same time.

Or maybe the last option is to execute the command in controller and then emit an event (PasswordChangedCommand) in command handler. Next, wait till event comes back and return the value in controller.

This last option seems quite good to me, but I have problems with clear implementation inside request lifecycle.

I base on https://docs.nestjs.com/recipes/cqrs

How to filter rows where a column A cell value is not part of a pattern of values from other rows?

I need to filter a column that contains a pattern of the numbers 1-5 in individual cells in the column. If the 1-5 pattern is broken, I need to hide the offending cells. Is there a built in feature or do I need to make a VBA macro?

Example

Which design pattern to use for a sequence of task in Java?

I want to build a sequence of task for a Java application in Dropwizard. The task should be stored inside a database

Consider a the following sequence of tasks:

Task 1
  Inputfile  : inputA
  Outputfile : outputA
Task 2 
  Inputfile  : outputA
  Outputfile : outputB

So simply the task 2 depends on output from task 1. The set of task is defined in a database. So that the java application can preform them only with the input files.

Since data base also stores each task I was thinking about using a job scheduler that handles checks periodically the existence of task and then runs them in succession. But then how can I wait for previous tasks? Is there a more elegant solution? Or a design pattern that can handles this issue?

A good design to conditionaly include/exclude property

For a web application, I have a service that get some information. For example a SaleOrder and SaleOrderDto which contains a few dozen of properties

  • OrderID
  • Date
  • Total amount
  • Total item count

... etc etc...

Asusme that some of the properties take time to call external services to include, I would like to have a mechanic that let user select/reject some properties for their call

For Example:

/service/order/1/info?include=OrderID,TotalAmount

I do not really like to do something like

if(OrderID)
{
   OrderDTO.OrderID = Order.OrderID
}
if(TotalAmount)
{
   OrderDTO.TotalAmount = Order.TotalAmount
}

Or using Reflection to loop through all properties

Can you help me with some suggestion to make cleaner code?

Is Creating a class for every UI component a good thing to do?

My company has yet to decide on a framework and style, for example using Bootstrap or Material UI and i am looking for a flexible design pattern to solve this issue if a change is needed in the future

I decided instead of using a label or an input or any other component, to use and create my own Label and Input and inside that i pass all the props to the react label and input and if a day comes where i need to change the style for my Labels, i figured that i simply have to change the base class meaning my own Label component

Is my approach a good idea?, are there any downside to such an approach?, are there any better alternatives?

Which is worse - duplicated code or double try/except?

I have a situation where I want to do multiple things while handling an exception. Since I want to make this about the general case, I'll translate my specific case into some more general language.

When I have an exception in this piece of code, I want to:

  1. Always perform a rollback-style operation
  2. If it is an application specific exception, I want to perform some logging and swallow the exception.

So I can think of two ways to solve it, both ugly:

# Method nested-try/except block
try:
    try:
        do_things()
    except:
        rollback()
        raise
except SpecificException as err:
    do_advanced_logging(err)
    return

# Method Duplicate Code
try:
    do_things()
except SpecificException as err:
    rollback()
    do_advanced_logging(err)
    return
except:
    rollback()
    raise

Both will have the same behaviour.

I'm tending towards the nested try/except solution myself. While it might be slightly slower, I don't think the speed difference is relevant here - at the very least not for my specific case. Duplication of code is something I want to avoid also because my rollback() statement is slightly more involved that just a database rollback, even if it has the exact same purpose (it involves a web-API).

Is there a third option I haven't spotted that is better? Or is the duplicate code method better? Please note that the rollback() functionality is already factored out as much as possible, but still contains a function call and three arguments which includes a single hardcoded string. Since this string is unique, there's no reason to make it a named constant.

How to update jpa element from list when it is unmanaged?

Environment:

  • JBoss 5
  • Java EE 5
  • Java 7

I have an entity course that have a list of students with a bidirectional relation.

VIEW

I have a view for course that shows a list of students but I also have a view for student edition. Every time it shows the view the elements are unmanaged.

When I modify a student using jpa

<T> T merge(T entity)

I have a new entity and then I would have to update the array list of course or replace the element with the new one.

Is there a way to do this more easily?

lundi 24 juin 2019

Single Responsibility Principle for Dao Classes

This is a sample code which haven't followed the single responsibility principle,

public class EmailSender
{
  public void SendEmail(string customerID, 
                       string emailNotificationType)
  {
    //STEP1: load customer details
    //STEP2: get email content
    //STEP3: send email (using SmtpClient class)
  }

  public string GetEmailContent(Customer customer, 
                 string emailNotificationType)
   {
    // Build the email notification content
   }
}

I agree, It will create the issue in case If I need to do following,

-> Changes in the way, you are loading customer details.

-> Changes to the email content because of requirement enhancements / changes.

-> If there any change in the way you are sending the email instead of using SmtpClient class or something like that.

so we need to apply Single Responsibility Principle to separate the classes. I totally agree on this principle. Say I need to create three classes like

EmailSender - which only focus on sending email CustomerRepository - which only focus on fetching customer data EmailContentBuilder - which parse the email content

But say If I have a Dao like CustomerDao, As of now I have all the curd operations related to CustomerDao in the same class like below

CustomerDao class
- add()
- update() - get()
- getAll()
- update()

Do we need to apply SingleResponsibilityPrinciple here? If so How to apply for CustomerDao class?

Thanks,
Harry

How to combine Visitor design pattern with Strategy?

I need a sample code that visitor design pattern works with Strategy design pattern. In my code I have a switch command that I replaced with Strategy design pattern but as each strategy has different return type I don't know how to manage it. Some people suggested to combine strategy pattern with visitor pattern but I don't know how.

Dropdown menu click-outside

I have a button (hamburger menu) and a dropdown menu just beneath him. When I click on my hamburger button, I want my dropdown menu who appears. And when I click outside my dropdown menu I want them to disappear... logic ever since.

But my button who triggers the appearing is also outside the dropdown menu ... so if I put an event on the dropdown clickoutside, my button will never be triggered (click event + clickoutside dropdown => nothing happens)

So how can I do that?

How to notify a parent thread of job completion in Python

I would like to use the following code to find a specific number of permutations in a list.

def permutations(ls, prefix, result):
    if ls:
        for i in range(len(ls)):
            permutations([*ls[0:i], *ls[i + 1:]], [*prefix, ls[i]], result)
    else:
        result.append(prefix)

    return result

My issue is that I cannot simply include another parameter to count the number of permutations found. I can't do that because each recursive call to permutations() "splits" into a new "version" (it's like a fork in the road with the old counter and each branch counts its own number of permutations found, not communicating with the others). In other words, this won't work:

def permutations(ls, prefix, result, count, limit):
    if count > limit:
        return 

    if ls:
        for i in range(len(ls)):
            permutations([*ls[0:i], *ls[i + 1:]], [*prefix, ls[i]], result)
    else:
        count += 1
        result.append(prefix)

    return result

So what I would like to do instead of including a count parameter in the function signature, is to notify some other part of my program every time a new permutation is found, and keep track of the count that way. This may be a good use of threading, but I would like to do it without parallelization if possible (or at least the simplest parallelized solution possible).

I realize that I would have to spawn a new thread at each call to permutations([*ls[0:i], *ls[i + 1:]], [*prefix, ls[i]], result) in the for loop.

I'm hoping that someone would be so kind as to point me in the right direction or let me know if there is a better way to do this in Python.

Is nodejs representing Reactor or Proactor design pattern?

Many articles online demonstrates NodeJS as an example of reactor pattern. Isn't it rather proactor?

As far as I understand, the difference between the two is:

  1. reactor handles events in a single thread (synchronously)
  2. proactor handles events is multiple threads (asynchronously) with completion callbacks.

For example in this article:

Reactor Pattern is an idea of non-blocking I/O operations in Node.js. This pattern provides a handler(in case of Node.js, a callback function) that is associated with each I/O operation. When an I/O request is generated, it is submitted to a demultiplexer.

Isn't it actually definition of proactor?

Search for pattern contained inside the same pattern

I am scanning a text document which it may contains the following patter : $someTitle(value , value )%% . So far so good I am able to extract that pattern from the text . Is there anyway using pattern and matcher to extract two patterns in the following case :

$someTitle($someTitle2(value, value)%% , value)%% .

The desired result would be : String 1 = $someTitle($someTitle2(value, value)%% , value)%% String 2 =$someTitle2(value, value)%%

Design PAtterns for alleviating maybe changing the visibility of an object

Problem

I keep running across this paradigm where I have to write functions of the form maybeUpdateEnabled, where I change one variable that determines visibility and have to check against a load of others.

Example

Imagine I have the following data (represented as strings here for convenience):

["apple", "pear", "tomato", "celery", "red pepper"]

and I provide the user with a GUI with two toggle-buttons, one for filtering out all things that are red, and one for filtering out all things that are vegetables. The user first filters out all of the reds, and then all of the vegetables, and only pears remain. When the user then toggles the red switch, the red peppers, which were initially filtered out, should still be invisible, as they are still being hidden via the vegetable filter.

Question

Are there any Design Patterns which can help alleviate this? I was considering using bitmasks, or a stack of some kind, but I don't think I'll be able to logically avoid the maybeUpdate paradigm, which is a horrendous code smell to me.

How to Design a program for a building with lift functionality using c# which should follow SOLID principle

Consider a building has lift(s) and each lift has some functionalities(Up,Down,Open,Close etc).

I need to design a program which will allow me to add a new lift to the building also new functionalities to the lift. I have to use solid principle for this.

I need some pseudo code or idea to design this.

Note: While adding new feature to the lift it should not force other lifts to add the same feature.

class Lift : ILiftFunctions
    {
        public void Close()
        {
            //some logic;
        }

        public void EmergencyExit()
        {
            //some logic;
        }.... so on

    }
---------
public interface ILiftFunctions : ILiftUPDown, ILiftOpenCLose
    {
        void EmergencyExit();
    }
    public interface ILiftUPDown
    {
        void MoveUp();
        void MoveDown();
    }
    public interface ILiftOpenCLose
    {
        void Open();
        void Close();
    }
--------
 interface IAddLift
    {
        void AddNewLift(Lift objLift);
    }
------------
 class Building:IAddLift
    {
        public int Height { get; set; }
        public int Area { get; set; }
        public string Name { get; set; }
        public List<Lift> lstLifts { get; set; }

        public void AddNewLift(Lift objLift)
        {
            lstLifts.Add(objLift);
        }
    }

Design pattern to compose different multiple Angular components together

I have a Angular6 app. The app has multiple pages. Each page is made up of multiple components. The components are basically of two types a filter component and a grid component. The filter components provide inputs on how to filter data in grid. These filter inputs can be async.

<page>
 <filter-1></filter-1>
 <filter-2></filter-2>
 <filter-3></filter-3>
 <grid filters="filtersForData"></grid>
</page>
page.component.ts
 filtersForData = [];
 callbackForFilter1(filter) { filters.push(filter)} // async
 callbackForFilter2(filter) { filters.push(filter)} // synchronous
 callbackForFilter3(filter) { filters.push(filter)} // async


Right now everything works as expected. However I would like to design the above in such a way that unless I have all the filters I should not load the grid. Reason being some calls being async in nature the grid throws ExpressionChangedAfterEvaluation Error. One thought process is too have all the filters async or not return an observable and once all observable are done then only load the grid. However this introduces another challenge of writing and maintaining observable. Also multiple filters coming in at different time will cause mutliple onChanges trigger which I want to avoid. How can the above be achieved?

Where is the best place to check a long logic in Laravel?

I have a long logic for checking if ordered products are compatible. and this logic is needed in two controllers. So I want to put this piece of code somewhere.

Is this a good idea to put this logic in OrderRepository while I want to follow Repository Pattern? if it's not, where is the best place?

here is the method for creating order in OrderRepository:

/**
 * Create the order
 *
 * @param array $params
 * @return Order
 * @throws OrderInvalidArgumentException
 */
public function createOrder(array $params) : Order
{
    try {
        $order = $this->create($params);

        $orderRepo = new OrderRepository($order);
        $orderRepo->buildOrderDetails(Cart::content());

        // Check the compatibility here

        event(new OrderCreateEvent($order));

        return $order;
    } catch (QueryException $e) {
        throw new OrderInvalidArgumentException($e->getMessage(), 500, $e);
    }
}

Using Task<> in a library

I'm designing the software architecture for a product who can instantiate a series of "agents" doing some useful things. Let's say each agent implement an interface having a function:

Task AsyncRun(CancellationToken token)

Because since these agents are doing a lot of I/O it could make some sense having as an async function. More over, the AsyncRun is supposed never complete, if no exception or explict cancellation occour.

Now the question is: main program has to run this on multiple agents, I would like to know the correct way of running that multiple task, signal each single completion ( that are due to cancellation/errors ) and I would like to know if this is the correct pattern, especially because the implementer can mismatch the RunAsync and do a blocking call, in which case the entire application will hang.

dimanche 23 juin 2019

Store and forward design pattern with multiple instances of a microservice

I am designing a service that will be receiving requests which must only be executed exactly once (can be received more than once due to unique id presence).

The flow is:

outside world -> HTTP -> [A set of instance of Myservice] -> HTTP -> Vendor services

So, I am receiving a bunch of requests over HTTP and I am looking to do some transformation, checking, store the request in a database and send to to the vendor services via HTTP too.

My question is:

What is an effective way to achieve a store and forward pattern in my service i.e. receive the request and store it immediately, therefore acking it to the "outside world" immediately and then in my own time forward it to the destination service, retrying as many times as needed?


Problems:

  • What if one of the instances of myservice goes down while it is sending the request to the vendor service?
  • How will I monitor if there are a bunch of request that have not been forwarded?
  • How to avoid another orchestration service?
  • How to avoid another single instance service that is effectively watching the database and forwarding any requests that have not been forwarded.
  • How to minimise external dependencies - e.g. I am aware some sort of queue here might help this issue, but I am trying to see if I can avoid that.

Question about hard coding vs. iterating thru a json file

I have a project that provides boilerplates for projects, like yeoman generator. The boilerplate code gets cloned from github. Right now, I have the types of projects hard coded:

inquirer.prompt({
            type: "list",
            name: 'type',
            message: "What type of project would you like to create: ",
            choices: [
                "Web Project",
                "React Project"
            ],
            filter: function(val){
                return val.toLocaleLowerCase()
            }
        })

I want to update this code to pull the names, descriptions, and github repo urls from a json file. What would be the best way to handle this? Whats the best method of downloading an up to date copy of the json file ? Does a github gist allow me to do this? Any advice is appreciated. Thanks

can I get cart content directly in order repository?

I'm dealing with design patterns and I found this piece of code from here:

    /**
     * Create the order
     *
     * @param array $params
     * @return Order
     * @throws OrderInvalidArgumentException
     */
    public function createOrder(array $params) : Order
    {
        try {
            $order = $this->create($params);
            $orderRepo = new OrderRepository($order);
            $orderRepo->buildOrderDetails(Cart::content());
            event(new OrderCreateEvent($order));
            return $order;
        } catch (QueryException $e) {
            throw new OrderInvalidArgumentException($e->getMessage(), 500, $e);
        }
    }

Does it break the rules? and what should I do if I want to pass products with an array from the design pattern point of view?

CRUD operation on stream as databases

I have been reading multiple blogs where people are saying that we can use Streams as a database. (Like this ).

And it will have obvious benefit of scalability, atomicity etc. Because Let's take the example of kafka. If we use kafka as a datastore and there are 10 topics in kafka. We can theoretically write with 10 transaction per seconds without worrying about collision (if all the writes are going to different topic). But on a very low level in any other database only one thread will be committing something to file system. (is my understanding correct?)

If I plan to implement the above. I will have a kafka as an intermediate datastore. And there are listeners running, who keep pushing to data to some persistent store(for reads/aggregate view).

In many CRUD services, we have to read the entity before we try to update it. But with the above approach, there might be some events which have not been processed yet. (I understand that the above problem might be there in other databases as well in terms of Eventual Consistency, but we can work around by using strong Quorums, but in the above case we have brought in one more point of failure and the probability of being out of sync increases). Also we will have to build pipelines to notify user if their operation was successful or not. Which can not be done synchronously now.

Hence, what are all the feasible use cases for the above Approach? Kafka is good as an event source database, but for writing CRUD service I see too many issues. Am I missing anything?

how to print this pattern in java i have no idea how

i cant print this pattern : 1 2 3 4 * 1 0 0 * 5 1 0 * 0 5 1 * 0 0 5 * 2 3 4 5

i tried to print but only on row :

public class Pattern {

public static void main(String[] args) { 
        for(int j=1;j<=5;j++)
        {
            if(j>4) {
                System.out.print("*");
            }
            else {
                System.out.print(j);

            }
        }
}

}

Design Pattern to use when you want apply some common functionality to some specific methods?

I am trying to figure out a design pattern to use(if any exists) to a situation where I would be re-doing some functionality across a bunch of classes. Below is a (simplified) overview of the problem I am facing:

I have some Java code to CREATE, UPDATE, DELETE Student objects, Professor object, & Staff objects. And every time such object is either created, deleted, or updated, I want to extract some information about the affected object(such as name, age, id) and notify an external service. So something like:

class StudentDAO {
   public Student createStudent(Student studentToCreate) {
       jdbcTemplate.update(INSERT_SQL, .....);
       //===> extract some info of the student
       //let external service know a student was created....
   }
   public Student deleteStudent(Student studentToDelete) {
       jdbcTemplate.update(DELETE_SQL, .....);
       //===> extract some info of the student
       //let external service know a student was deleted....
   }
   //same thing for update
}

class ProfessortDAO {
   public Professor createProfessor(Professor professorToCreate) {
       jdbcTemplate.update(INSERT_SQL, .....);
       //===> extract some info of the professor
       //let external service know a Professor was created....
   }
   public Student deleteProfessor(Professor professorToDelete) {
       jdbcTemplate.update(DELETE_SQL, .....);
       //===> extract some info of the professor
       //let external service know a professor was deleted....
   }
   //same thing for update
}

//repeat for Staff

The example is bit contrived but assume that Student, Professor, Staff share no inheritance hierarchy. Is there a way to achieve this functionality without copying and pasting the logic for extracting the info and sending it in all the DAO classes for CREATE, DELETE, UPDATE methods ?

Design question - Multiple classes with same functionality

I have some things to clarify for myself, so please bear with me.

Let's say I want to have an object that will explode after a certain period of time. If the object explodes while the person is still holding it, you get killed.

Let's consider the following implementation:

public interface IKillable
{

    void Kill();

}



   public interface IExplodable : IKillable
{
     float TimeLeft { get; set; }
     void Timer(float timeToExplode);

}


public abstract class Bomb: IExplodable
{
public float TimeLeft { get; set; }

public void Kill()
{
    //Destroy the object
}

public void Timer(float timeLeft)
{
    if (TimeLeft <= 0) {

        Kill();
    }
}

}

What if I also want to add let's say a "Backpack" instead of "Bomb" that will have the exact same functionality or any other item that can explode (and kill)?

  1. Is inheriting a "Backpack from Bomb" reasonable in this case?
  2. Probably copying the code won't follow SOLID principles?

Inherit and add methods or compose new object and take data as argument?

I am self-learning object-oriented Python and have a classical "inherit or compose" question in my project. I read through many of the general guidelines/answers to this question, but it's hard for me to apply this to my specific case - so I decided to ask.

My program is a web-scraper, that's scrapes a website with different types of pages (and different data-objects from theses pages). I use BeautifulSoup (bs4) to parse the data from the raw request response. As there are many different data objects wanted, I need about 10 different parser-functions.

My question - what would be the best architecture for the parser-object?

A: Create a class 'mySoup' inheriting from BeautifulSoup and add the parser-functions as methods.

B: Create a class 'Parser' on its own, that takes the BeautifulSoup-object as argument.

I already changed back an forth between the two solutions and my personal feeling is, that I would rather pick the Inheritance-Solution, simply because it makes calling the parser clean and simple. Also 'Parser' doesn't look like a necessary object to me, more a collection of functions.

class mySoup(BeautifulSoup):
    def parseData1(self):
        ...
        return data_as_dict

    def parseData2(self):
        ...
        return data_as_dict

soup = mySoup(page_source)
data = soup.parseData1()

vs.

class Parser():
    def __init__(self,soup):
        self.soup=soup

    def parseData1(self):
        ...
        return data_as_dict

    def parseData2(self):
        ...
        return data_as_dict

soup = BeautifulSoup(page_source)
data = Parser(soup).parseData1()

Split string by dot lua

I'm trying to split a string by a single dot, yet retain double(and more) dots.

My approach is like this,which works only with double dots:

local s = "some string.. with several dots, added....more dots.another line inserted."; for line in s:gsub('%.%.','#&'):gmatch('[^%.]+') do print(line:gsub('#&','..')); end

Another approach was like this

print(s:match('([^%.]+[%.]*[^%.]+)'))

which halts after the next sequence of dots, so it does not suit properly.

How could I accomplish this in a pattern matching?

Flutter design pattern

So I have created a flutter page which has a bunch of inputs in it. I thought this is a mess, lets refactor it and created a new stateful widget for each input.

This is great except the data needs to be in the parent widget and I am having a hard time understanding how to pass the data back from the new child widgets to the parent.

I've found some hacky way where you pass in a function and whenever there is a change you pass the data to the parent through that function.. Works but now theres multiple variables, one in the child and one in the parent.

I've read about the bloc pattern and I'm not sure whether this is what i need. I just want a singleton style object that the main widget and its children can both read and the children update when there is new input.

I would be really grateful if someone could explain whether the bloc pattern would help me with this or if there is another design pattern that will help me with this.

Thank you

Factory pattern: Restrict object construction to factory

I have a class T and a factory TFactory that creates objects of type T. I want to make sure that only the factory is allowed to create new T objects.

A halfhearted solution would be to require the factory as a parameter in T's constructor, for the only purpose that only somebody who at least brings a factory object can create T's:

class T
{
   public T( TFactory Tf )
   {
      if( !(Tf is TFactory) )
          throw new InvalidOperationException( "No factory provided" );
   }
}

But wherever a TFactory is at hand, one could construct T's. Another approach would be to check via stack tracing, if the constructor call really came from within a TFactory, but this seems overkill to me.

A third apporach would be to put both T and TFactory in an assembly of their own, ad make T's constructor internal. But a new project and assembly just for this purpose?

Any better idea anybody? (Although my code is C#, this is probably a more general question)

samedi 22 juin 2019

Best practice for simple Laravel model operations

Let's say I'm writing a Laravel controller that has a function: make a simple search on a model and do anything with the result. Something like this (without any validation, for simplicity):

public function search($name)
{
  $person = Persons:where('name', $name)->first();
  doSomethingWith($person);
  // ...
}

Should I move this tiny Eloquent code to the Person model in a dedicated function? Usually I write all the "complex" operations to the Models to have short and readable controllers, but when I have to do little operations like this I always find that moving a single line of code (even if it is directly related to the database) into a separated model function will bring too much overhead to my code.

Design pattern for a global cache of objects with lookup

I am currently working on a project that requires a common interface for defining, sharing, and lookup of a hierarchy of objects. Essentially, there would be a shared project that defines a common structure for all objects, and consuming projects can use it to define objects and share them among other projects. I am wondering if there is an existing design pattern that fits this and implements this well.

I have already attempted this, but I'm not exactly satisfied with the results. My current approach defines a Tag class, which uusesa unique string as the name, and a Guid as a runtime-generated Id for faster lookup (hashing and equating Guid values is much faster than doing so with strings). Then, objects that I want to be shared among projects globally define that Tag as a member.

In this current design, Tag objects serve solely as an identifier, and contain no data. I would like to re-design this so that tags DO contain data and serve as a base class. However, this is becoming increasingly complex, and so I am hoping to find established design patterns or existing projects that implement a similar system to aid in development.

[DebuggerDisplay( "Name = {Name}, Children = {ChildCount}" )]
public class Tag : IDisposable, IEquatable<Tag>
{

  #region Data Members

  public readonly Guid Id;

  public readonly string Name;

  public readonly string FullName;

  public readonly Tag Parent;

  protected readonly HashSet<Tag> children_;

  protected readonly int hash_;

  protected bool isDisposed_;

  #endregion

  #region Properties

  public IReadOnlyCollection<Tag> Children
  {
    [MethodImpl( MethodImplOptions.AggressiveInlining )]
    get => children_;
  }

  public int ChildCount
  {
    [MethodImpl( MethodImplOptions.AggressiveInlining )]
    get => children_.Count;
  }

  public bool HasChildren
  {
    [MethodImpl( MethodImplOptions.AggressiveInlining )]
    get => children_.Count > 0;
  }

  public bool HasParent
  {
    [MethodImpl( MethodImplOptions.AggressiveInlining )]
    get => Parent != null;
  }

  #endregion

  #region Constructor

  public Tag( string name )
    : this( Guid.NewGuid(), name, null )
  {
  }

  public Tag( string name, Tag parent )
    : this( Guid.NewGuid(), name, parent )
  {
  }

  public Tag( Guid id, string name )
    : this( id, name, null )
  {
  }

  public Tag( Guid id, string name, Tag parent )
  {
    Id = id;
    FullName = Name = name;

    children_ = new HashSet<Tag>();
    hash_ = Name.GetHashCode( StringComparison.InvariantCultureIgnoreCase );

    if( parent != null )
    {
      Parent = parent;
      FullName = $"{parent.FullName}.{Name}";
      Parent.AddChild( this );
    }
  }

  ~Tag()
  {
    Dispose( false );
  }

  #endregion

  #region Public Methods

  [MethodImpl( MethodImplOptions.AggressiveInlining )]
  internal void AddChild( Tag child )
  {
    if( !children_.Add( child ) )
    {
      children_.TryGetValue( child, out var existingChild );
      throw new DuplicateTagChildException( this, existingChild, child );
    }
  }

  [MethodImpl( MethodImplOptions.AggressiveInlining )]
  internal void RemoveChild( Tag child )
  {
    children_.Remove( child );
  }

  [MethodImpl( MethodImplOptions.AggressiveInlining )]
  public bool HasChild( Tag child )
  {
    return children_.Contains( child );
  }

  #endregion

  #region Overrides

  [MethodImpl( MethodImplOptions.AggressiveInlining )]
  public bool Equals( Tag other )
  {
    return Name.Equals( other.Name, StringComparison.InvariantCultureIgnoreCase );
  }

  [MethodImpl( MethodImplOptions.AggressiveInlining )]
  public override bool Equals( object obj )
  {
    return obj is Tag other
      && Name.Equals( other.Name, StringComparison.InvariantCultureIgnoreCase );
  }

  [MethodImpl( MethodImplOptions.AggressiveInlining )]
  public override int GetHashCode()
  {
    return hash_;
  }

  #endregion

  #region IDisposable Methods

  public void Dispose()
  {
    Dispose( true );
    GC.SuppressFinalize( this );
  }

  public virtual void Dispose( bool disposing )
  {
    if( isDisposed_ )
      return;

    if( disposing )
    {
    }

    Parent?.RemoveChild( this );
    TagCache.TryRemove( this );

    isDisposed_ = true;
  }

  #endregion

}

Where's the best place to call methods that interact with my database?

I'm creating an app that interacts with a Firestore database. As of now I have a singleton class, DatabaseManager that has all the methods relating to the Firestore database (i.e. get/post methods).

I have a User model called User that has properties such as name, email, photoURL, and some app-specific properties. Any user can edit their profile to update information from a view controller called EditProfileViewController.

Now my question is: is it best to call the DatabaseManager.shared.updateInfo(forUser: user) (where user is a User instance) from EditProfileViewController, User, or some other place?

Sorry if this is an obvious question, but there's going to be a lot of points in the app where I'll need similar logic so I wanted to know what's the best design. Also I'm sure this question has more to with MVC than it does Firebase/Swift.

Why does Core Java library NOT use ENUMs for implementing the Singleton pattern

The core java classes pointed by the famous BalusC answer (https://stackoverflow.com/a/2707195):

java.lang.Runtime#getRuntime()
java.awt.Desktop#getDesktop()
java.lang.System#getSecurityManager()

All the above classes seems to Classes with private constructors instead of being the Enums. If Enum was the best practice to implement a Singleton pattern (Why is Enum best implementation for Singleton), why it was not used in the core java source?

What are the dangers of non thread safe singleton?

Recently I found this article that explains how to implement a thread safe singleton pattern in C#. However I wonder how important it is to make your singleton thread safe what and what are the dangers of having your singleton class non thread safe. Consider a very simple, non thread safe, implementation of a singleton pattern:

public class ThreadNotSafeSingleton
{
    public static ThreadNotSafeSingleton Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new ThreadNotSafeSingleton();
            }

            return _instance;
        }
    }

    private static ThreadNotSafeSingleton _instance;

    private ThreadNotSafeSingleton()
    {
    }
}

Now let's say, due to the fact that this code is non thread safe, two threads will enter this line of code _instance = new ThreadNotSafeSingleton();. In this case, the first thread will initialize _instance field and then the second one will initialize _instance field again, any way as a result you will have a single _instance existing in your application.

So what is the big deal here then? I know, if you have more complex code, and your constructor runs some other code that may not be thread safe it may be dangerous. But are there any problems with non thread safety if your singleton is that simple?

vendredi 21 juin 2019

Difficulty understanding why subclassing singleton contradicts definition of singleton?

From other answers on here, I see that essentially subclassing a singleton contradicts what it means to have a singleton. However, I don't quite understand why each subclass can really crea

class Singleton {
    private static Singleton instance = null;
    protected Singleton() {

    }
    public static Singleton getInstance(){
        if (instance == null) {
            instance = new Singleton();         
        } 
        return instance;
    }
}

class SubclassSingleton extends Singleton {
    public SubclassSingleton() {

    }
}


SubclassSingleton x =  new SubclassSingleton();
SubclassSingleton y = new SubclassSingleton();
System.out.println(x.getInstance() == y.getInstance()); // true

Yes, technically x and y are instances of Singleton, but getting there instance still results in a shared resource, and the constructor (from my understanding) after constructing x has essentially no effect—rather, the static method getInstance() will return the shared consstruction of the parent class. So, I'm having trouble understanding how this violates essentially having one shared instance of Singleton, despite being subclassed.

What is the most suitable design pattern and architecture pattern for an online e-commerce application?

I'm developing an online food ordering system using php and mysql for an assignment.What will be the most suitable design pattern and architecture pattern for this web application?Could any one please eaxplain me.

How to remove circular dependency between two classes in a same package?

We are doing some refactoring and we have hit the wall here. There are two service classes AService and BService doing different works have a circular dependency. Earlier they were in a different libraries so there was no circular dependency existed. But now after refactoring we have moved them into a single library into a single package. AService job is to persist some data into a NoSQL database for a separate use case. BService job is completely different than AService job. AService needs BService to GET some data. BService needs AService to write some data to NoSQL Database and reads back.

How to fix the circular dependency issue without making each of them depends on each other. Any design pattern for such issues?

class AService {
@Autowired
private BService bService;

}

class BService {
@Autowired
private AService aService;

}

Design: best practice to convert REST dtos to java database entities

I'm working on an Android project. I get some DTO from REST API (e.g. CompanyDTO, DepartmentDTO,ProjectDTO) , and I want to persist them in my database.

These DTO may have has-a relations: for example, in each CompanyDTO we have a list of DepartmentDTO.

So I already created all converters that convert DTO to database entities (CompanyEntity, DepartmentEntity, etc.). But I have a problem, for example:

for (CompanyDTO companyDTO : apiDTOS.getCompanyDTO()) {
   CompanyEntity companyEntity = CompanyConverter.convert(companyDTO);
   companyRepository.insert(companyEntity);
   for (DepartmentDTO departmentDTO : companyDTO.getDepartmentDTO) {
      DepartmentEntity departmentEntity = DepartmentConverter.convert(departmentDTO);
      departmentRepository.insert(departmentEntity );

    // here we have more imbrications
   }
}

I don't think it's good in the view of design, I want to know if there is a best practice to do this kind of conversions ? Thank you.

jeudi 20 juin 2019

Parent wrapping child class methhod

I have these Worker classes doing some job

class WorkerOne implements IWorker {
    @Override
    public doWork(Resource resource){
     // do some work
    }
}

I want all doWork() methods to be wrapped by the same operation.

One way to achieve it is creating an abstract class as the following example:

abstract class WorkWrapper implements IWorker {
    @Override
    public doBetterWork(){
       Resource resource = // ...
       doWork(resource)
       reource.close();
    }
}


class WorkerOne extends WorkWrapper {

    protected doWork(Resource resource){
     // do some work
    }
}

and invoke the Worker as-

WorkerOne worker = new WorkerOne();
worker.doBetterWork();

For some reasons I prefer not to use inheritance. Is there a better solution to do this wrapping?

Two different approaches to delimit fields for a WHERE clause

I posted a more detailed version of this question on code review exchange, check this link. I later got my implementation reviewed by one of my colleagues and he suggested a different approach to solve the problem. So this question is to help me find out, which of the two approaches should be picked and why?

If this is not suitable for StackOverflow and should still be in CodeReviewExchange, please let me know and I will move it there.

Also I want to say this in the beginning itself because I was criticized for this in my earlier post. The actual code is different than what I have provided here, its more complex so I had to simplify it to ask just what I want to figure out i.e. inheritance vs composition, which is better here?

Here is my set of classes:

public abstract class ConditionBuilder<TContext> : IConditionBuilder where TContext : FieldSearchContext
{
    public virtual bool QuotedValues { get; set; } = true;

    public abstract string OperatorSymbol { get; }

    public string BuildCondition(SearchCondition searchCondition)
    {
        var conditionBuilder = new StringBuilder();

        var context = searchCondition.GetContext<TContext>();

        conditionBuilder.Append(context.FieldId);
        conditionBuilder.Append(OperatorSymbol);
        conditionBuilder.Append(GetValue(context));

        return conditionBuilder.ToString();
    }

    public abstract bool CanHandle(FilterAction filterAction);

    public abstract object GetValue(TContext context);

}

public class TextLikeConditionBuilder : ConditionBuilder<TextContext>
{
    public override string OperatorSymbol => " LIKE ";

    public override bool CanHandle(FilterAction action) => action == FilterAction.TextLike;

    public override object GetValue(TextContext context)
    {
        if (context.Text == null)
        {
            return null;
        }

        return string.Concat("%", context.Text, "%");
    }
}

public class TextEqualsConditionBuilder : ConditionBuilder<TextContext>
{
    public override string OperatorSymbol => " = ";

    public override bool CanHandle(FilterAction action) => action == FilterAction.TextEqual;

    public override object GetValue(TextContext context)
    {
        if (context.Text == null)
        {
            return null;
        }

        return "'" + context.Text + "'";
    }
}

In their default implementation the classes build a WHERE clause for SQL. These classes are consumed by other developers and can be overridden to build WHERE clause that is not necessarily meant for Database for example one can override protected virtual StringBuilder GetCondition(SearchFilterCondition filterCondition, TContext context) to build a QUERY for Elasticsearch also.

Coming back to the topic, in one particular instance where these classes are used with their default behavior, I wanted to delimit the FieldId so as to ensure that it works when FieldId contains spaces and special characters. This is how I implemented the solution:

public interface IDelimitedIdentifier
{
    string Delimit(string input);
}

internal class SqlServerDelimitedIdentifier : IDelimitedIdentifier
{
    public string Delimit(string input)
    {
        return "[" + input.Replace("]", "]]") + "]";
    }
}

internal class OracleDelimitedIdentifier : IDelimitedIdentifier
{
    public string Delimit(string input)
    {
        return "\"" + input + "\"";
    }
}

public abstract class ConditionBuilder<TContext> : IConditionBuilder where TContext : FieldSearchContext
{
    public virtual bool QuotedValues { get; set; } = true;

    public abstract string OperatorSymbol { get; }

    public string BuildCondition(SearchCondition searchCondition)
    {
        var conditionBuilder = new StringBuilder();

        var context = searchCondition.GetContext<TContext>();

        conditionBuilder.Append(SanitizeFieldId(context.FieldId));
        conditionBuilder.Append(OperatorSymbol);
        conditionBuilder.Append(GetValue(context));

        return conditionBuilder.ToString();
    }

    public abstract bool CanHandle(FilterAction filterAction);

    public abstract object GetValue(TContext context);

    protected virtual string SanitizeFieldId(string fieldId)
    {
        return _delimitedIdentifier.Delimit(fieldId);
    }

}

public class SanitizedFieldConditionBuilder<TContext> : ConditionBuilder<TContext> where TContext : FieldSearchContextBase
{
    private readonly ConditionBuilder<TContext> _baseConditionBuilder;
    private readonly IDelimitedIdentifier _delimitedIdentifier;

    public SanitizedFieldConditionBuilder(ConditionBuilder<TContext> baseConditionBuilder, IDelimitedIdentifier delimitedIdentifier)
    {
        QuotedValues = false;

        _baseConditionBuilder = baseConditionBuilder;
        _delimitedIdentifier = delimitedIdentifier;
    }

    public override string OperatorSymbol => _baseConditionBuilder.OperatorSymbol;

    public override bool CanHandle(SearchFilterAction action) => _baseConditionBuilder.CanHandle(action);

    public override object GetValue(TContext context) => _baseConditionBuilder.GetValue(context);

    protected override string SanitizeFieldId(string fieldId)
    {
        return _delimitedIdentifier.Delimit(fieldId);
    }
}

public static class ConditionBuilderExtensions
{
    public static SanitizedFieldConditionBuiler<TContext> SanitizeField<TContext>(this ConditionBuilder<TContext> source, IColumnSanitizer columnSanitizer) where TContext : FieldSearchContext
    {
        return new SanitizedFieldConditionBuiler<TContext>(source, columnSanitizer);
    }
}

The classes can be instantiated as shown below:

class Program
{
  static void Main(string[] args)
  {
   var conditionBuilders = new List<IConditionBuilder>()
        {
            new TextEqualsConditionBuilder().SanitizeField(new SqlServerDelimitedIdentifier()),
            new TextLikeConditionBuilder().SanitizeField(new SqlServerDelimitedIdentifier())
        };
        }
}

My colleague suggested to use composition instead of extension. Here is how the classes would look like as per his recommendation.

 public abstract class ConditionBuilder<TContext> : IConditionBuilder where TContext : FieldSearchContext
    {
        private readonly IDelimitedIdentifier DelimitedIdentifier;

        public virtual bool QuotedValues { get; set; } = true;

        public abstract string OperatorSymbol { get; }

        protected ConditionBuilder(IDelimitedIdentifier delimitedIdentifier)
        {
            DelimitedIdentifier = delimitedIdentifier;
        }

        public string BuildCondition(SearchCondition searchCondition)
        {
            var conditionBuilder = new StringBuilder();

            var context = searchCondition.GetContext<TContext>();

            conditionBuilder.Append(DelimitedIdentifier.Delimit(context.FieldId));
            conditionBuilder.Append(OperatorSymbol);
            conditionBuilder.Append(GetValue(context));

            return conditionBuilder.ToString();
        }

        public abstract bool CanHandle(FilterAction filterAction);

        public abstract object GetValue(TContext context);

    }

    public class TextLikeConditionBuilder : ConditionBuilder<TextContext>
    {

        public TextLikeConditionBuilder(IDelimitedIdentifier delimitedIdentifier) : base(delimitedIdentifier)
        {

        }

        public override string OperatorSymbol => " LIKE ";

        public override bool CanHandle(FilterAction action) => action == FilterAction.TextLike;

        public override object GetValue(TextContext context)
        {
            if (context.Text == null)
            {
                return null;
            }

            return string.Concat("%", context.Text, "%");
        }
    }

    public class TextEqualsConditionBuilder : ConditionBuilder<TextContext>
    {

        public TextEqualsConditionBuilder(IDelimitedIdentifier delimitedIdentifier) : base(delimitedIdentifier)
        {

        }

        public override string OperatorSymbol => " = ";

        public override bool CanHandle(FilterAction action) => action == FilterAction.TextEqual;

        public override object GetValue(TextContext context)
        {
            if (context.Text == null)
            {
                return null;
            }

            return "'" + context.Text + "'";
        }
    }

Here are my arguments for why it shouldn't be done as per what my colleague recommends doing:

  1. IDelimitedIdentifier is very specific to database, why should it be moved inside the base class when the functionality can be supported using extension.
    1. Extension reduces the number of changes otherwise adding that constructor would mean changing all derived classes and let me tell you that there are 15 odd deriving classes
    2. Isn't adding a constructor against Open-Closed principle?

Pass object or objects id to new activity

If I have a list of certain items (let's say fruits) in one activity. Here the items are completely loaded from a ROOM database. Clicking on a Fruit should take you to the FruitDetailPage. Ofcourse I have to pass the Fruit to the new activity with an Intent.

But what would be better to do?

  • Pass the complete fruit object
  • Pass the fruit_id and reload the fruit object from the database in the new activity

What type of design pattern is the AngularJS $scope object?

I'm new to SO and have been learning and working with JavaScript and AngularJS for about 3 months, so super super new to the field. I'm in the process of going deeper into JS and am studying Design Patterns, so a question popped up in my head -> What type of design pattern is the $scope object?

I have done a fair bit of reading but other than the obvious -> being part of the MVC architecture of AnguarJS, I can't imagine anything more specific.

I'm looking forward to hearing some more experienced developers's answers on this.

Print pyramid and invert pyramid pattern

I am printing pattern,pattern include invert pyramid and pyramid pattern contain invert pyramid and pyramid

I can not print in shell script

Regex.Matches find least amount of characters per each match found

I want to iterate over each match but my code only finds 1 match by getting everything between the first and last character to find in the pattern.

Basically, I want to iterate over the 3 matches found in the following string:

value = "{account_id}{user_id}{someValue}";

But it only finds 1 match (the whole thing) using the following pattern: "{\\S+}"

foreach (Match match in Regex.Matches(value, "{\\S+}"))
{
    var key = match.Value.Replace("{", "").Replace("}", "").Trim();
    // do stuff with key...
}

This makes sense because "{" and "}" are both non-white space character so I tried using "{[a-zA-Z_]}" but this fails too.

foreach (Match match in Regex.Matches(value, "{[a-zA-Z_]}"))
{
    var key = match.Value.Replace("{", "").Replace("}", "").Trim();
    // do stuff with key...
}

Variable key in the loop should be "account_id", then "user_id", then "someValue", however it is always "account_iduser_idsomeValue (the whole thing).

How can I fix this?

Design Pattern for a very long base class

If I have 8 long methods that will be shared among 4 child classes (not all of them will be using all the methods) some will be use only 2 others 4, etc.

If I create a base class and each of the 4 child classes inherit from the base class then the problem is solved but I am trying to avoid using a very long base class.

I can try to divide the base class in more classes depending on how they are used and then use multiple inheritance, this is another solution.

Is there any other pattern to solve this problem?? What would be the optimal?

Shared pointer using (this) registering to an observer

I am having a problem trying to use a shared pointer from a class that wants to register to an observer (using ) here is the example.

Observer.hpp

class Observer {
virtual void update() = 0;
}

Consumer.hpp

class Consumer : public Observer {
virtual void update() override;
}

Consumer.cpp

class Consumer {
***

THIS IS NOT WORKING - How to do it using shared pointers??


register.registerObserver(std::make_shared<Observer>(this));
}

Register.cpp

class Register {
void registerObserver(const std::shared_ptr<Observer>& observer);
}

mercredi 19 juin 2019

Implementation of Interface Segregation Principle Example given in Uncle Bob's Agile Principles Book

Is my implementation of Figure 12-1 correct? Figure12-1

This is an implementation of Interface Pollution example from Uncle Bob's book Agile Principles Patterns and Practices in C#.

I have tried implementing it as following:-

using System;

namespace AgilePrinciplesCSharp.Chapter12.Listing12_2
{
    class Listing12_2
    {
        static void Main(string[] args)
        {
            var door = new TimedDoor();
            var client = new Client(door);
            client.TimeOut();
        }
    }

    public interface ITimerClient
    {
        void TimeOut();
    }

    // We force Door, and therefore (indirectly) TimedDoor, to inherit from TimerClient.
    public interface IDoor : ITimerClient
    {
        void Lock();
        void Unlock();
        bool IsDoorOpen();
    }

    // Implementation of Door Interface with Timer functionality
    public class TimedDoor : IDoor
    {
        public bool IsDoorOpen()
        {
            return true;
        }

        public void Lock()
        {
            Console.WriteLine("Door Locked");
        }

        public void TimeOut()
        {
            var timer = new Timer();
            timer.Register(5, this);
            Console.WriteLine("Timeout! Door left open for so long");
        }

        public void Unlock()
        {
            Console.WriteLine("Door Unlocked");
        }
    }

    // Timer class can use an object of TimerClient
    public class Timer
    {
        public void Register(int timeout, ITimerClient client)
        {
            /* CODE */
        }
    }

    // Client uses Door Interface without depending upon any particular implementation of Door
    public class Client
    {
        IDoor door;

        public Client(IDoor door)
        {
            this.door = door;
        }

        public void TimeOut()
        {
            door.TimeOut();
        }
    }
}

My doubt is in the way the implementation is described in the book, where Door is sometimes being called as a class or sometimes as an interface and i am getting confused whether i need to have a separate implementation of Door class apart from IDoor interface? Also the author does not use I notation while naming an interface which makes it even more confusing.

If anyone has read the book, i hope can understand my concern and help me out with this.

Design patterns iOS - Swift - Coordinator, MVP and MVVM

I need advice on which design pattern to adopt or recently in-usage for large applications(having DB storage, web-service interactions etc.), keeping in mind:

  • Harnessing the latest swift coding features
  • Code maintainability
  • Maximum test coverage
  • Minimizing lines of code and source files count

I have been shifting between Android and iOS and have not worked on iOS Apps for about a year now. If I want to start an app from scratch, I need some inputs to give an heads-up.

I have gone through various tutorials explaining each design patterns. But, each one looks good as per the objective it is trying to put forth and as far as small apps are concerned.

Need advice based on patterns used by large-scale apps.

Thanks in advance!