vendredi 30 novembre 2018

Which design pattern to use for this requirement

Requirements - * Sort/segregate students on the basis of various criterias. * Right now, we will be sorting on the basis of students age but in future different kind of sorting requirements may come. * Future requirements can be any like sort students on the basis of their father’s age, segregate students on the basis of grades they got etc. * For all the sorting/segregation types, list of students objects will be provided. * Create a reusable framework which can be used for age based sorting & future sorting requirements which may come. This needs to be implemented in java.

Design dynamic grouping of wcf service response attributes based on input request c#

Below is a sample format of response and equivalent service contract of my web service looks like.

<Players>
 <Player>
     <Name>Sachin</Name>
     <Sport>Cricket</Sport>
     <SportType>Team Game</SportType>
 </Player>
 <Player>
     <Name>Ronaldo</Name>
     <Sport>Football</Sport>
     <SportType>Team Game</SportType>
 </Player>
 <Player>
     <Name>Alfred</Name>
     <Sport>Shooting</Sport>
     <SportType>Individual</SportType>
 </Player>
</Players>

Now UI team is asking for new feature where they want grouping logic of different fields in service. For example in input request in newly exposed 'groupBy' field they can send can send field name "Sport" and then they want Player element grouped by "Sport" in response and same is possible for "SportType".

<SportTypes>
    <SportType>
        <Type>Team Game</Type>
        <Players>
            <Player>
                <Name>Sachin</Name>
                <Sport>Cricket</Sport>
            </Player>
            <Player>
                <Name>Ronaldo</Name>
                <Sport>Football</Sport>
            </Player>
        </Players>
    </SportType>
    <SportType>
        <Type>Individual</Type>
        <Players>
            <Name>Alfred</Name>
            <Sport>Shooting</Sport>
        </Players>
    </SportType>
</SportTypes>

I don't have problem grouping the fields after retrieving them from database but I don't know how can I define service contract for dynamic service response as response structure will change after grouping.For some very odd(maybe stupid) reasons UI team doesn't want to do this grouping so it has to be done in service. Maybe I am approaching the problem in wrong way.Any help is appreciated.

Design pattern use cases in java libraries and packages

inputStream in java io package is implemented using Decorator pattern.There will be lot more,please share those. This knowledge can give more hold on design patterns same time good understanding of design pattern implementation in java. Below are the list of design patterns.

1.Creational Design Pattern

Factory Pattern

Abstract Factory Pattern

Singleton Pattern

Prototype Pattern

Builder Pattern.

  1. Structural Design Pattern

Adapter Pattern

Bridge Pattern

Composite Pattern

Decorator Pattern

Facade Pattern

Flyweight Pattern

Proxy Pattern

  1. Behavioral Design Pattern

Chain Of Responsibility Pattern

Command Pattern

Interpreter Pattern

Iterator Pattern

Mediator Pattern

Memento Pattern

Observer Pattern

State Pattern

Strategy Pattern

Template Pattern

Visitor Pattern

Permission checks in service implementation

I have service implementation class which has lot of code. I need to write permission logic which has many checks Where is the best way to put this code I have create UserAction class for this which I am calling in service implementation method

Is this the right way to do it or I should create abstract class or interface like UserAction interface and create impl class for user action

This is more of design question or better way to structure your code for maintainability

Java Spring boot Api : Controller behavior depending on query parameter

Basically I am forced to use a path url as follows GET /accounts/<accountNumber::string>/reports?type=<DAILY>&date=<YYYY-MM-DD> The thing is that my behaviour is highly dependent of my report type, as you can see "Daily" in my example. So i am looking for a design pattern that would allow me to simulate a controller factory that would instantiate specific controllers for each of my reports types. For example i would have a DefaultController having a method called getReport that would be mapped to my GET request and that would delegate to other specific controllers (i.e: DailyReportController) the task of generating and returning the report.

I want my design to be as reliant as possible to on the SOLID principles and other clean code and maintainability principles. So even if i would add a report type in a month, all it would take me is adding a new TypeReportController and a value in my ReportType enum, and not having infinite methods in my controller and my services

python loop, Pyramid pattern

can anyone help me with this code. It must be done using for and if only. 0 1 0 1 2 1 0 1 2 3 2 1 0 1 2 3 4 3 2 1 0 1 2 3 4

I tired and think every stuff but I dont understand what i am missing. I am having a issue with generating 101, 21012, 3210123, 43211234

here is my code(which is wrong) for i in range (1,6): for t in range (i,5): print('\t', end="") for j in range (0,(2*i-1)): print(2*i-1-j, "\t", end="") print("")enter image description here

AngularJS: Is it a good practice to have multiple functions in controller?

I have a controller which has four functions bind to scope. These functions will be called when user clicks on buttons(using ng-click).

Example:

.controller('myController', function($scope){
    $scope.myVariable = 0;
    $scope.funcOne = function(){
        // modify $scope.myVariable
        ...
    };
    $scope.funcTwo = function(){
        ...
    }
    // more functions...
});

Inside these functions, they contain some logic like modifying scope variables based on user input, so that the scope variable's change can reflect on DOM. (For example: in above code, myVariable is modified in funcOne, this will reflect on DOM.)

Some online resources indicates that main logic should be contained in service, then inject the service into the controller.

My questions:

  • is this a good practice?
  • Should controller contain a lot of logic?
  • If the logic should be contained in service, what should be contained in controller? and how would you do the dependency injection?

Thanks!

Should service call another service or repository directly?

I am creating the WebApplication, with many layers (for now important are Model, Repository, BusinessLayer)

Having ClassService, ClassRepository and StudentService, StudentRepository, should ClassServiceMethod call methods from StudentService or StudentRepository?

Please provide as many arguments or additional links/blogs/informations as possible :)

Thanks in advance.

Here is my example code, some generics are added. The question is about GetClassAndBestStudent method:

Services - Business Layer

public class ClassService :  BaseService<Class>, IClassService
{
    IClassRepository classRepository; // Resolved by IoC, will be injected to BaseService
    IStudentRepository studentRepository;
    IStudentService studentService;

    public virtual Class GetClassWithHighestNotes() { ... } // Do some stuff and call classRepository.GetClassWithHighestNotes()
    public virtual Teacher GetTeachersByClass(int classId) { ... } // Do some stuff and call classRepository.GetTeachersByClass()

    public virtual GetClassAndBestStudent(int classId)
    {
        // Question here: Which call is valid?
        var best = studentRepository.GetStudentWithHighestNotes()
        var best = studentService.GetStudentWithHighestNotes();
    }
}

public class StudentService : BaseService<Student>, IStudentService
{
    IStudentRepository studentRepository; // Resolved by IoC, will be injected to BaseService

    public virtual IEnumerable<Student> GetStudentsByClass(int classId) { ... } // Do some stuff and call studentRepository.GetStudentsByClass()
    public virtual Student GetStudentWithHighestNotes() { ... } // Do some stuff and call studentRepository.GetStudentWithHighestNotes()
}

// Abstract, generic CRUD service 
public abstract class BaseService<T> : IBaseService<T> where T : MyBase
{
    IRepository<T> repository;

    public virtual IEnumerable<T> GetAll() { ... } // Do some stuff and call repository.GetAll()
    public virtual T GetById(int id) { ... } // Do some stuff and call repository.GetById()
    public virtual T Insert(T entity) { ... } // Do some stuff and call repository.Insert()
    public virtual T Update(T entity) { ... } // Do some stuff and call repository.Update()
    public virtual bool Delete(T entity) { ... } // Do some stuff and call repository.Delete()
    public virtual bool Delete(int id) { ... } // Do some stuff and call repository.Delete()
}

Repositories - Data Layer

public class ClassRepository : BaseRepository<Class>, IClassRepository
{
    public virtual Class GetClassWithHighestNotes() { ... }
    public virtual Teacher GetTeachersByClass(int classId) { ... }
}

public class StudentRepository: BaseRepository<Student> IStudentRepository
{
    public virtual IEnumerable<Student> GetStudentsByClass(int classId) { ... }
    public virtual Student GetStudentWithHighestNotes() { ... }
}

// Abstract, generic CRUD repository
public abstract class BaseRepository<T> : IRepository<T> where T : MyBase
{
    public virtual IEnumerable<T> GetAll() { ... }
    public virtual T GetById(int id) { ... }
    public virtual T Insert(T entity) { ... }
    public virtual T Update(T entity) { ... }
    public virtual bool Delete(T entity) { ... }
    public virtual bool Delete(int id) { ... }
}

Mapping complex data from Model to View

Let's consider a simplified MVC architecture, where Model operates on different types of Confections. There are different subtypes of Confection class, such as Candy, Cookie, Doughnut, etc. Every subtype, in turn, has different sets of properties, like size, color, shape and so on.

For instance, that's one implementation of Candy class:

class Candy extends Confections {
    public enum Size {
        LARGE,
        MEDIUM,
        SMALL,
    }

    public enum Color {
        RED,
        GREEN,
        YELLOW,
    }

    private Size size;
    private Color color;

    ...        
}

Now the Model wants to update the View with a new set of Confections to display. Let's say that the only thing View needs to get the picture of a Confection is a string representation of its type and properties, e.g. "candy_red_large". The dumbest thing to do this is to have a number of instanceof branches and switches for types inside the View:

if (confection instanceof Candy) {
    result.append("candy");
    switch ((Candy) (confection).color) {
        case RED:
            result.append("_red");
            break;
        ...
    }
    ...
} else ...

Besides this monster is large and ugly, it also doesn't benefit from encapsulation and OOP. Let's consider a better way of doing this by providing each Confection subclass with a method like toString(), which will return the desired string representation. The only problem I see in this approach is some kind of architectural "trade-off" when Model is actually aware of View implementation details having toString method, which is useless from Model's point of view.

What would be the best approach or design patterns to use in such case for mapping diverse data from Model to View representation?

binary composition of structural patterns

How can I make binary compositions of the next structural design patterns?

  • Adapter
  • Bridge
  • Composite
  • Decorator
  • Facade
  • Flyweight
  • Proxy

Ruby - Calling methods in class definition

I was recently sifting through some code and came across this:

class A

  @@container = {}
  def self.register(a, b)
    @@container[a] = b
  end

  def self.get(a)
    @@contaienr[a]
  end
end


class BRunner < A
  A.register(D, self)

  def self.run
    #...
  end
end

class CRunner < A
  A.register(E, self)

  def self.run
    #...
  end
end


class C
  [D, E].each do |item|
    A.get(item).run()
  end
end

BRunner and CRunner call register when their respective class definition blocks are executed at runtime without explicitly calling them. This doesn't seem right because to me, this is not clear code. Is this a Ruby thing or just bad programming? Whats your opinion on code like this and why?

Using factory when loading from file

I'm relativity new to C++ , though I do have some experience in java. Trying to approach to following problem ;(this is part of a bigger task from my university)

class myCustomer :public Customer {/.../}


class myEmployee :public Employee {/.../}

So Customer is an interface , and myCustomer is a derived class with the implementation ,same goes for employee .(i have to use it that way)

Followed by this (sort-of) an API for a flight company data base ;

class MyImplementation{
   //I want to link id's to an object so i can call id using a given id
   map <string,myCustomer*> customers_map;
   map <string,myEmployee*> employees_map;
...
   //must implement this function
   virtual Customer* addCustomer(string full_name, int priority){
    if(!customers_loaded){
        load_customers();
    }
    auto curr_customer = new myCustomer(id,full_name,priority);
    customers_map.insert(pair<string,myCustomer*>(id,curr_customer));
    }



    void load_customers(){
        vector<string> parameters;
        string line;
        fstream customers_file;
        customers_file.open(CUSTOMER_INFO_PATH,fstream::out);
        //check if null is returned
        if (!customers_file.is_open()) {
            throw "Error:cannot open employees file";
        }
        //iterate over lines
        while(getline(customers_file,line)){
            //just a function to split a line from file to a vector               
            parameters=splitLine(line,SPLITTER);
            try{
                customer_from_string(parameters);
            }catch(...){
                //could not load current object 
                cout << "Could not load customer "<< parameters[0] <<
                "(line number:"<< lineNumber << ")" <<endl;
                continue;
            }
        }
        customers_file.close();
    }


    void customer_from_string(vector<string> parameters){
        string id = parameters[0];
        string name = parameters[1];
        int priority = stoi(parameters [2];
        auto curr_customer = new myCustomer(id,name,priority);
        customers_map.insert(pair<string,myCustomer*>(id,curr_customer));
    }
    /** more code**/

So i have to do this to about 6 classes , each has its own constructor with different number of parameters. Trying to avoid this code duplication I understand i need to approach this using an Abstract factory design pattern. So i thought about implementing the following :

class Factory {
virtual void create(vector<string>& parameters,
                    map<string,Factory*>&id_map,/*..more parameters*/)=0;
 }

and let the load method decide which object to create (maybe send a char as identifier) , using the create method above, Let each class Implement the factory interface and than using the create function.So i think i need to change the maps to

 map <string,Factory *> objectName_map;

Now im kinda stuck since the map holdes A pointer to a factory object , and I want to use the maps id's to do the following :

virtual Customer* getCustomer(string id){   //must implement this function
    if(!customers_loaded){
        load('C');
    }
    return customers_map.find(id)->second;
}

And i cannot call any inner functions for each object ,after , lets say :

void setEmployer(Employee* employer){//...//}

Since the maps are holding a Factory* . I tried to keep the maps as they are but couldnt use them in a create function since it cannot convert a myCustomer* object to Factory* . Im kinda lost , tried to find solutions online but had no luck , though i feel im implementing this wrong. Thanks in advance for any help with this!

Example of the Object Calisthenics First Class Collection rule in C#?

I am playing with the Object Calisthenics rules and I am having some troubles to see when to use the first class collections when using C#.

I mean I hardly see when it's supposed to be used, for example it would be hard to apply that rule to an EF DbContext.

Let's say, we design a Board class.

public class Board
{
    public IList<BoardRow> Rows { get; }
    public IList<BoardColumn> Columns { get; }

    public Board()
    {
        Rows = new List<BoardRow>();
        Columns = new List<BoardColumn>();
    }
}

So according to that rule, we would have to turn the code above into:

// Is it really that better than just using List<BoardRow>?
public class BoardRowCollection : IEnumerable<BoardRow>
{
    public void Add(BoardRow row) { /*...*/ }
    public void Remove(BoardRow row) { /*...*/ }

    // IEnumerable<BoardRow> Impl goes here...
}

// Is it really that better than just using List<BoardColumn>?
public class BoardColumnCollection : IEnumerable<BoardColumn>
{
    public void Add(BoardColumn column) { /*...*/ }
    public void Remove(BoardColumn column) { /*...*/ }

    // IEnumerable<BoardRow> Impl goes here...
}

public class Board
{
    public BoardRowCollection Rows { get; }
    public BoardColumnCollection Column { get; }

    // Rest of the impl, ctor, etc.
}

I am not really sure to get the point of this rule when you already have base classes that can be leveraged to achieve your goals.

Maybe the code above is not the best but I would like to see one example which can shed the light on the purpose of that rule.

jeudi 29 novembre 2018

Should the logic inside a factory class query the database

Is it a good design practice to let the logic inside a factory class query the database in order to select/returnright service implementation?

Vue.js: Backend realization

So, i have been learning Vue.js as my first js framework for some time and after i made some simple SPAs without much interactions with server i started to wonder: what should Backend be like with Vue? For education purpose i gave it a try and came up with some pattern on my own and now i can't imagine anything else, maybe got some wrong idea.

What i came up with. I made a simple API with PHP which was receiving requests from Frontend (Vue component methods reacting on UI events) and requesting data from Model or updating data through it.

Hiding the Model in MVC behind REST API

Let's start with an example:

A user is trying to create a new task in a ToDo MVC web app. When the user submits the new task, it, in an ideal scenario, gets validated by JS in the view, serverside in the controller, and then sent to the model via a REST API call. The web app can establish direct access to the database, if it wanted to, but it uses the established REST API to perform the CRUD operation and any final validation.

What are the advantages, disadvantages, or flaws with "hiding" the Model in an MVC web app behind a REST API, even if a direct connection to the DB is possible? Is doing this common practice?

An advantage I can think of is that you don't have to redefine the CRUD operations using direct DB connections if you already have a REST API.

A disadvantage would be the extra authentication that needs to happen for API calls, even if the web app user is logged in.

I'm new to designing REST API and MVC web apps, so I want to get some answers from the more experienced developers before I finalize my design for my current project which needs both a REST API and an MVC web app.

Service B relies on data in Service A: Duplicate data or retrieve on-demand?

This is a microservice design question which is a simplification of a real-life problem I would like to solve.

Service A has entities which can be active or inactive.

[
    {
       id: "a46e6cc7-97ca-4570-b3f3-2be00ca9dab5",
       name: "foo",
       active: true
    },
    {
       id: "eb1ced31-eccc-4ad6-a695-5c6c76cab7a5",
       name: "bar",
       active: false
    },
    {
       id: "ef332044-9e66-4a0b-91ed-c16a2537e848",
       name: "baz",
       active: true
    }
]

Service B has jobs that are related to Service A's entities and should only run if the entities are active (according to business rule).

Option 1: Service B does not store whether the jobs should run.

[
    {
       id: "39cf3321-34d1-4557-b1c4-ca628c191b92",
       entityId: ""a46e6cc7-97ca-4570-b3f3-2be00ca9dab5",
       start: "Thu Nov 29 2018 08:40:27 GMT-0800 (Pacific Standard Time)",
       ended: null,
       recurrence: "hourly"
    },
    {
       id: "77296d22-564f-4289-8327-f23bceb1d400",
       entityId: "a46e6cc7-97ca-4570-b3f3-2be00ca9dab5",
       start: "Tu Nov 27 2018 15:56:01 GMT-0800 (Pacific Standard Time)",
       ended: null,
       recurrence: "hourly"
    },
    {
       id: "2916a920-13a3-46f6-9ffd-d7629163924a",
       entityId: "eb1ced31-eccc-4ad6-a695-5c6c76cab7a5",
       start: "Wed April 01 2018 00:00:00 GMT-0800 (Pacific Standard Time)",
       ended: Thu April 01 2019 00:00:00 GMT-0800 (Pacific Standard Time),
       recurrence: "daily"
    },
]

When a job is scheduled to run it checks

if Service A has j.entityId = true
   run j

using Service A's API.

Option 2: Service B stores whether the job should run

[
    {
       id: "39cf3321-34d1-4557-b1c4-ca628c191b92",
       entityId: ""a46e6cc7-97ca-4570-b3f3-2be00ca9dab5",
       active: true,
       start: "Thu Nov 29 2018 08:40:27 GMT-0800 (Pacific Standard Time)",
       ended: null,
       recurrence: "hourly"
    },
    {
       id: "77296d22-564f-4289-8327-f23bceb1d400",
       entityId: "a46e6cc7-97ca-4570-b3f3-2be00ca9dab5",
       active: true,
       start: "Tu Nov 27 2018 15:56:01 GMT-0800 (Pacific Standard Time)",
       ended: null,
       recurrence: "hourly"
    },
    {
       id: "2916a920-13a3-46f6-9ffd-d7629163924a",
       entityId: "eb1ced31-eccc-4ad6-a695-5c6c76cab7a5",
       active: false,
       start: "Wed April 01 2018 00:00:00 GMT-0800 (Pacific Standard Time)",
       ended: Thu April 01 2019 00:00:00 GMT-0800 (Pacific Standard Time),
       recurrence: "daily"
    },
]

Its storage is kept up-to-date by means of notification from Service A:

Entity e changes => publish e => Service B updates accordingly

Here are the arguments I see in favor of each option.

Option 1 arguments:

  • Less storage cost since data is not duplicated
  • When a job is scheduled to run it always has the most recent information about whether it should be active (more "consistency"?)
  • Don't have to deal with complexity of syncing data across service. In this example there is only Service B that relies on data from A, but imagine the complexity if there were services X0, ..., X1000 that all needed to know whether an entity is active.

Option 2 arguments:

  • The services are truly independent: If A is not running, B can still run
  • Less chatty services (less network transfer cost)
  • Although perhaps more complex, the complexity of duplicating/propagating data forces the services to share nothing or little

Builder pattern - Build() method behaviour

There is a Builder. Programming language is irrelevant.

Which one is correct:

    • you set up the builder
    • you are able to call Build() as many times you like to. So in result you end up with X objects of the same parameters (or even changed parameters if you add more configuration.
    • you set up the builder
    • after Build() call, the builder has to be set up again to be able build another object.

Is there any convention how should the Build() behave?

Both scenarios may be valid. In first scenario you have to copy the values, in second you are able to move the values from builder to created object.

I'd like to properly name the "builders" to be able to distinguish behaviour by just reading the name; code comments are lies, the code always tells the truth.

Injecting a dependency that is a tree of dependencies

Is it a pattern or antipattern to inject a dependency that is a tree of dependencies?

For example:

public class ClassExample
{
    private IContainer _container;

    public ClassExample(IContainer container)
    {
        _container = container;
    }
}

public interface IContainer
{
    IDependencyA DependencyA { get; set; }
    IDependencyB DependencyB { get; set; }
    IDependencyC DependencyC { get; set; }
}

public interface IDependencyA
{
}

public interface IDependencyB
{
}

public interface IDependencyC
{
}

The above example could be made even deeper (a tree) - for example IDependencyA could contain even more dependencies IDependencyAA, IDependencyAB, etc.

Someone might use above method to minimize code duplication when having multiple places where a same set of services need to be injected. Code will end up looking like: container.DependencyA.DependencyAA.Method(...) in many cases which makes it more verbose and less DRY.

Is using above method a good or bad idea (pattern/antipattern)? Or when is it a good idea, and when is it a bad one?

Profiling all class methods

I'm reading the Practical Python Design Patterns and I'm trying to learn the decorator concept. I've stuck in the last example, where I cannot get the logic of the writing a profiler that applies to all methods of a class.

Here is at the example from the book. I didn't rewrite it here because of the copywrite restriction but I hope Google Book's link is sufficient.

The problem is, when I implement the code and apply it on my DoMathStuff class, I get TypeError: 'NoneType' object is not callable. To me, the try/except/else part is unclear and I think there is a typo somewhere but I can tell where.

@profile_all_class_methods
class DoMathStuff(object):
    """docstring for DoMathStuff"""
    def __init__(self, n):
        self.n = n

    def fib(self):
        fPrev, f = 1, 1
        for num in xrange(2, self.n):
            fPrev, f = f, f + fPrev

        return f

    @profiling_decorator
    def fact(self):
        fct = 1
        for num in xrange(1, self.n):
            fct *= num

        return fct


if __name__ == '__main__':
    m = DoMathStuff(10)
    print("Fib = {}, Fact = {}".format(m.fib(), m.fact()))

What pattern to use while working with sockets

currently i'm developing an android application. I would like to use sockets so the client can receive data from the server.

I read about the client-server pattern. For the client side i'm using the MVC pattern. The controllers communicate with the server.

On the server side im currently not using any pattern. I handle the connections in one class and the business logic in other classes.

My question is, what design pattern is correct practise for the server side?

Find a pattern at certain location in a String and replace it with something else in Java

I’m facing a weird problem that I cant resolve for some reason. If I have this String: “aaaa aa” And the pattern is: “aa” So there is 3 places that match that pattern: (aa)(aa)( aa) I want to change the pattern at specific location (let’s say at the second position) with something else, let’s say this String: “bbb”.

So the final result will be: “aabbb aa”.

What is the simplest way to solve this? Without any special collection or special classes.

What java design pattern to avoid casting data entity

I'm currently implementing asynchronous-like event queue inside my application - it is designed to work like this: one component reacts to some user input and putting event to the queue, and another "listener" is checking whether there is event of specific type inside the queue and run it's own business logic

There can be various event types (like USER_MOUSE_CLICK, USER_KEYBOARD_CLICK etc) and every implementation has it's own "event-object" type

It looks like this (I'm ommiting constructors - setting all fields and getters/setters - they are just normal default ones):

public abstract MyEvent<T> {
    private EventType eventType;
    private T eventData;
}

public MouseClickEvent extends MyEvent<ClickPoint> { // ClickPoint class contains x,y of mouse click
    public MouseClick(ClickPoint point) {
        super(EventType.USER_MOUSE_CLICK, point);
    }
}

public KeyboardClickEvent extends MyEvent<String> { // character that has been clicked on keyboard
    public MouseClick(String key) {
        super(EventType.USER_KEYBOARD_CLICK, key);
    }
}

I have also a service with queue of MyEvent instances and the method to retrieve first event of provided EventType if exists - it's look like

...
private List<MyEvent> queue;
...
public MyEvent fetchMyEvent(EventType eventType) {
    for(MyEvent event : queue) {
        if(event.getEventType().equals(eventType) {
            return event;
        }
    }
    return null;
}
...

The problem is that when I'm trying to retrieve the event I need to cast it to specific implementation like

// some listener logic
MouseClickEvent event = (MouseClickEvent ) eventService.fetchMyEvent(EventType.USER_MOUSE_CLICK);
log("The X point of mouse click was: " + event.getEventData().x);

I don't like this casting - I feel like I have no control of a types when I'm fetching events and I see this situation like a 'weak point' and bug generator. Is there any design pattern to avoid this, or should I redesign whole system? Or maybe this is the only way and I should not care

Advice if DRY could be applied for the following Java Code

public static HashMap<Language, Double> getBigramResult(ArrayList<Character> textCharList) {
        HashMap<Language, Double> totalProbabilities = new HashMap<Language, Double>();
        for (int j = 0; j < textCharList.size() - 1; j++) {
            if (textCharList.get(j) != '+' && textCharList.get(j + 1) != '+') {
                FileHandler.writeSentences("BIGRAM :"+textCharList.get(j)+""+textCharList.get(j + 1));
                for (int k = 0; k < biGramList.size(); k++) {
                    BiGramV2 temp = biGramList.get(k);
                    double conditionalProbability = Math.log10(temp.getConditionalProbabilty(textCharList.get(j),
                            textCharList.get(j + 1)));
                    updateTotalProbabilities(totalProbabilities,temp.getLanguage(),conditionalProbability);
                    FileHandler.writeSentences(temp.getLanguage().toString()+ ": p("+textCharList.get(j+1)+"|"+textCharList.get(j) +") ="+conditionalProbability+"==> log prob of sentence so far: " +totalProbabilities.get(temp.getLanguage()));
                }
                FileHandler.writeSentences("");
            }
        }
        return totalProbabilities;
    }

    public static HashMap<Language, Double> getUnigramResult(ArrayList<Character> textCharList) {
        HashMap<Language, Double> totalProbabilities = new HashMap<Language, Double>();
        for (int j = 0; j < textCharList.size(); j++) {
            if (textCharList.get(j) != '+') {
                FileHandler.writeSentences("UNIGRAM :"+textCharList.get(j));
                for (int k = 0; k < uniGramList.size(); k++) {
                    Unigram temp = uniGramList.get(k);
                    double conditionalProbability = Math.log10(temp.getProbabilty(textCharList.get(j)));
                    updateTotalProbabilities(totalProbabilities,temp.getLanguage(),conditionalProbability);
                    FileHandler.writeSentences(temp.getLanguage().toString()+ ": p("+textCharList.get(j)+") ="+conditionalProbability+"==> log prob of sentence so far: " +totalProbabilities.get(temp.getLanguage()));

                }
                FileHandler.writeSentences("");
            }
        }
        return totalProbabilities;
    }

public static void updateTotalProbabilities(HashMap<Language, Double> totalProbabilities,Language l,double conditionalProbability)
{

    Double oldValue = totalProbabilities.get( l);
    totalProbabilities.put( l,oldValue != null ? oldValue + conditionalProbability : conditionalProbability);

}

In the above code ArrayList textCharList => List of lowercase characters including '+'.

BiGramList is a list of "BiGramV2" class which has 2 methods "getLanguage()" that returns either Germany, English or French (as enum) and "getConditionalProbabilty()" that takes 2 characters and return a double.

Now almost similar is UniGramList is a list of UniGram class has 2 methods "getLangauge()" which is same as Bigram and "getProbabilty()" that takes 1 character and returns a double.

Both the above methods are very similar, and I feel like its not design efficient, but I am not able to refactor them because of the different outer for-loop, if block and different probability calculating methods. Any suggestion on my code would be appreciated.

Data processing pipeline design for processing data

I have a use case for which I need to build a data processing pipeline

  • Customer contact leads data coming from different data sources like csv, data base, api has to be first mapped to a universal schema fields. There could be ~100k rows coming each day that need to be processed.
  • Then some of the fields have to be cleansed, validated and enriched. For example- the email field has to be validated by calling an external API to check if it's valid and does not bounce, address field has to be standardized to a particular format. There are other operations like estimating city, state from zip, phone number validation. Atleast 20 operations already planned, more to come in future
  • The above rules are not fixed and can change based on what user wants to do with his data (saved from user interface). For example, for a particular data, a user may only choose to standardize his phone number, but not check if its valid: thus operations performed on the data is dynamic.

Here is what I am doing currently:

  1. Load the data as a pandas data frame(have considered spark. But data set is not that large[max 200 mb-]to use spark). Have a list of user-defined operations that need to be performed on each field like

    actions = {"phone_number": ['cleanse', 'standardise'], "zip": ["enrich", "validate"]}

As I mentioned above, the actions are dynamic and vary from the data source to data source based on what user choose to do on each field. There is lot many custom business like this that can be applied specifically to a specific field.

  1. I have a custom function for each operation that user can define for fields. I call them based on the "actions" dictionary and pass the data frame to the function - the function applies the logic written to the data frame and returns the modified data frame.
def cleanse_phone_no(df, configs):
    # Logic
    return modified_df

I am not sure if this is the right approach to do it. Things are going to get complicated when I have to call external API's to do enrichment of certain fields in future. So I am considering a producer-consumer model

a. Have a producer module that creates that splits each row in file(1 contact record) as single message in a queue like AMQ or Kafka

b. Have the logic to process the data in consumers - they will take one message at a time and process them

c. The advantage I see with this approach is -it simplifies the data processing part- data is processed one record at a time. There is more control and granularity Disadvantage is it will create overhead in terms of computation as a record in processed one by one - which I can overcome to an extent using multiple consumers

Here are my questions:

  • What is your opinion about the approach? Do you have any suggestions for a better approach?
  • Is there any more elegant pattern I can use to apply the custom rules to the data set that what I am using currently
  • Is using a producer-consumer model to process the data one row at a time than entire data set advisable (considering all the complexity in logic that would come in future)? If so should I use AMQ or Kafka?

mercredi 28 novembre 2018

How to restrict textbox in html to only accept letters with space?

I want to restrict textbox to only accept letters with spaces. I have tried this but it is not accepting spaces

<input type="text" 
       maxlength = "15"  
       name="txtName" 
       pattern="[A-Za-z \s*]"  
       class="form-control"  
       placeholder="Name" 
       required="required" 
       class="validate">

I also try this pattern.

pattern="[A-Za-z][" "]" 

I don't want to use any function for this pattern in my code. How can I do this in simple one line code.?

Design pattern to use when the application wants to know which concrete class it got

I have a class structure like the on below.

    class Technology;
    class BasicTechnology : public Technology;
    class BasicChildTechnology : public BasicTechnology;
    class ConcreteChildTechnology1 : public BasicChildTechnology;//concretechildtech1
    class ConcreteChildTechnology2 : public BasicChildTechnology;//concretechildtech2
    class ConcreteChildTechnology3 : public BasicChildTechnology;//concretechildtech3
...
    class ConcreteChildTechnologyN : public BasicChildTechnology;//concretechildtechN

The ConcreteChildTechnologyN/3/2/1 has an isValid(String selector) method, which is as shown below,

public isValid(String selector){
 return "concretechildtech1".Equals(selector);
}

Now in the client code is,

Technology tech = getTechnologyObject("concretechildtech1"); //tech becomes an instance of ConcreteChildTechnology1

How should I implement getTechnologyObject() in this case?.

Thought of using the abstract factory pattern, but doubtful of that. or even create a Facade and create the concrete child based on the input argument? The problem is, only the ConcreteChildTechnology1 knows whether the input string (concretechildtech1) belongs to him or not; via isValid() method.

Again if I start to create N objects every time to check the validity, that will cause and overhead, because 1)the system is running in a very low memory environment like mobile and tablets, 2)the number of instance creation is high, 10-100 per minute.

May be make the isValid() a static inline method and create object based on the reply from child objects?

Composing a common interface with c# library class

Suppose I have a class:

public class Foo<TKey, TValue> {
    private readonly ConcurrentDictionary<TKey, TValue> m_dict;
    public Foo() {
        m_dict = new ConcurrentDictionary<TKey, TValue>();
    }
    public void AddThings(TKey key, TValue val) {
        m_dict.Add(key, val);
    }
    public void RemoveThings(TKey key) {
        m_dict.Remove(key);
    }
    //}

This is the API for ConcurrentDictionary : https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2?view=netframework-4.7.2 It implements the following interfaces:

public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, IDictionary, ICollection, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>

Essentially my class Foo uses a subset of ConcurrentDictionary's API methods.

Now there is a requirement to use a ConcurrentTreeMap<TKey, TValue> in the client class in certain use cases. I have implemented a ConcurrentTreeMap<TKey, TValue> class myself with all the API methods the client class is requiring. This class implements IDictionary<TKey, TValue> and ICollection<KeyValuePair<TKey, TValue>>

I want my Foo client class to be able to use both ConcurrentDictionary and ConcurrentTreeMap. Something like this, simplified:

public class Foo<TKey, TValue> {
        private readonly IConcurrentDictionary<TKey, TValue> m_dict;
        public Foo(IConcurrentDictionary dict) {
            m_dict = dict;
        }
        public void AddThings(TKey key, TValue val) {
            m_dict.Add(key, val);
        }
        public void RemoveThings(TKey key) {
            m_dict.Remove(key);
        }
        //}

This would be easy for languages like Python and Go. If I had access to ConcurrentDictionary's implementation I would obviously just extract a common interface type between the two. Or I could define a composite interface of all the interfaces ConcurrentDictionary implements. But since ConcurrentDictionary is part of some base c# library, I can't do that. Should I use some type of proxy class between ConcurrentDictionary and my custom interface? That seems like a lot of boilerplate code I'd have to write.

The backing data between a treemap and a hashmap(dictionary) is quite different so I also couldn't inherit ConcurrentTreeMap from ConcurrentDictionary (most of its methods are not virtual, anyways).

Building complex data class

I have the following builder/factory which abstracts a serializeable model from a class.

public class FooBarFactory : IFooBarFactory
{
    public IFooModel Create(IFoo someClass)
    {
        // some complex model building code here
    }
}

And I have a concrete implementation of IFooModel like so:

public interface IFooModel
{
    string AbstractedData1 { get; }
    string AbstractedData2 { get; }
    int AbstractedData3 { get; }
}

public class ConcreteFooModel : IFooModel
{
    public string AbstractedData1 { get; set; }
    public string AbstractedData2 { get; set; }
    public int AbstractedData3 { get; set; }
    public bool ExtraData1 { get; set; }
}

Now arises the issue, I am struggling to find a way to not reference any concrete implementations in my builder/factory method, e.g.

public class FooBarFactory : IFooBarFactory
{
    public IFooModel Create(IFoo someClass)
    {
        // some complex model building code here
        var model = new ConcreteFooModel(someClass.data1, someClass.data1); // Aaargh
    }
}

Something about this code is smelly to me, perhaps this is the only way, but I don't like the idea of being forced into referencing the concrete implementation to instantiate the data class, IFooModel.

This gets more complex if I now introduce another data holder interface into the IFooModel

public interface IFooModel
{
    string AbstractedData1 { get; }
    string AbstractedData2 { get; }
    int AbstractedData3 { get; }
    IBarData BarData { get; }
}

public interface IBarData
{
    // some data in here
}

Forcing me then to create another concrete reference for the nested interface

public class FooBarFactory : IFooBarFactory
{
    public IFooModel Create(IFoo someClass)
    {
        // some complex model building code here
        IBarData barData = new ConcreteBarData();
        IFooModel model = new ConcreteFooModel(someClass.data1, someClass.data1, barData);
    }
}

Is there a better way to do this while still sticking to the SOLID principle and IoC?

CQRS - Creating BaseCommandHandler using Mediatr in C#, ASP.net Core

So I learned about Mediatr created by Jimmy Bogard and it really amazed me how we achieve CQRS pattern using Mediatr.

I started to implement it in my application, and then I realized that I might have hundreds of Entities in my application, and for each Entity I am not sure about creating separate commands and queries, that would be just opposite of DRY. So I started writing base commands and handlers.

public abstract class CreateBaseCommand : IRequest
{    
}

public abstract class DeleteBaseCommand : IRequest
{
}  //... and so on.

And respective handlers.

public abstract class CreateBaseHandler : IRequestHandler<CreateBaseCommand>
{
}

public abstract class DeleteBaseCommandHandler : IRequestHandler<DeleteBaseCommand>
{
}//... and so on.

But I realised, I would still need separate commands for my domain entities, and they will have to derive from their Base commands respectively.

Then I though if I can just put all commands in one and have just one base handler.

    public abstract class BaseCommand : IRequest
    { 
       int CommandType
    }

    public abstract class BaseCommandHandler : IRequestHandler<BaseCommand>
    {
       public Task<Unit> Handle(BaseCommand request, CancellationToken cancellationToken)
       {
        if (CommandType == 0)
        {
            // Create entity
        }
        if (CommandType == 1)
        {
            // Update entity
        }//.. and so on
      }
    }

I was wondering if there is more efficient way to do this, I am not very convinced with idea of using CommandType and have one handle method to perform all CRUD operations.

Is this a good approach or should I have separate set of commands for each domain entity?

Any help and suggestions are appreciated.

Update all rows in SQL table periodically

We have a SQL table which the primary key is a guid. We want to periodically query some service - and unfortunately these have to be individual queries per row - and update all of the rows with new values.

We have a distributed system which we can run separate update queries on separate nodes concurrently.

My current design involves around retrieving N rows at a time from different nodes, so the work is splitted. Perhaps add another index field which will help this splitting mathematically (like an int). Another potential design would be to queue all of the update queries and use auto-scaling to handle them as quickly as it can.

Just wanted to see what other types of architecture can be planned around a requirement like this.

Is a public static DateTime field an anti pattern or a good practice?

In our program we have so called WallclockDateTime. Because we can shift in time, this WallclockDateTime is not related to the current time. But now I need this WallclockDateTime everywhere in my classes.

First I decided to pass this WallclockDateTime by reference from constructor to constructor. But that takes a lot of maintenance. And now I have some class Foo which is created in masses in a Collection<Foo>, and passing this same WallClockTime over and over again through the constructor seemed a bit useless to me. So I thought: Can't this be done more efficient?

First I tried to make the central WallclockDateTime static. But the OnPropertyChanged() is from outside my solution. If I make _wallclockDateTime public and static I can get to it everywhere! But it seems dirty to me. So what is a good solution for this? Passing from constructor to constructor? Or make the field public and static? Or some other clever solution?

    private DateTime _wallclockDateTime;
    public DateTime WallclockDateTime
    {
        get
        {
            return _wallclockDateTime;
        }
        set
        {
            if (_wallclockDateTime != value)
            {
                _wallclockDateTime = value;
                OnPropertyChanged(nameof(WallclockDateTime));
                OnPropertyChanged(nameof(CurrentSliderStateLabel));
                OnPropertyChanged(nameof(WallclockDateTimeTicks));
            }
        }
    }

// This class is used in a Collection<Foo>
public class Foo
{
    private static DateTime _wallClockTime;

    public Foo(ref DateTime wallClockTime)
    {
        _wallClockTime = wallClockTime;
    }

    public void Bar()
    {
        // Do something with the _wallClockTime
    }
}

Query builder design pattern?

I want to build a query builder for ElasticSearch but struggling to find the best pattern(s) to design it properly.

here is what I want to achieve

$builder
  ->index($indexString)
  ->type($typeString)
  ->query(function($builder){
    $builder->bool(function($builder){
      $builder
        ->must($field, $value)
        ->must($field2, $value2);
    });
  });

Any idea where to start or similar examples to learn from?

Testing error message content for multiple languages

I'm writing negative tests for checking content of error message shown to the user. There are two languages in app: english and german. The test works but the code for checking each language looks like this:

//Check if modal dialog with error message is shown
                string currentLanguage = loginPage.currentLanguage.Text;
                string modalMessage = loginPage.errorMsgModalDialogTitle.Text;

                try
                {
                    Assert.True(!string.IsNullOrEmpty(modalMessage));
                    test.Log(Status.Pass, "Office365 login has failed and modal dialog was shown to user!");
                    test.Log(Status.Info, "Checking modal dialog error message...");

                    switch (currentLanguage)
                    {
                        //Current language is english
                        case "German":
                            try
                            {
                                Assert.AreEqual(modalMessage, "User does not exist!");
                                test.Log(Status.Pass, "Modal dialog message title verified!  Message title: '" + modalMessage + "'");
                            }
                            catch(AssertionException)
                            {
                                test.Log(Status.Fail, "Modal dialog did not contain message title: '" + modalMessage + "'");
                            }
                            break;

                        //Current language is german
                        case "English":
                            try
                            {
                                Assert.AreEqual(modalMessage, "Benutzer existiert nicht!");
                                test.Log(Status.Pass, "Modal dialog message title and text verified!  Message title: '" + modalMessage + "'");
                            }
                            catch (AssertionException)
                            {
                                test.Log(Status.Fail, "Modal dialog did not contain message title: '" + modalMessage + "'");
                            }
                            break;
                    }
                }

As you can see, the code to check the title of modal dialog in both languages is kinda too big and there will be negative tests with even more error messages to check in both languages.

Is there a way to somehow refractor this code and make it simpler or cleaner? Could I create some helper method that just takes current language as parameter, message and expected message and just return true or false?

How to synchronize multiple controls?

I am looking for pattern in swift to synchronize the state of multiple controls. Say I have NSSegmentedControl in the view, NSMenuItems with checkmarks and NSSegmentedControl in touch bar. Each of them is sending change to model. But how to synchronize with other two? I can use delegates but it looks like the complexity will grow with number of synchronizable items. Is there a common pattern to approach this problem? I would think of something like subscription to change, so all 3 controls can subscribe to it and receive notification when a change occurs, then use it's own transformation of data to pass to the control. Wonder if there is some mechanism for that.

Use Connection inside Entity

I don't really know, how to call this approach, but question is - is it ok doing something like this. I create an entity Messages and set Connection inside this entity.

<?php

class Message {
   private $connection;

   public function setName();
   public function setSubject();

   public function send()
   {
       $this->connection->send($this);
   }
}

It looks like violation of single responsibility principle.

I have service Mailer which can create Message entity (already with Connection inside). Also Mailer can send Message entity by itself.

And there are two options, how I can use it;

<?php
// First
$mailer->send($message);

// Second
$message->send();

Is it not ok, and I should use only first approach?

mardi 27 novembre 2018

What is the most idiomatic way to mimic inheritance in Go in this specific case?

I've been thinking alot about this particular problem I'm having an how I'm supposed to solve it the cleanest way.

Imagine an application looking like this:

type AreaCalculator interface {
  Area() int
}

type Rectangle struct {
    AreaCalculator
    color  string
    width  int
    height int
}

type Circle struct {
    AreaCalculator
    color    string
    diameter int
}

type Canvas struct {
    children []AreaCalculator
}

func (c *Canvas) String() {
    for child := range c.children {
        fmt.Println("Area of child with color ", child.color, " ", child.Area())
    }
}

This example obviously would not compile because while the String() method of Canvas can call c.Area(), it can't access c.color since there's no way to make sure that a struct implementing AreaCalculator has that property.

One solutions I could think of was to do it like this:

type AreaCalculator interface {
  Area() int
  Color() string
}

type Rectangle struct {
    AreaCalculator
    color  string
    width  int
    height int
}

type (r *Rectangle) Color() string {
   return r.color
}

type Circle struct {
    AreaCalculator
    color    string
    diameter int
}

type (c *Circle) Color() string {
   return c.color
}

type Canvas struct {
    children []AreaCalculator
}

func (c *Canvas) String() {
    for child := range c.children {
        fmt.Println("Area of child with color ", child.Color(), " ", child.Area())
    }
}

The other way would be to try something like this:

type Shape struct {
    Area func() int 
    color string
    diameter int
    width int
    height int
}

func NewCircle() Shape {
    // Shape initialisation to represent a Circle. Setting Area func here
}


func NewRectangle() Shape {
    // Shape initialisation to represent a Rectangle. Setting Area func here
}

type Canvas struct {
    children []Shape
}

func (c *Canvas) String() {
    for child := range c.children {
        fmt.Println("Area of child with color", child.color, " ", child.Area())
    }
}

None of these options seem clean to me. I'm sure there's a way cleaner solution I can't think of.

How to create an abstract adapter class that forces subclasses to call specific methods in constructor

I am looking for feedback on a design I did for a custom adapter class in java. I am trying to create an elegant solution for an abstract adapter class that can be extended to create unique adapters that can connect to different data stores. Here are some of the requirements

  • Each adapter must implement an initialize function that establishes the connection
  • Each adapter must implement an execute function
  • The initialize function must be called when a new instance of the adapter class is created
  • Each adapter constructor must take in a Configuration object that contains all the connection information for that specific adapter.
  • Configurations are unique to the adapter, but I want a way to enforce that the configuration gets read in and set to a config variable either at the abstract class level or the base class level.

I also chose to implement a factory pattern when creating a new adapter here is my code below:

BaseAdapter.java

public abstract class BaseAdapter {

    private Configuration config;

    /*
        Default constructor
    */
    protected BaseAdapter(Configuration config) {
        this.config = config;
    }

    /*
        Abstract method that will initialize adapter with
        Configuration properties
    */
    public abstract void initialize(Configuration config);

    /*
        Abstract method that will execute query
    */
    public abstract void execute(String query);

ElasticSearchAdapter.java

public class ElasticSearchAdapter extends BaseAdapter {

    public ElasticSearchAdapter(Configuration config) {
        super(config);
        initialize(config);
    }

    @Override
    public void initialize(Configuration config) {
       //initialization implementation
    }

    @Override
    public void execute(String query) {
       //execute query
    }

}

BaseAdapterFactory.java

 public class BaseAdapterFactory {

     private static final String ES = "elasticsearch";

     public static BaseAdapter getBaseAdapter(String type, Configuration config) {

        if(ES.equals(type)) {
            return new ElasticSearchAdapter(config);
        }
        else {
            return null;
        }
    }
}

I was curious if there is a better way to design this based on the requirements stated above.

Should suffixes like "Builder" and "Factory" only be used when that pattern is being utilised?

One of things I struggle with most as a junior is coming up with suitable names for the classes that I am creating. I'm learning a lot about different coding patterns at the moment, and some of the patterns that are coming up regularly are Builder, Factory, and Repository.

However when I'm writing my code I'm unsure whether or not these suffixes should be reserved and only used when that particular pattern is being utilised within my code. So unless I'm implementing the builder pattern I should not use the 'Builder' suffix.

However if this is the case then this leaves me with the problem of not knowing what I should name my classes. Obviously there are some classes that have the responsibility of "building" a product from data or other classes, what suffixes or naming conventions should I use for these classes in particular?

Using C# if that matters.

Why do we inject database context in repositories instead of creating database context inside repository class itself?

One of the objectives of Repository pattern is supposed to decouple business logic with data access. Then why is it that database context is not created in repository class itself instead of being provided to it by service layer or controller?

Java correct Design Pattern

I have faced this problem a few times in the past, but haven't really found a good solution/design for it.

The below example code will generate PDF doc from Entity (Company or Article)

public class Entity
{
    int id;
}

public class Company extends Entity
{
    private String HQ;
}

public class Article extends Entity
{
    private String title;
}

public interface EntityPDFGenerator
{
    void generate(Entity entity);
}

public class ArticlePDFGenerator implements EntityPDFGenerator
{
    public void generate(Entity entity)
    {
        Article article = (Article) entity;
        // create Article related PDF from entity
    }
}

public class CompanyPDFGenerator implements EntityPDFGenerator
{
    public void generate(Entity entity)
    {
        Company company = (Company) entity;
        // create Company related PDF
    }
}

Main class:

public class PDFGenerator
{
    public void generate(Entity entity)
    {
        EntityPDFGenerator pdfGenerator = getConcretePDFGenerator(entity);
        pdfGenerator.generate(entity);

    }

    // lets make the factory task simple for now
    EntityPDFGenerator getConcretePDFGenerator(Entity entity)
    {
        if(entity instanceof Article){
            return new ArticlePDFGenerator();
        }else{
            return new CompanyPDFGenerator();
        }
    }
}

In the above approach the problem is with the casting the Entity to the concrete type (casting can be dangerous in later stage of the code). I tried to make it with generics, but then I get the warning

Unchecked call to 'generate(T)'

I am just wondering if there is any good design for it?

Best, Karoly

OO programming about state

This is my professor's assignment for oo programming. But I found that the marital status can be an variable in the Person class, how can I achieve this with two classes?

Assume people can have marital status: single, married, widow, divorced. Create a state OODP (i.e., Java, JavaScript, C++, Python, or Ruby) that deal with people's marital status. You will have at least two classes: Person, and Marital State. Make sure the following rules are followed: single->married married-> divorced | widow divorced -> married widow -> married create a Client class to test your program. Make sure you test valid and invalid change of marital status.
The assignment page


These are my codes:

public class AssignmentOOP {
    public static void main(String[] args) {
        Person p1 = new Person("p1");
        Person p2 = new Person("p2");
        Person p3 = new Person("p3");
        p1.PrintMaritalStatus();
        p2.PrintMaritalStatus();
        p3.PrintMaritalStatus();
        p1.GetMarried(p2);
        p1.GetMarried(p3);
        p2.Died();
        p1.GetMarried(p3);
    }
}

class Person {
    String maritalstatus;
    boolean mateIsAlive;
    Person mate;
    String name;

    Person(String name1) {
        maritalstatus = "single";
        mate = null;
        name = name1;
    }

    void GetMarried(Person mate) {
        if(this.maritalstatus.equals("married")|| mate.maritalstatus.equals("married"))
        {
            System.out.println("Marital status error! At least one of you are married");
            return;
        } else {
            this.maritalstatus = "married";
            this.mate = mate;
            mate.maritalstatus = "married";
            mate.mate = this;
            System.out.println("Congratulations!!! " + this.name + " and " + mate.name + " are married!");
        }
    }

    void GetDivorced(Person mate) {
        if(this.maritalstatus.equals("married") && this.mate == mate) {
            maritalstatus = "divorced";
            System.out.println(this.name+" and "+mate.name+" are getting divorced.");
        }else if(this.maritalstatus.equals("single")) {
            System.out.println("You are not married and you cannot get divorced before getting married");
        }else if(maritalstatus.equals("widow")) {
            System.out.println("Your marital status is widow, you cannot get divorced.");
        }
    }

    void Died() {
        this.maritalstatus = "dead";
        this.mate.maritalstatus = "widow";
        System.out.println("Sorry for your loss, " + this.mate.name + " marital status is widow.");
    }

    void PrintMaritalStatus() {
        System.out.println(this.name + " marital status is " + this.maritalstatus);
    }
}

Applying the strategy design pattern

I need to write a program for text lemmatization (different forms of words). Since I'm going to be using different lemmatization libraries and comparing them I've decided to use Strategy Pattern.

My idea is to wrap everything to single class and, depending on lemmatization function, only change my lemmatize method.

Here's my class:

import re
import types

create_bound_method = types.MethodType

class Lemmatizator(object):
def __init__(self, filename=None, lemmatization=None):
    if lemmatization and filename:
        self.filename = filename
        self.lemmatize = create_bound_method(lemmatization, self)

def _get_text(self):
    with open(f'texts/{self.filename}.txt', 'r') as file:
        self.text = file.read()

def _split_to_unique(self):
    text = re.sub(r'[^\w\s]', '', self.text)
    split_text = re.split(r'\s', text)

    self.unique_words = set(split_text)

    return self.unique_words

def lemmatize(self):
    return 'Lemmatize function or text are not found'

Then I'm creating my lemmatize method:

def nltk_lemmatization(self):
words = {}

for word in self.unique_words:
    if word:
        words[word] = {
            'noun': wnl.lemmatize(word),
            'adverb': wnl.lemmatize(word, pos='r'),
            'adjective': wnl.lemmatize(word, pos='a'),
            'verb': wnl.lemmatize(word, pos='v')
        }

return words

And trying to apply it:

nltk_lem = Lemmatizator('A Christmas Carol in Prose', nltk_lemmatization)
nltk_lem.lemmatize()

But I receive the following error:

for word in self.unique_words:

AttributeError: 'Lemmatizator' object has no attribute 'unique_words'

what's wrong?

C# asp.net web api best way or design pattern to implement DRY principle

I have the following two action methods in my controller. Both take the same parameter and do the same validation of the model. it differs at only one line where it makes a call to a service method.

Is there a better way to refactor this code?

[HttpPost]
public async Task<IActionResult> Search([FromBody]AggregateSearchCriteria criteria)
{
    if (criteria == null || !criteria.Aggregates.Any())
    {
        return BadRequest();
    }

    var providers = Request.Headers["providers"];

    if (providers.Equals(StringValues.Empty))
        return BadRequest();

    criteria.Providers = providers.ToString().Split(',').ToList();

    ModelState.Clear();

    TryValidateModel(criteria);

    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var result = await _searchService.Search(criteria);

    return Ok(result);
}

[HttpPost("rulebreak")]
public async Task<IActionResult> SearchRuleBreak([FromBody]AggregateSearchCriteria criteria)
{
    if (criteria == null || !criteria.Aggregates.Any())
    {
        return BadRequest();
    }

    var providers = Request.Headers["providers"];

    if (providers.Equals(StringValues.Empty))
        return BadRequest();

    criteria.Providers = providers.ToString().Split(',').ToList();

    ModelState.Clear();

    TryValidateModel(criteria);

    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var result = await _searchService.SearchRuleBreak(criteria);

    return Ok(result);
}

lundi 26 novembre 2018

Javascript - lots of standalone functions are bad ??? (node.js)

I am refactoring my code now..and I have to refactor my lots of if..else statements, so I am now creating many functions by each conditions.

Code:

class Strategy {
    constructor(state) {
        this.state = state;

        if(this.state === 1){
          return first();
        }else if (val === 2){
          return second();
        }else if (val === 3){
          return third();
        }
    }

}

function first(){
  //do something
}

function second(){
  //do something
}

function third(){
  //do something
}

let firstClass = new Strategy(1);

Is it OK to declare all each functions by condition??? Or, Is it better to declare each functions in prototype method?/?

Javascript - Refactoring if..else statements (ES6)

now I am trying to refactor my lots of if..else statements.

My code:

let condition = 'hi';

if(condition === 'hi'){
  commonFunction('hi');
  console.log('hi is called');

}else if(condition === 'bye'){
  commonFunction('bye');
  console.log('bye is called');

}else if(condition.includes('happy')){
  commonFunction('happy');
  console.log('happy is called');

}else if(condition === 'greeting'){
  commonFunction('greeting');
  console.log('greeting is called');

}

Refactored Code:

if(condition === 'hi'){
  hi();
}else if(condition === 'bye'){
  bye();
}else if(condition.includes('happy')){
  happy();
}else if(condition === 'greeting'){
  greeting();
}

function hi(){
  commonFunction('hi');
  console.log('hi is called');
}

function bye(){
  commonFunction('bye');
  console.log('bye is called');
}

function happy(){
  commonFunction('happy');
  console.log('happy is called');
}

function greeting(){
  commonFunction('greeting');
  console.log('greeting is called');
}

Is it better to declare each functions by condition like my refactored code???

Or, How about make class and call commonFunction by constructor? (I think switch..case is not useful becasue I have a condition that has includes() )

What design pattern would be suitable for this program?

Supose I have to create a GUI application in Java. The layout looks like this: enter image description here

Both panels are JPanel objects. The left one contains an object from class ProductList.java that extends awt.List. The right one contains an object from class ProductTable.java that extends JScrollPane and adds a TableModel implementation to its JViewPort object. Both ProductList and ProductTable are added to the panels like this:

pleft.add(new ProductList()); 

and

pright.add(new ProductTable());  

Now this has to change. A Lister.java class has to replace those classes like this:

pleft.add(new Lister(Lister.LIST));

and

pright.add(new Lister(Lister.TABLE));

I recently started seeing design patterns in java , so my understanding and experience using them is fairly limited. I could think of a factory or decorator design pattern, since the Lister class delivers two objects that are somewhat related (they both are awt.Component objects). What confuses me, is how new Lister() could deliver two different objects using only a String constructor parameter. Im stuck here:

public class Lister{

    public static final String LIST = "LIST";
    public static final String TABLE = "TABLE";

    public Lister(String type){
        if(type.equals(LIST)) {

        }
        if(type.equals(TABLE)) {

        }
    }
}

What design pattern to use in this program?

This is a program that displays two tables inside a JFrame component. The first table uses a awt.List object and the other table is a TableModel instance inside a JScrollPane object. Below code shows how those objects are added to the Pane.

ProductDisplay.java

public class ProductDisplay extends JFrame
{
    private static final long serialVersionUID = 1L;

    public ProductDisplay()
    {
        super("Die Telematik-Produkte");
        setLF();             //set look and feel
        setCloseClick();     //set close on window close click
        InputFile f = new InputFile("products.txt");
        Vector<String> prod = new Vector<String>();
        //read in product list
        String s = f.readLine();
        List alist = new List();

        while(s != null)
        {
            prod.addElement(s);
            s = f.readLine();
        }
        JPanel p = new JPanel();
        getContentPane().add(p);
        p.setLayout(new GridLayout(1,2));

        JPanel pleft = new JPanel();
        JPanel pright = new JPanel();
        p.add(pleft);
        p.add(pright);
        pleft.setLayout(new BorderLayout());
        pright.setLayout(new BorderLayout());

        //add in customer view as list box
        pleft.add("North", new JLabel("Customer view"));

        // Here, ProductList and ProductTable are added to the Pane object. 
        // Now, a new class Lister.java has to be created and represent both 
        // objects depending on the second constructor parameter
        pleft.add("Center", new ProductList(prod));           // This row ...
        //pleft.add("Center", new Lister(prod, Lister.LIST)); // ...should be replaced by this one

        //add in execute view as table
        pright.add("North", new JLabel("Executive view"));

        pright.add("Center", new ProductTable(prod));           // And this row ...
        //pright.add("Center", new Lister(prod, Lister.TABLE)); // ...should be replaced by this one


        setSize(new Dimension(400,300));
        setVisible(true);
    }
    //-----------------------------------------  
    private void setCloseClick()
    {
        //create window listener to respond to window close click
        addWindowListener(new WindowAdapter() 
        {
            public void windowClosing(WindowEvent e) {System.exit(0);}
        });
    }
    //------------------------------------------
    private void setLF()
    {
        // Force SwingApp to come up in the System L&F
        String laf = UIManager.getSystemLookAndFeelClassName();
        try {
            UIManager.setLookAndFeel(laf);
        }
        catch (UnsupportedLookAndFeelException exc) 
        {System.err.println("Warning: UnsupportedLookAndFeel: " + laf);}
        catch (Exception exc) {System.err.println("Error loading " + laf + ": " + exc);
        }
    }

    //---------------------------------------------

    static public void main(String argv[])
    {
        new ProductDisplay();
    }
}

The to be created class Lister.java accepts as parameters a products Vector and a String stating what type of table to represent.

ProductList.java

public class ProductList extends java.awt.List
{
    private static final long serialVersionUID = 1L;

    public ProductList(Vector<String> products)
    {
        super(products.size());    //for compatibility
        for (int i = 0; i < products.size(); i++)
        {
            //take each strig apart and keep only
            //the product names, discarding the quntities
            String s = products.elementAt(i);
            int index = s.indexOf("--");  //separate qty from name
            if(index > 0)
                add(s.substring(0, index));
            else
                add(s);
        }
    }
}

ProductTable.java

public class ProductTable extends JScrollPane
{
    private static final long serialVersionUID = 1L;

    JTable table;

    public ProductTable(Vector<String> list)
    {
        table = new JTable(new prodModel(list));
        getViewport().add(table);
    }
}
class prodModel implements TableModel
{

    int rows;

    int columns;

    Vector<String> prodNames;

    Vector<String> quantities;

    public prodModel(Vector<String> products)
    {
        rows  = products.size();
        columns = 2;
        prodNames = new Vector<String>();
        quantities =  new Vector<String>();
        for(int i=0; i< products.size(); i++)
        {
            String s = products.elementAt(i);
            int index = s.indexOf("--");  //separate qty from name
            if(index > 0)
            {
                prodNames.addElement(s.substring(0, index));
                quantities.addElement(s.substring(index+2).trim());
            }
            else
                prodNames.addElement(s);

        }
    }
}

So basically, the to be created class Lister.java has to be able to "mutate" into both objects. Multiple inheritance is not possible in Java so extending both classes is not possible. My limited understanding on design patterns is that this could be solved using a Factory Method or maybe a Facade, but im not even sure. My Lister.java looks as follows:

Lister.java

public class Lister{

    public static final String LIST = "LIST";
    public static final String TABLE = "TABLE";

    public Lister(Vector<String> product, String type){
        if(type.equals(LIST)) {

        }
        if(type.equals(TABLE)) {

        }
    }   
}

Is there a problem using a "shared" private property in a class to build fluent/evolving DB query?

I'm trying to write a class that relies on some legacy code to fetch data from database related to a particular table (productcode)

For not repeating myself, I implement a private property $sql that holds the "evolving" query and finally applying getResult() on it (as this snippet shows it)

My question: is there any design principle violation by implementing this pattern? (specially adopting the "shared" $sql property). If the answer is yes, why and what is the proper way to do it?

<?php

class ProductCodeDataSource
{
    use dbmanager_aware_trait;
    private $sql;

    public function findByProductId($productId)
    {
        $this->sql = [];
        $this->sql['fields'] = 'productcode_value';
        $this->sql['tables'] = 'productcode';
        $this->sql['where'][] = sprintf('productcode_product_id = %d', (int) $productId);
        $this->sql['order'][] = 'productcode_default';

        return $this;
    }

    public function findOneByProductId($productId)
    {
        $this->findByProductId($productId);
        $this->sql['limit'] = 1;

        return $this;
    }

    public function getResult()
    {
        // get_all_value is a legacy method that fetches data from mysql DB

        // build_select_ext is also a legacy method that builds sql queries from
        // $sql array structures

        return$this->dbmanager->get_all_value($db->build_select_ext($this->sql));
    }
}

android quiz editor implementation

we are planning to build a quiz app for android. The idea is that the user can add quizzes, let us say he can add name, description, etc. in the quiz body the user can add text, images or code segments. So, the user has something like building blocks that he can add, rearrange and remove. Now the question is: what is the best way to implement this? What design pattern should we use? And what is the best strategy to represent these elements in android.

Design concerns about Page Object Model Pattern

I wonder if something is wrong with our approach to the POM. In many examples on the internet I find this pattern used in a way so that your test script looks like this:

pageObject.doSomethingWithElement(parameters...)

For us it was more natural to do it like this:

pageObject.element.doSomething(parameters...)

So we don't need to implement what can be done with an element in the page class but just simply define those actions in the test script. For some reason that felt more natural for us similar to the fact that there is

System.out.println()
System.err.println()

instead of

System.printlnOut()
System.printlnErr()

Do we miss some disadvantage of our approach?

design pattern to handle sequential tasks c#

i'm struggling to find a good way to create multiple workflows that sometimes share steps. are there any good resources that solves these problems, and enforces the "Required-Rule" between steps.

public class Weekday
{
    // Initial Step
    public BreakfastStep BreakfastStep { get; set; }

    // Breakfast step required
    public WorkStep WorkStep { get; set; }

    // Work step required
    public ExerciseStep ExerciseStep { get; set; }
}

public class Weekend
{
    // Initial Step
    public BreakfastStep BreakfastStep { get; set; }

    // Breakfast step required
    public ExerciseStep ExerciseStep { get; set; }
}

public class ExerciseStep
{
    public bool ChangeClothesComplete { get; set; }
    public bool RunEnabled => ChangeClothesComplete;
    public bool RunComplete { get; set; }
    public bool ShowerEnabled => RunComplete;
    public bool ShowerComplete { get; set; }
}

public class BreakfastStep
{
    public bool GetItemsComplete { get; set; }
    public bool MakeSandwichEnabled => GetItemsComplete;
    public bool MakeSandwichComplete { get; set; }
    public bool EatSandwichEnabled => MakeSandwichComplete;
    public bool EatSandwichComplete { get; set; }
}

public class WorkStep
{
    public bool CommuteComplete { get; set; }
    public bool DoWorkEnabled => CommuteComplete;
    public bool DoWorkComplete { get; set; }
    public bool CommuteBackHomeEnabled => DoWorkComplete;
    public bool CommuteBackHomeComplete { get; set; }
}

Javascript - Change lots of if statements by using class (ES6)

I am using lots of if statements in my code now, so I want to change by using class (ES6)

However, I am not much good at Javascript... so PLZ HELP ME..!

Prior code:

//example code
function first(){
  console.log('first scenario called');
}

function second(){
  console.log('second scenario called');
}

function third(){
  console.log('third scenario called');
}

state = 1;
if(state === 1){
  first();
}else if(state === 2){
  second();
}else if(state === 3){
  third();
}
//first scenario called

Changed code:

class Strategy {
    constructor(state) {
        this.state = state;

        if(this.state === 1){
          return first();
        }else if (val === 2){
          return second();
        }else if (val === 3){
          return third();
        }
    }

}

function first(){
  console.log('first scenario called');
}

function second(){
  console.log('second scenario called');
}

function third(){
  console.log('third scenario called');
}

let firstClass = new Strategy(1);
//first scenario called

This is my sample code..

Actually, I have almost 50+ if statments. Is it right way to change lots of if statements???

dimanche 25 novembre 2018

How to follow Single Responsibility Principle in set of actions

I have a windows service application that read some files and does some modification and upload to a web API.

In here I followed the single responsibility principle as much as possible.

In this app, I have 3 classes that read files' content, apply business logic and upload that modified content to the server.

class GetFileContent { 
// in here there is a method to return the file content
}

class ApplyBusinessLogic { 
// in here there is a method to get that file content as param and apply business logic
}

class UploadContent {
// get the modified content and upload it
}

Now my question is if I added a new class as DoMyActions and create objects of above class and call theres methods for doing those task, is that violation of the Single Responsibility Principle? For make clear of my question I am tring to do something like below.

class DoMyAction { 

GetFileContent content = new GetFileContent();
// call the method in above class and get the content

ApplyBusinessLogic doMyThing = new ApplyBusinessLogic();
// do my stuff using that file content

UploadContent uploader = new UploadContent();
// upload the content
}

Is there a better approch on this?

If I continuously want to use DoMyAction class how to follow the Single Responsibility Principle?

Perl: How to substitute the content after pattern

So I cant use $' variable

But i need to find the pattern that in a file that starts with the string “by: ” followed by any characters , then replace whatever characters comes after “by: ” with an existing string $foo

im using $^I and a while loop since i need to update multiple fields in a file.

I was thinking something along the lines of [s///]

s/(by\:[a-z]+)/$foo/i

I need help. Yes this is an assignment question but im 5 hours and ive lost many brain cells in the process

Iterate nested objects in Yii2 php

I need iterate nested objects to form a proper JSON file with the following structure:

"stories": [
    {
        "storyID": "66d2efb9-2e16-4251-8e9d-8caa44323f81",
        "status": 0,
        "categoryID": "0345aa43-7fd8-4f32-a65a-143da19df423",
        "details": {
            "title": "Lily Green"
        },
        "seasons": [
            {
                "seasonID": "b6ccd3c7-ddd4-4044-a342-2f167532f2f2",
                "status": 0,
                "details": {
                    "title": "Season0",
                    "body": "He called me his little girl. The father could do anything he wanted with his little girl. 10 years ago he forced me to kill my mother. Today I’m gonna kill him.",
                    "previewAssetID": "e355a090-c10c-4feb-82c6-cf0279408b6b",
                    "coverAssetID": "e8cc3da6-03b4-46f4-8dce-bc02cf143f8d"
                },
                "episodes": [
                    {
                        "episodeID": "8c202576-d79f-4acc-8ea9-a8fa9600da9a",
                        "status": 0,
                        "preload": false,
                        "details": {
                            "title": "EpisodeTitle0"
                        },
                        "assetID": "67187c26-386b-419e-a30f-43fd4ff7ab8a"
                    }
                ]
            }
        ]
    }
]

Appropriately I have entities called Story, Season and Episode. Story has many Season and Season has a lot of Episode I need to find some way how I can iterate those type of objects without using directly Yii2 relations like :

foreach($stories as $story){
   -----
   foreach($story->seasons as $season){
     ---
        foreach($season->episodes as $episode){

        }
   }
}

Above example didn`t suit for me cause it is possible that this structure will have bigger depth than now. I have already read about Iterator pattern, but to be honest, I can't realize how I can use it in my case. I will be appreciated for any advice.

Which of these is the correct way to compose interfaces?

Let's say I have a business entity called a "dude" which has the following characteristics:

  • Every dude has a first name
  • Every dude has an age
  • Some dudes have a last name
  • The idea of a "last name" only makes sense in the context of a dude; in other words, I don't expect it to be used in any other context

Option 1:

interface IDude
{
   string FirstName { get; }

   int Age { get; }
}

interface IDudeWithLastName : IDude
{
   string LastName { get; } 
}

Option 2:

interface IDude
{
   string FirstName { get; }

   int Age { get; }
}

interface ILastNamed
{
   string LastName { get; } 
}

interface IDudeWithLastName : IDude, ILastNamed
{
}

Is there any reference design or writings for the program/workflow process in Java (OOP)? [on hold]

Is there any reference design or writings for the program/workflow process in Java (OOP)?

This is the short version if the question which I am asking here but what follows is the longer version of it.

I have searched on internet about this topic and also in table of contents of many books to find information about the problem which is when to use static or not a static code for implementing the part behavior of a program.

It can be any other program but in my case it is an program which is manipulating (set values) the properties of objects which are part of a collections. The process is well known and is not changing much. Parts of it is implemented as static methods.

When reading the principles of OOP then the suggestion there are never based on static code. The lack of information about the static way of programming results into a dilemma, to use static content or not, and beside that if the usage of static way of programming is not a bad practice then another question is when precisely should it be used.

//not static example
...
public void manipulate(Object obj) {
    ObjectManipulator objectManipulator = new ObjectManipulator();
    objectManipulator.apply(obj);
}

//static example
...
public void manipulate(Object obj) {
    ObjectManipulator.apply(obj);
}

Both ways have their advantages and disadvantages.

  1. not static methods

    • creating objects - allocating memory, setting memory free - performance costs, less memory.
    • testing - Method can be mocked (JUnit, Mockito)
  2. static methods

    • not creating objects - memory allocation at the beginning once - less performance costs, more memory.
    • testing - Method can not be mocked (JUnit, Mockito) - but Powermock works which is bad practice?

An conversation about usage of static methods can be found under the question Java: when to use static methods.

But back to my question Is there any reference design or writings for the program/workflow process in Java (OOP)?

I am a little but suprised that I can't find anything on this topic in the books where the basic of OOP and its principles are described.

samedi 24 novembre 2018

Implementing multi-platform plugin architectute

I looked everywhere on this topic but didn't find the answer. So, I'm working on a mobile app which can extend its functionalities and UI using third party plugins. Later on, this will be implemented on the desktop application and a web app too. The technology stack I chose is JavaScript Stack.

The tech stack is: MERN Stack - Server-Side ReactJS - Web App React Native - Mobile ElectronJS - Desktop

I need suggestions on the following two points:

  1. Is this the best technology stack to use?
  2. If yes, then is it possible to create a single plugin manager and abstract layer which can be used in all these technology without or little changes. If no, then what will be the best technology stack & approach should I use?

Design pattern for services in unity3d

I want to establish decoupled and interchangable system in my unity architecture for 3rd party services like Analytics(Unity,GA, Firebase, FB Analytics), Advertisement etc. Which design pattern is most suitable for my needs ?

composite design pattern for awt and swing components

Im learning about design patterns in Java and Im still a little bit confused on how to implement them. I have a class TwoList.java that displays two awt.List objects. There are buttons that add texts to those lists and remove them. The question is the following: the class is to be modified that instead of using the awt.List objects, JList objects have to be used. Methods addName, moveNameRight and moveNameLeft can't be modified.

TwoList.java

//Demonstration of simple Two-list program
//using awt controls

import java.awt.*;
import java.awt.event.*;

public class TwoList extends Frame
   implements ActionListener
{
   private Button Add, MoveRight, MoveLeft;
   private List leftList, rightList;
   private TextField txt;

   public TwoList()
   {
      super("Two Lists");
      setCloseClick();
      setGUI();
   }
   //--------------------------------------------
   private void setGUI()
   {
      setLayout(new GridLayout(1,2));  //two columns
      setBackground(Color.lightGray);
      Panel pLeft = new Panel();
      Panel pRight = new Panel();
      add(pLeft);
      add(pRight);
      pLeft.setLayout(new BorderLayout());

      //top panel contains text field and 
      //Insert buttn
      Panel pTop = new Panel();
      pLeft.add("North", pTop);
      txt = new TextField(10);
      pTop.add(txt);
      Add = new Button("Insert");
      pTop.add(Add);

      //right border contains add and remove buttons
      Panel rBorder = new Panel();
      rBorder.setLayout(new GridLayout(2,1));
      MoveRight = new Button("Add --->");
      MoveLeft = new Button("<--- Remove");

      Panel rbTop = new Panel();
      rbTop.add(MoveRight);
      rBorder.add(rbTop);

      Panel rbBot = new Panel();
      rbBot.add(MoveLeft);
      rBorder.add(rbBot);
      pLeft.add("East", rBorder);

      leftList = new List(10);
      pLeft.add("Center", leftList);

      rightList = new List(10);
      pRight.add(rightList);

      //Add button action listenes
      Add.addActionListener(this);
      MoveRight.addActionListener(this);
      MoveLeft.addActionListener(this);

      setSize(new Dimension(400, 300));
      setVisible(true);
   }
   //-----------------------------------------  
   private void setCloseClick()
   {
      //create window listener to respond to window close click
      addWindowListener(new WindowAdapter() 
       {
            public void windowClosing(WindowEvent e) {System.exit(0);}
            });
   }
   //---------------------------------------------
   public void actionPerformed(ActionEvent e)
   {
      Button b = (Button)e.getSource();
      if(b == Add)
         addName();
      if(b == MoveRight)
         moveNameRight();
      if(b == MoveLeft)
         moveNameLeft();
   }
   //--------------------------------------------
   private void addName()
   {
      if (txt.getText().length() > 0) 
         {
         leftList.add(txt.getText());
         txt.setText("");
         }
   }
   //--------------------------------------------
   private void moveNameRight()
   {
     String sel[] = leftList.getSelectedItems();
     if (sel != null)        
     {
         if (sel.length==0) return;
         rightList.add(sel[0]);
         leftList.remove(sel[0]);
     }
   }
   //--------------------------------------------
   public void moveNameLeft()
   {
    String sel[] = rightList.getSelectedItems();
     if (sel != null)        
     {
         if (sel.length==0) return;
         leftList.add(sel[0]);
         rightList.remove(sel[0]);
     }
   }
   //--------------------------------------------
   static public void main(String argv[])
   {
      new TwoList();
   }
}

Looking at the docs of both objects, they have a hierarchy like this one:

    Object
      |
      |
  Component
  /        \
List     Container
              \
          JComponent
                \
              JList

By looking at this the design pattern that comes to my mind is Composite. List being a leaf and Container a composite object which holds JComponents and one of those is JList. This is my understanding, feel free to correct me. Although I think the Composite design pattern would work here, I dont know how to start or what to do.

Memento design pattern and its oop principles

I need to know what is the Oop principles that applied in memento design pattern? and simple explain of each one.

vendredi 23 novembre 2018

Enums vs string constants c#

So I have recently read a book specifically on Dependency Injection. In this book, somewhere, it states that enums are a code smell....

I wanted to get a general consensus from SO'ers. I need to design a rather large application with some central core classes, and am seeking assistance in terms design principles that fellow SO'ers would use in this instance, before committing myself to one way or the other making it very difficult to change afterwards.

public enum Foo
{
  LovelyFoo,
  TerribleFoo
}

OR

Using a static class with Contants

    public static class Foo
    {
    public const string LovelyFoo = nameof(LovelyFoo); //or "Lovely Foo";
    public const string TerribleFoo = nameof(TerribleFoo); // or "Terrible Foo";
    }
}

Then Of course using it when required

Foo MyFoo = Foo.LovelyFoo;

OR

string MyFoo = Foo.LovelyFoo;

OOP Design Pattern / reading information from file or API?

I have (x2) ways to get information for my object:

  1. Read from a file stored on the disc
  2. Access the application that made the file through the application's API

Once the information is acquired, I'll have methods to:

  • Display
  • Analyze
  • Change the information (again as either a file or through the API)

If I change the information, it need not be the same way that I received the information. Therefore I could:

  • Receive the info by file and push the info back by API
  • and all the other obvious combinations...

I won't have additional ways to get the data in/out (e.g. API and file cover all options).

The code will be in Matlab, so I don't have easy access to enumerated types and a few other nice programming features, so I'm tempted to use a design pattern rather than a switch inside the class.

Questions

What are appropriate design patterns for this problem?

Should I use a design pattern and write a few classes to get this done or just write a single class with a switch for file or API?

const access and non-const access

I have a class which internally owns a vector of foo

class bar {
  private:
    vector<Foo> foos_;
}

Now I want to design public access to this vector. I am thinking of two versions of the function:

Foo& getFoo(int index) {
  // first do size checking, return ref
  return foos[index];
}

and

const Foo& getFoo(int index) {
  // first do size checking, return const reference
  return foos[index];
}

Any downside of this approach? One obvious downside is I copy the almost identical code simply twice. Is there a better way to do this?

Is the following an anti pattern?

I have a class which consists of only methods and no state. Since it has methods only, I want to make it a singleton class.

 public class SomeSingleton implements SomeInterface {
    private static SomeSingleton instance;

    private SomeSingleton() {}

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

    // interface methods implementations
 }

Now when I test this class, inside the test I have to use this getInstance() method:

 @Test
 public void someMethodTest() {
   SomeSingleton singleton = SomeSingleton.getInstance();
   //test lines
 }

Is this an anti pattern? I get a gut feeling that this is not the right way. Is there some more elegant way of doing it?