dimanche 30 septembre 2018

Implementing Strategy pattern in C#

I am implementing strategy pattern. I have defined a strategy as interfaces and concrete classes to implement the strategy. Based on user selection/configuration, the algorithm to apply the discount changes.

  public interface IStrategy
    {
        double calculate(double x, double y);
    }

concrete classes implementing the gold strategy is listed below -

public class clsGoldDiscountStrategy : IStrategy
    {
        public double calculate(double x, double y)
        {
            return (x * y) * 0.8;
        }
    }
}

concrete classes implementing the platinumstrategy is listed below -

public class clsPlatinumDiscountStrategy : IStrategy
    {
        public double calculate(double x, double y)
        {
            return (x * y) * 0.7;
        }
    }

The business logic to apply

public class clsBL
    {
        public double costPrice { get; set; }
        public double qty { get; set; }
        IStrategy _strategy;

        public clsBL(IStrategy strategy)
        {
            _strategy = strategy;
        }

        public double GetfinalPrice(double cp, double qty)
        {
            return _strategy.calculate(cp, qty); 
        }

    }

//Main method

static void Main(string[] args)
        {
            Console.WriteLine("Enter the discount Plan (Gold/Platinum)");
            string filter = Console.ReadLine().ToUpper();
            double result = 0;

            if (filter.Length > 0)
            {
                switch (filter)
                {
                    case "GOLD":
                        //Gold 
                        clsBL blgold = new clsBL(new clsGoldDiscountStrategy());
                        blgold.costPrice = 5;
                        blgold.qty = 10;

                        result = blgold.GetfinalPrice(blgold.costPrice, blgold.qty);
                        break;

                    case "PLATINUM":
                        //Platinum
                        clsBL blplatinum = new clsBL(new clsPlatinumDiscountStrategy());
                        blplatinum.costPrice = 10;
                        blplatinum.qty = 8;

                        result = blplatinum.GetfinalPrice(blplatinum.costPrice, blplatinum.qty);
                        break;
                    default:
                        Console.WriteLine("Enter the discount value as either  gold or platinum");
                        break;
                }

                Console.WriteLine("The result for " + filter + " is " + result);

            }
            else
            {
                Console.WriteLine("Enter the discount value");
                return;
            }


            Console.ReadLine();

        }

Design a new cloud based application with multiple login mechanism

I recently switched to a new company where my manager wants me to develop entirely new cloud based project in MVC. I have never worked on a project from the start and I think this is a good opportunity for me to lead. However, I think the requirements of the clients are bit confusing.

Here is what he wants:

  1. Client should be able to access the cloud hosted application from his network with single sign on. He wants to use his active directory for that.
  2. There are different users in active directory, they will have different roles (I think we can handle this on database side. Create different roles and assign roles to users).
  3. Client has to add vendor info in the application. But for this, system should send an email to vendor with the url of the cloud application. He wants user to login to the application using 2 Factor Authentication. So, send dummy password with url, and send OTP to his mobile number. Just like registering to any system.

Now my questions are:

Is it possible to have 2 different types of login mechanisms in the same application? SSO for client and 2FA for outside vendors?

If yes, could you please guide me in the right direction?

what things I need? Which framework, design pattern should I prefer?

How do I proceed ?

Capture between variable string and pattern in lua

I want to get a string between two strings.

texterrors = [[
    <error_no name="1">
    <designator>M18</designator>
    <pin>M18</pin>
    <stamp_name>Con_10p</stamp_name>
    <package_name>M18</package_name>
    <errortype>9</errortype>
    <error_contents></error_contents>
    <pcb_no></pcb_no>
    <feeder_no></feeder_no>
    <pos_x>23735</pos_x>
    <pos_y>9722</pos_y>
    <window>2</window>
    <ng_message>Histogram NG 0%</ng_message>
    <comment>Histogram NG 0%(* *){Con_10p}</comment>
    <ng_image></ng_image>
    </error_no>
    <error_no name="2">
    <designator>M13</designator>
    <pin>M13</pin>
    <stamp_name>Cage_SFP_back</stamp_name>
    <package_name>M13</package_name>
    <errortype>9</errortype>
    <error_contents></error_contents>
    <pcb_no></pcb_no>
    <feeder_no></feeder_no>
    <pos_x>10962</pos_x>
    <pos_y>14090</pos_y>
    <window>64</window>
    <ng_message>Mismatch13%</ng_message>
    <comment>Mismatch13%(-0.14 -0.07){Cage_SFP_back}</comment>
    <ng_image></ng_image>
    </error_no>
]]

I want to capture n strings, each between "<error_no name="i">"and "</error_no>" My code is below, but results is nil for each i

for i = 1, n do
errindex1[i] = '<error_no name='..'"'..i..'"'..'>'
stringg = errindex[i]
texterr[i] = string.match(texterrors,"..stringg..(%a)</error_no>")

How is possible to use variable string like stringg as pattern?

Use Service / providers in models wit ionic3/Angular4

I want to do this question for people who have more experience than me to know if my planning is right or not.

We are going to suppouse we are develping and Ionic3-Angular app where we have a CRUD for "Clientes". I have read that right way is:

  • Cliente Model: Class where I define attributes.
  • Cliente Service / Provider: It will manage database communication getting, modifing and saving data.
  • Page: Where I call load datad and show.

All examples I found should be:

  • They instance model Cliente in Page.
  • They inject Service / Provider Cliente in Page.

To load data:

  • From Page they load data throw Provider and it assign data to an object (type CLiente).

Now I'm going tolaunch my doubt. Could be better implement data access and manage directly in Model?. I have done small projects with this but I can found any example where people do this and may I'm in a mistake. I mean:

For exmple I'll have a Client Class with these methods:

static load(cs:ClienteService,id):Cliente{
//function that receive provider and use it to access data with the other parameter (id of the Cliente)
}

guardar(cs:ClienteService):boolean{
// function to save object throw the ClienteService parameter
}

ClienteServicio will be injected in Page and will be passed to Model as parameter function if necesary. By this way logic, check data, etc.. will be manage at Model.

I hope I explained it and get advice from community. Thanks so much

Implications of naming the interfaces like the implementations

I would like to ask you, what are the positive and negative implications of naming the interfaces like the implementations, but storing them in interface-specific folders, like Contract (see Option 2).

Thank you for your time.


Option 1:

enter image description here

tests/Model/Entity/UsersInterface.php

<?php

namespace Test\Model\Entity;

use Test\Model\Entity\UserInterface;

interface UsersInterface {

    public function remove(UserInterface $user);
}

tests/Model/Entity/Users.php

<?php

namespace Test\Model\Entity;

use Test\Model\Entity\UserInterface;
use Test\Model\Entity\UsersInterface;

class Users implements UsersInterface {

    private $users = [];

    public function remove(UserInterface $user) {
        //...
    }

}


Option 2 (desirable):

enter image description here

tests/Model/Contract/Entity/Users.php

<?php

namespace Test\Model\Contract\Entity;

use Test\Model\Contract\Entity\User;

interface Users {

    public function remove(User $user);
}

tests/Model/Entity/Users.php

<?php

namespace Test\Model\Entity;

use Test\Model\Contract\Entity;

class Users implements Entity\Users {

    private $users = [];

    public function remove(Entity\User $user) {
        //...
    }

}

What is the proper way to implement the Repository Pattern ? and How to use it ?

I have an object called Product and I want to retrieve the "Bill Of Material" for a certain product from the list of all products (stored in SQL Server). Should I first create the Product object then get the data from my repository thru a method, like this:

var productId = "1";
Product product = new Product(productId);
DataTable billOfMaterial = product.GetBillOfMaterial();

OR retrieve the data strait from a static Repository, like this:

var productId = "1";
DataTable billOfMaterial = product.GetBillOfMaterial(productId);

OR maybe like this?

var productId = "1";
DataTable BillOfMaterial = ProductRepository.GetBillOfMaterial(productId);

OR maybe when I create the Product I automatically get the Bill in the constructor of the product:

var productId = "1";
Product product = new Product(productId);
DataGrid.DataSource = product.BillOfMaterial;

I am using the MVP pattern, and don't know if it is best practice to fill object just to get the DataTable or if I can just quickly use a static repository. What is the correct way to do it?

JPA Clean Architecture

im Refactoring a Microservice according to Clean Architecture:

enter image description here

Frameworks should be at the utmost layer. So i used the Adapter Pattern and Dependency Inversion to put org.springframework.data.repository.CrudRepository at the utmost layer. But how can i use @Entity (from Java Persistence API) to persist my Entitys if Entites are in the center and Frameworks are at the utmost layer?


Example: Demo-Entity:

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;

@Entity
public class Demo implements Serializable {
    @Id
    @GeneratedValue
    private long id;
    
    @NotNull
    private String foo;

}

GenericRepostioryInterface (in the Usecase Layer)

public interface CrudRepositoryInterface<S,T> {
    public <U extends S> U save(U u) ;    
    public <U extends S> Iterable<U> saveAll(Iterable<U> itrbl) ;    
    public Optional<S> findById(T id) ;    
    public boolean existsById(T id) ;    
    public Iterable<S> findAll() ;    
    public Iterable<S> findAllById(Iterable<T> itrbl) ;    
    public long count() ;    
    public void deleteById(T id) ;    
    public void delete(S t);    
    public void deleteAll(Iterable<? extends S> itrbl) ;    
    public void deleteAll() ;  
}

Some usecase:

    @Autowired
    private CrudRepositoryInterface<Demo,Long> demoRepository;
    ...
    
    private void deleteAll(){
      this.demoRepository.deleteAll();
    }
    ...

Adapter (DB Layer)

public interface DemoRepositoryAdapter extends CrudRepository<Demo,Long>,CrudRepositoryInterface<Demo,Long>{    
}

Config for Injection (i put that in the DB Package/Layer aswell)

@Configuration
public class InjectRepositoryConfig {    
    @Bean
    public CrudRepositoryInterface<Demo,Long> animalOwnerRepository(@Autowired DemoRepositoryAdapter demoRepositoryAdapter){
        return demoRepositoryAdapter;
    }
}

this Works fine so far but im unsure how to remove / replace / refactor JPA out of the core layer?

Thanks in advance

Have background of div extend to sides of the page

My website's basic structure is provided by a .page-container class, attributed to the main container elements. The class sets width, max-width and margin: auto; properties so as to have all the content tidy, centred and aligned.

Inside the .page-container elements, further subdivisions are made, as you can see from this Fiddle and the image below.

Basic website structure

I would like to add a background to the text part – the <article> with the .content class in the Fiddle –, that extends to the upper, lower and right part of the screen.

I would like to do this maintaining the current architecture as much as possible and without adding unmeaningful elements, obtaining something like the image below. Is it possible? Shall I rethink my architecture? Was my design pattern good in the first place?

Desired result

Step by step pattern with data transfer between steps

I write simple application which consists of several step. Each step takes its specified input data and produces its specified output. I try to realize such pattern based on pipeline pattern. There are common parts: Interface that each step must realize:

interface IStep
{
    Data Execute(Data data);
}

Interface that must be implemented by class that processes steps:

interface IProcess
{
    void AddStep(IStep step);
    void Run();
}
class Process: IProcess
{
    private List<IStep> steps = new List<IStep>();

    public void AddStep(IStep step)
    {
        steps.Add(step);
    }

    public void Run()
    {
        var data = new Data();
        foreach(step in steps)
        {
            data = step.Ececute(data);
        }
    }
}

Implementation of Data class is the next:

public class Data: Dictionary<string, object> {}

And this is a problem. I have to store key constants for Data and in the beggining of each step extract values required by step. Is there more elegant way to implement such approach?

samedi 29 septembre 2018

User Interface for filtering objects in Python

In my application I have a Job class as defined/outlined below. Instance of this job class represents a particular Job run, Job can have multiple checkpoints and each checkpoint can have multiple commands.

Job
 - JobName
 - [JobCheckpoint]
 - StartTime
 - EndTime
 - Status
 - ...

JobCheckpoint
 - JobCheckpointName
 - [JobCommand]
 - StartTime
 - EndTime
 - Status
 - ...

JobCommand
 - JobCommandName
 - [Command]
 - StartTime
 - EndTime
 - Status 
 - ...

At any given day there are like 100k different jobs that runs. I want to design a user interface in Python for querying these job objects. For example users want to query

  1. Jobs that ran between x and y interval.
  2. Jobs that run command x
  3. Jobs in failed state.
  4. All checkpoints/commands of a particular job.
  5. And many more...

To solve this, I was thinking of providing following methods in user interface.

  1. dict getJobs(Filter)
  2. dict getCommands(Job)
  3. dict getCheckpoints(Job)

I am not sure

  1. How Filter class will look like?
  2. Is returning dict correct or should I return proper Job object?
  3. Should I take dict as an input or defined classes as an input.
  4. Whether this is a best design.

Dynamic "pipes and filters" or "decorator"

I'm currently working on a project, where I need to route incoming requests to a specific target. There are multiple attributes the requests have, that need to be combined to select the correct target and execute the correct manipulations on the request. e.g. a request of user 1 needs to be routed to our test environment while user 2 needs to be routed to the integration environment...

There are also some more complex conditions like. All requests of user 2 need to be routed to int but the requests to one specific part of the application should actually be routed to the test environment.

My first approach was based on the wording the customer used and the architect of the project wanted to have a more generic approach. We designed together an alternative using 2 types of "filters". Each filter has a name and when executed returns the name of the filter, that should be executed next. Also each filter has gets a map (key-value-pairs) as an input which it uses to read from or write to. The first type of filter allows branching, based on one or multiple keys from the map (basically a switch-case-statement). The second filter reads in a value from the map (optional), selects some information from the value using regex (optional), defines an output-format or value and assigns the result to a key in the map. This filter can have multiple of those actions.

Those filters can be defined in a database and are loaded and stored, so that a controller can easily find them by name. When the controller receives a new request it extracts the key-value-pairs to the map and executes the first filter. Then it executes the filter returned by the previous filter until it gets no filtername to execute next.

I'm not sure if there is an official pattern or best practices of an approach like the one designed by the project's architect and me and I didn't find one. So I wanted to ask for some input on that topic.

Thanks in advance.

what is the name of design pattern illustrated in this code?

from the code below, is this an exemple of prototype design pattern ?

As I noticed, it is kind of returning instances of an already created items.

Thank you in advance.

enter image description here

html5 pattren to accept arabic and english character with space?

I have tried this pattern but not working

pattern="[A-Za-zا-ی\s]*"

Implementing a Factory Pattern in C#

I am implementing a factory pattern and would like to get it confirmed that it is the right approach. Is there any error in this approach. If so where should i be making the changes.

First I am creating an interface IAuto.

 //IAuto.cs
    namespace TestDesignPatterns.Auto
    {
        public interface IAuto
        {

            void start();
            void stop();
        }
    }

Create a class that implements the IAuto.

    //clsBMW.cs
    namespace TestDesignPatterns.Auto
    {
        public class clsBMW : IAuto
        {
            public void start()
            {
                Console.WriteLine("BMW started");
            }

            public void stop()
            {
                Console.WriteLine("BMW stopped");
            }
        }
    }

Create another concrete class for Audi implementing IAuto.

namespace TestDesignPatterns.Auto
{
    public class clsAudi : IAuto
    {
        public void start()
        {
            Console.WriteLine("Audi started");
        }

        public void stop()
        {
            Console.WriteLine("Audi stopped");
        }
    }
}

Create an Interface of factory which creates the model.

//IautoFactory.cs
public interface IAutoFactory
    {
       IAuto createModel(ModelType m);
    }

concrete factory class.

//clsAutofactory.cs
 public class clsAutoFactory : IAutoFactory
    {
        public IAuto createModel(ModelType m)
        {
            IAuto instance = null;
            switch (Convert.ToInt32(m))
            {
                case 0:
                    instance = new clsBMW();
                    break;

                case 1:
                   instance =  new clsAudi();
                    break;
                default:
                    break;


            }

            return instance;
        }
    }

Main Program

//program.cs

            IAutoFactory factory = new clsAutoFactory();
            IAuto model = factory.createModel(ModelType.Audi);
            model.start();
            model.stop();
            Console.ReadKey()

Single Instance of Application Service in DDD Approach

As I have learned about Application Service layer, it must be stateless i.e. it shouldn't store any dynamic data in properties or fields. So different instances of Application Service would do almost the same thing. So does it mean we may implement it as a static class or using singleton pattern?

vendredi 28 septembre 2018

For loop iteration increament value by 1.why?

why k value is one increment when it should stop to 1 in first iteration and 3 in second iteration and so on?

enter image description here

What Design pattern is this peudocode for?

In an interview I was asked this quistion :

X a = new X("param");
Y b = new Y(a);
Z c = new Z(b);

I was thinking about Creational DP : AbstractFactory but I am not so sure.

So what DP is this code ?

Thank you

Need help defining software design proposal

I am having trouble defining a software design proposal - I have been calling it "Rules Based Design" but when I look that up it doesn't really match what I am doing. So I want to know if the following already exists as a design pattern and if so which one or at least which one comes closest to what I am doing.

Essentially what I am proposing is creating a collection of small Java classes that perform business functions in an atomic manner. Then I create two tables Rule Set that is a collection of identifiers and filters that point to what I call Rules in another table. The Rules table is mostly just a FQCN that will be created via Java reflection to act on business data to perform the function defined in the filter table.

Let me give a very basic example:

Say I have a system that manages membership in multiple programs here is what the filter and rule table would look like for the "APPLY" function:

Rule Set

Function    Program    Rule    Order
===========================================
Apply       All        1       1 
Apply       PGM1       2       2 


Rule

Rule    Name               FQCN
=========================================================
1       Duplicate Check    com.rule.all.DuplicateCheck 
2       PGM1 Eligibility   com.rule.PGM1.EligiblityCheck 

So when someone is on the "Apply for Membership" screen - which his the same screen for all programs - they select the program and I go to the Rule Set table looking for all Rules for the APPLY function that are for ALL programs or the specified program.

Then I loop through these FQCN creating an instance and passing a map of parameters captured on the APPLY screen. If no exception is thrown I move on to the next rule.

If I get through all the rules with no exceptions I move to the next screen.

Basic Information to starting the project

I have an startup project that I want to create that using Asp.Net core But many things are cause that be confused, there are:

  1. What is ORM to use?
  2. What architecture should I use? (like N-Tire,MVC or something like that)
  3. What Common Design-Pattern should I use?
  4. What Unit-Testing should I use?
  5. What to use for the client?(like Angular,react,...)
  6. What Software Engineering Methodology should I use?
  7. Is selecting these things to improve the progress of the project?

And I have big Idea for this project, if I want to preventing data loss, what should I do? how do I go?

I would appreciate if anyone can help.

API Gateway + Keycloak

i have 5 Microservices (Java Spring) a Keycloak Server and a RabbitMQ Server all deployed via Docker. I want to start using a API Gateway to have the same baseadress for all MS:

demo.com/api/ms1/
demo.com/api/ms2/
...

But im a bit overwhelmed. What would you guys recommend? What is the easiest most begginer friendly solution to use?

thanks

jeudi 27 septembre 2018

Looking for presentation about coding, interfaces

Some woman was talking that no one will ever use your interface. And why do people sign their classes.

Is it true that If Bridge Pattern is used as structural pattern then Strategy Pattern is used by default?

There are a lot of questions on SO comparing Bridge pattern and Strategy pattern. Explanations include

Bridge is structural and Strategy is behavioral

and

UML and code look similar but the intent is different

among other less common ones.

None of those explanations I've come across here or elsewhere is satisfactory. I clearly know when I am using the Strategy pattern and Bridge pattern because of my intention and the problem I need to solve but from a distance, the distinction gets blurred. Thus, this question keeps my mind busy time to time.

If I use the Bridge pattern when modeling the structure of the components, doesn't it become Strategy pattern in runtime, naturally?

Java: How cast an Object to another Object with the same attributes using design pattern? without libraries

I´ve two POJO´s in Java, Movie to use in my database and other Movie to use like result from request to webservice.

package .database
public class Movie{
 private String title;
 private String year;
 private String poster
}

package .service
public class Movie{
  private String title;
  private String year;
  private String poster;
}

I´ve solve this, create a class that do the cast.

 public class MovieObjectAdapter {
    public static List<service.Movie> castFrom(List<database.Movie>moviesDatabase){
        List<service.Movie> moviesModel = new ArrayList<>();
        for (database.Movie movie:
             moviesDatabase) {
            service.Movie movieModel = new service.Movie();
            movieModel.setTitle(movie.getTitle());
            movieModel.setPoster(movie.getPoster());
            movieModel.setYear(movie.getYear());
            moviesModel.add(movieModel);
        }
        return moviesModel;
    }
}

But i´m not very happy with this. So Which design pattern can you recommend me to use?

How to Design classes in OOPS way to respond to search query with complex filter

We have search query with Complex search criteria. To serve this request, lot of data(modeled as multiple in memory POCOs , some data gathered from External Rest Services, Some data queried from DB) need to be queried and then business logic needs to be applied on top of this data. Current solution uses Manager class to gather data from all these sources and feeds it to Domain Model :that has methods to act upon data and perform filter operations. But Manager class method is having around quite lot of code to get data from multiple sources (around 15 calls ) and then set the data in Domain model and then call Domain model methods to act upon it. This makes it look dirty and procedural. Can anyone suggest more cleaner approach/ pattern to use.

What is the best architecture pattern that changed the way of software development?

I am new to Software development, I want to know what Architecture pattern/style that changed the way of software development or design?

Which design pattern to use to replace if condition in the c# code

Need to remove the if statement for the new instances , kindly suggest which design pattern to use. No case statement please

public ITrialBalance GetTrialBalanceReport(string param1, int param2) {

        if (param2 == 1)
            return new TrialBalanceReport().GetTrialBalanceLevel2(param1, param2);
        else
            return new TrialBalanceReport().GetTrialBalanceLevel2(param1, param2);
    }

Thanks

mercredi 26 septembre 2018

Using interfaces for ViewModels?

I am currently integrating architecture components into my app according to the official documentation and the sample apps provided by google (sunflower and todo-app). I realized that none of these use interfaces for ViewModels (the sunflower app does not even use interfaces for repositories).

My question is: is it reasonable to just omit the interfaces for ViewModels (including advantages and disadvantages)?

Pattern for large hash creation?

I'm working on filling a large (155 fields) PDF using pdftk, and I find myself creating a massive Hash with the PDF's field names, and the values to be filled in.

For my specific implementation, I'm using Ruby, and have a PdfJob object which collects all of the data from a model object into a hash, and passes that hash into a wrapper around pdftk stored in $PDFTK.

class PdfJob
  def perform(model)
    $PDFTK.fill_form('path/to/fillable.pdf', Tempfile.new, Fields.call(model))
  end

  private

  class Fields
    def self.call(model)
      {
        OWNER_NAME: "#{model.first_name} #{model.last_name}",
        TOTAL_PRICE: calculate_total_price(model),
        FOO: 'bar',
        # 152 more lines of key/value pairs.
      }
    end

    def self.calculate_total_price(model)
      # Most of these methods are multi-line.
      model.item_relations.sum(&:price)
    end

    # about 50 more class methods to simplify assignment in #call()
  end
end

This is a heavily-simplified example, but I think it illustrates where I've found myself.

What I'm looking for is a design pattern or some other way to break up this hash into multiple classes, methods, or some other unit so I don't end up with a Fields class with nearly 250 lines of near-untestable key/value pairs and helper methods.

conditional ifs for multiple return cases

I have the following condition a class and a method

public class ReturnParameter
   {
      public string v1 {get; set;} 
      public string v2 {get; set;} 
      public string v3 {get; set;} 
   }


  public string RideCombination(ReturnParameter retor)
  {
     var v1 =  retor.v1;
     var v2 =  retor.v2;
     var v3 =  retor.v3;


     // case 1
     if(v1 == "A" && v2 == "b" && v3 == "C" ) 
       return  "valid 1 "

     // case 2
     if(v1 == "C" && v2 == "A" && v3 == "C" ) 
       return  "valid 2 "

    // case 3
     if(v1 == "D" && v2 == "T" && v3 == "C" ) 
       return  "valid 3 "

   // case 4
     if(v1 == "A" && v2 == "B" && v3 == "C" ) 
       return  "valid 4 "

  }

suppose I have 20 conditions I will have to 20 ifs to return 20 different combinations, is there any way I can eliminate multiple conditions without having to do one by one?

CDI Interceptor vs CDI events

I have a question about the best implementation to have a system in java EE that is as uncoupled as possible, the question is whether it is better to use CDI events or CDI interceptors, obviously for things like security would be an interceptor, for logs for example any of the two according to the specific case, but for business rules in which a certain task must be done while another is executed.

Leaving aside that asynchronous events may or may not occur, my doubt is more in favor of the decoupling of modules, since for my concept the events are more decoupled than the interceptors, since in the interceptor the class that contains the function must be defined intercept, but in the case of events only the message must be defined.

Custom class working like a using statement with curly braces

Is it possible to create a class, or operator, that would work like using does?

Example:

using (IDataReader reader = cmd.ExecuteReader())
{
  while (reader.Read())
  {
    count++;
  }
}

Often we use the using statement to not have to handle post operations manually, like dispose and such.

I have in mind a couple of usage of this mechanic.
But I cannot figure out how to achieve this.

An example of actual implementation:

  MyClass mc = new MyClass();
  MyClass sub = mc.GoDown();
  //Do things on sub
  sub.GoUp();

What I would like it to be:

  MyClass mc = new MyClass();
  mc.GoDown {
    //Do things on sub
  } // GoUp

I know I could use a try {} finally {}. I am just curious if there is a way to do what using is doing.

Edit: I do know about the IDispose implementation. I am just wondering if we can do what using does without using.

Edit #2: Improved the example.

Should i use a pattern

So I'm receiving a string from twitch irc and based on that command I execute some code. The question is can i simplify my code or use a pattern. You can see the code below. It looks very messy and adding new commands or functionality will probably be a pain(if I have 200 or more commands).

public void onCommand(User user, Channel channel, String command)
    {

        // some if statements 

        switch (command.toLowerCase()){
        case "hi":{

            //some simple action
        }
        case "fire":{

            vote(60, channel, "fire")
        }
        ...

        //timeout
    }

    void vote(int duration, final Channel channel, String voteFor){
        Timer timer = new Timer();

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                //start voting
            }, duration);

            switch (voteFor){
                case "fire":{
                    if (voteYes > voteNo) {
                        //some action
                    }else
                        //some action
                    break;
                }
                ...
    }  

P.S I tried using the strategy pattern but it felt like there is no need for it.

In which layer should the validations be done mainly in the context of DDD?

This question might be asked a thousand of times but a lot of confusions and contradictions in the answers.

I ask about the validations in the context of domain driven design.

  1. In which layer should the validations be done mainly ?
  2. Is it acceptable for the object to be in invalid state? because many answers said that it's okay and mainly because of historical data and the business rules may change over time and loading historical data might cause problems?
  3. Many implementations consider throwing exceptions in the domain layer and mapping the messages to the UI although Martin Fowler recommends to Replacing Throwing Exceptions with Notification in Validations! When to return messages and when to throw exceptions in the validation context ?
  4. Many articles explain some tips or paths to follow like Vladimir Khorikov and jbogard in their articles but in the comments they confess that they do things a wee differently now. Are these patterns still valid?

  5. Should I use framework like FluentValidation and if I use it, Is this frame work used only in the application layer as an alternative to the MVC annotations ?

  6. When Should I use Business Rule Framework (BRF) instead?

I know many questions here but they are targets the same spot(Validation in DDD).

Note: I don't use CQRS pattern because it made the application so complex. So I have (domain layer,data layer, application layer(MVC), and shared kernel)

How pass any type of class inside my Aspect, then cast the jointpoint object to it

I have a spring AOP interceptor annotation on my API level below:

  @ETISLog(etisModule = EtisModules.SYSAD, etisSubmodule = EtisSubmodules.MAINTENANCE,
      logEvent = LogEvent.CREATE)
  @RequestMapping(method = RequestMethod.POST)
  public ResponseEntity<MaintApplicationType> save(
      @RequestBody MaintApplicationType maintApplicationType) {
    LOGGER.info("API: SAVE {}", maintApplicationType);

    return new ResponseEntity<>(maintApplicationTypeService.save(maintApplicationType),
        HttpStatus.CREATED);
  }

Below is my around method inside my Aspect class: I cast the intercepted object from the jointpoint to a specific class type

public Object auditLogAround(ProceedingJoinPoint joinPoint, ETISLog etisLog)
      throws Throwable {
    LOGGER.info("INTERCEPTING REFERENCE SERVICE...");
    Object interceptedObject = new Object();

      if (LogEvent.CREATE.equals(etisLog.logEvent())) {

        interceptedObject = joinPoint.proceed();

      ResponseEntity<MaintApplicationType> httpResponseReference = (ResponseEntity<MaintApplicationType>) interceptedObject;


      MaintApplicationType referenceData = httpResponseReference.getBody();
        auditMainDetails.setUsername(referenceData.getCreatedBy());
 }
}

The code above works fine, but it has limitation, it only works for MaintApplicationType Entity. If i intercept another API level of another Entity i get ClassCastException here:

ResponseEntity<MaintApplicationType> httpResponseReference = (ResponseEntity<MaintApplicationType>) interceptedObject;

How can i make my auditLogAround method flexible enough to accept any class type to intercept.

I created an ENUM below but dont know how to implement this.

public enum MaintenanceTypeEnum {

  ACCREDITED_PRINTER, ALPHANUMERIC_TAX_CODE, APPLICATION_TYPE, ATTACHMENT_TYPE,
  AUTHORIZATION_TYPE, BARANGAY, BOOK_OF_ACCOUNT, CASE_EVENT, CASE_TYPE, CITY_MUNICIPALITY,
  COUNTRY, FORM_TYPE, IDENTIFIER_TYPE, INCENTIVE_CLASSIFICATION
}

How to assign abstract object to Reflection.Emit derived one

Hello i am facing the following problem:

I have an abstract class which has to be somehow initialized before i can call one of its async methods in which its fields are assigned:

class Dependency {}

abstract class Relay : Abs.Api.IAll {

        private Dependency dep;

        public static async Task<Relay> RunAsync(Dependency _dep) {
            Relay daemon = // [ Reflection.Emit derived object]
            await daemon.InternalConnectAsync(port);
            return daemon;
        }
        private async Task InternalConnectAsync(Dependency _dep) {
            //async code//
            this.dep=_dep;
        }
    }
class AutoGeneratedRelay : Relay {
}

As you can see the Dependency object dep is initialized after i have a concrete object derived from Relay.
The problem is that this object daemon will be assigned to a derived object obtained via Reflection.Emit ,in our case AutoGeneratedRelay.I am creating a derived class with reflection and i want to fetch it and assign the base object daemon.

How to execute common code before and after another function in c?

here I explain the problem. Suppose I have a struct A loaded in shared memory. The struct A might be something like this:

typedef enum{
    GPIO_1,
    GPIO_2,
    GPIO_3,
    GPIO_4,
    GPIO_5,
    N_GPIO
} gpio;

struct B {
    bool active;
    bool status;
    bool direction;
    int timestamp;
    int t1;
    int t2;
};

struct A {
    struct B gpio[N_GPIO];
};

Also suppose I have two functions which would operate on one of the B structs in A:

bool set_status(gpio g, bool status, int t1, int t2);
bool activate(gpio g, bool active);

Since A is loaded in shared memory, I need to call shmget and shmdt within the two functions above; the pseudocode for the first function should be something like this:

bool set_status(gpio g, bool status, int t1, int t2) {
    struct A shm = shmget();
    struct B target = shm.gpio[g];
    if(target.active) {
        bool res = foo1(target, status, t1, t2); //do something on struct B indexed by g
        shmdt();
        return res;
    else 
        return false;
}

The pseudocode for the second function should be something like this:

bool activate(gpio g, bool active) {
    struct A shm = shmget();
    struct B target = shm.gpio[g];
    if(target.active) {
        bool res = foo2(target, active); //do something on struct B indexed by g
        shmdt();
        return res;
    else
        return false;
}

Now, is there a way I can prevent to have that common code which manages shm and checks if B.active is set? To me, this looks something like decorators, i.e. have a function that manages shm, checks for B.active and calls a second function within it, but the problem is that that the second function might has not a unique signature (might have different number of parameters).

Thanks!

Implement a functional processing pipeline with compile-time order constraints

Let's say we have a data object X and some "processor" objects/methods A, B, C and D. A(X) produces a new X with some additional data (the result of A processing). B(X) produces a new X with some other additional data. C(X) also produces a new X with some additional data but it requires that A has already been ran against X. So: A(X).B(X).C(X).D(X) should run properly. B(X).D(X).A(X).C(X) should also run properly. B(X).C(X).A(X).D(X) should fail (because C requires the info A produces).

Is this possible to implement in C# so that the order constraints are enforced in compile time? If not, is there a design pattern or some common strategy of how this should be implemented? There can be many processors and many constraints, what I'd like to avoid is having to declare a factorial number of types to keep track of whether a processor has been ran or not.

mardi 25 septembre 2018

Handling overlapping asynchronous POST requests

We have implemented How to Use POST for Asynchronous Tasks in our project for long running tasks.

My question is how we can handle the case wherein we have multiple POST requests issued back-to-back from the same client. In this case, only the last POST request is what the client really is interested in. When a POST triggers a background thread, a subsequent POST also tries to trigger another background thread.

This effectively means that apart from the last POST request, the others result in wasteful computation

Are there any design patterns to address this?

What design pattern bootstrap v4 uses on the click event

Here is a snippet I am trying to figure out

$(document).on(
Event.CLICK_DATA_API,
Selector.DISMISS,
Alert._handleDismiss(new Alert()) )

This snippet is part of the Alert component:

https://github.com/twbs/bootstrap/blob/v4-dev/js/src/alert.js

I am trying to understand why on a click event we are trying to pass a new Alert() rather than just an instance of or let the event.target do the heavy lifting on the listener.

Is it a bad practice to set dependencies to NULL in a IoC container and supply the dependencies at runtime?

I have a SocketManagerclass that contains a Socket and other fields. All fields except the Socketcan be injected during the composition of the object graph with a DI framework. My idea was to simply build the entire object graph upfront by leaving Socket empty and set it during runtime. This would allow me to complete the SocketManager instantiation at one point in the code and use that instance throughout my entire program (as it was already set as an dependency through the DI framework)? Is that the standard way to "inject" runtime dependencies or is it bad practice?
A abstract factory seems to be a bad idea for two reasons: a) it creates a different object everytime b) It requires the runtime parameters at every place where I want to create the object

problem to create pattern like minesweeper with C#

first at all, i'm new at C#, so, I apologize if I ask something somewhat "so newbie". Well, here the thing:

I'm trying to create a pattern, just like the game: Minesweeper 'cause i'm making a simple game, a chess game, so my big problem right now is that i can't create the columns efficiently, so, here's my code:

class chessGame
{
    static void Main(string[] args)
    {
        const string EX = "X";
        const string OU = "O";
        const int VALUE_X = 8;

        int numRows = 0;
        int numCol = 0;

        while (numRows < VALUE_X)
        {
            for (numCol = 0; numCol < VALUE_X; numCol++)
            {
                Console.WriteLine(OU);
            }
            for (numRows = 0; numRows < numCol; numRows++)
            {
                Console.WriteLine(EX);
            }
            Console.WriteLine();
        }
        Console.ReadLine();
    }
}

also, i don't know at all if that's the way create the columns and rows with that nested loop, so, if someone can help me with this, or just someone can help me to do it right with my actual code, thank you so much!

and for the record, here's what i see in the console right now:

enter image description here

beforehand, thank you for your advices to all of you guys!

handling of communication between Application and Domain layers in DDD

I'm trying for the first time to implement DDD to build an application. I have decided to land my little knowledge on the code to generate a structure that I like and keep clean, for the implementation I have started with the context of user management (authentication, registration, password recovery, password change, etc).

To expose my doubt I will take as an example the case in which a user authenticates in the application using his mail and his password.

For that case, the basic responses are:

  • Correct authentication, must return the authenticated user's data.
  • Incorrect authentication, the email entered does not exist.
  • Incorrect authentication, the password entered is not correct.

To make this case, I created an application service called LogInUserWithEmailService. This uses a domain service called AuthenticationService that knows how to authenticate a user as the case may be.

Therefore in my application layer I have a LogInUserWithEmailService that receives a DTO with the request, then I call AuthenticationService that is inside my domain layer and he is the one who does the management.

In reaching this situation I have encountered a problem, I need my authentication service can return user data or error messages as appropriate. In addition to communicating errors of internal validation of the fields, such as the length of the password, that the email is a valid email, etc.

To get out of that problem, I opted for the simple, return the user if it is correct and send it out in the form of DTO from the application layer. And throw specific exceptions for each error, which I catch in the application layer and add the more natural message next to a code to throw it out.

The problem is that you should not be throwing exceptions for those cases. And I do not know in what way I should communicate the answer to my application layer. I thought I could do it using simple DTO to pass the data between layers, but I do not think it is correct since a UserDTO is not something belonging to the domain, so my domain should know nothing about any DTO, although it may be wrong in this point.

So, what would be a correct or effective way to do this? And coming from the same topic, should my domain service receive as parameter a request object, primitive types or value objects of that data (do I have value objects of password and email?

Awk printing specific variable & original data together between the pattern

original data and desired output

Hello,

I want to get specific variable values between Patterns and print ( REF_ID value, C_ID value and Date-Time infront of it.

you can see Original data & Desired output below:

+--------+--------+-----+   +-------+--------+---+---+--------+--------+-----+
|        BEFORE         |   |                     AFTER  
+--------+--------+-----+    +-------+--------+---+---+--------+--------+-----+
| [2018  | 13:50] | ALI |    | [2018 | 13:50] | X | Y | [2018  | 13:50] | ALI |
| REF_ID | X      |     |    | [2018 | 13:50] | X | Y | REF_ID | X      |     |
| A      | 3      |     |    | [2018 | 13:50] | X | Y | A      | 3      |     |
| C_ID   | Y      |     |    | [2018 | 13:50] | X | Y | C_ID   | Y      |     |
| B      | 4      |     |    | [2018 | 13:50] | X | Y | B      | 4      |     |
| [2018  | 14:00] | ALI |    | [2018 | 14:00] | Z | T | [2018  | 14:00] | ALI |
| C      | 3      |     |    | [2018 | 14:00] | Z | T | C      | 3      |     |
| REF_ID | Z      |     |    | [2018 | 14:00] | Z | T | REF_ID | Z      |     |
| D      | 1      |     |    | [2018 | 14:00] | Z | T | D      | 1      |     |
| E      | 4      |     |    | [2018 | 14:00] | Z | T | E      | 4      |     |
| C_ID   | T      |     |    | [2018 | 14:00] | Z | T | C_ID   | T      |     |
+--------+--------+-----+    +-------+--------+---+---+--------+--------+-----+

I have tried the following but it does not work as i desired.

awk '
BEGIN {FS=" "}
{if ($0 ~ /\[2018/) {flag=1;date_ref=$1;time_ref=$2;}            }
{if ($0 ~ /REF_ID/ ) {t_ref=$2}                   }
{if ($0 ~ /C_ID/ ) {gcid_ref=$2}        }
{if (flag=1) print date_ref,time_ref,t_ref,gcid_ref,$0}
'

to solve the problem i believe have to put the data to buffer , collect the variable and merge it..

could you please help me to solve this problem? If you can explain the code you provide it would be much helpful.

Is there a way to specify "type of current class" in a C# method signature?

I'm trying to define an abstract class which other classes will extend, and they have to be able to serialize themselves to JSON and deserialize from JSON. I want to write the abstract class something like this:

public abstract class BaseApiModel {
    public abstract string ToJson();
    public abstract T FromJson(string json);
}

... where T is the type of the current class. I would then write an extending class like this:

public class ContactApiModel : BaseApiModel {
    public string ContactName { get; set; }
    [...other properties...]

    public override string ToJson() {
        [...return serialized JSON string...]
    }

    public override ContactApiModel FromJson(string json) {
        [...return deserialized object...]
    }
}

Of course this doesn't work because T in the abstract class isn't defined. But is there some way I can write "this method has to return the type of the current class" in C#? Do I just going to have to make it return object? Or am I approaching this wrong and there's a better way to structure it?

Using a Manager to manage game object lifetime

I have a lot of hint arrow requirements in my game. So far, i have a hint arrow manager, that checks the arrows kill condition, and destroys it if the kill condition is satisfied. The manager has an update function linked to the games update.

Is it okay practice to manage lifetime from the Manager?

Pseudo code example of my system:

HintArrowFactory:createHintArrow(target, angle, priorityEnum)
                :addKillCondition(time, function(obj, deltaTime) obj.time -= deltaTime))

Function definitions:

HintArrowFactory HintArrowFactory:CreateHintArrow(target, angle, priorityEnum)
HintArrowFactory HintArrowFactory:AddKillCondition(HintArrowAdditionalParams, KillConditionFunc)
bool KillConditionFunc(HintArrowObj, deltaTime)

Another approach would be to handle lifetime explicitly in the code: No inpure kill conditions, but possibly some extra strain when coding.

hint = createHint()
delayedDestroy(hint)

What would be advantages/disatvantages of either approach?

P.S

Using timing kill condition and delayed destroy is done just for convenience. Another example specific for my game would be destroy with message box. so the difference would be that in the first case i would send isMessageBoxActive kill condition, and in the second case i would have to make another update function to monitor msgbox activity and then destroy the arrow - destroyWithMessageBox(hintArrow).

Divide one external request into multiple internal ones and redirect to the specific handlers

I have soap service with 2 methods:

SendRequestReques and GetRequestResponse

In each method I receive wrapped request with internal request(8 types of internal request). This may look like:

public SendRequestResponse sendRequest(SendRequestRequest request){

    if(request.getInternalrequestType().equals("RequestFirst"))
      RequestFirst requestFirst = marshaller.marsla(request.getInteRnalrequest());
      //send this reuest to concrete handler
    } else if(request.getInternalRequestType().equals("RequestSecond"))
      RequestSecond requestSecond= marshaller.marsla(request.getInternalrequest());
      //send this reuest to concrete handler
    } else if(request.getInternalrequestType().equals("RequestLast"))
      RequestLast requestLast= marshaller.marsla(request.getInternalRequest());
      //send this reuest to concrete handler
    }
   ...

I use strategy pattern:

InternalRequestHandler handler = internalrequestsResolver.getInternalRequestHandler(request.getInternalrequestType())
handler.process(request);

And in each handler implement marshalind to concreate class and implemebt logic.

But now I want change it to annotations. I want create handlers for eacj internal request:

@MyHandler(type = MyType.TYPE1)
@Component
public class MyFirstController {
  ...
}

And when spring boot app started I want faind all beans with @MyHandler annotations and create esolver/factory/etc with this beans. So I still get the strategy pattern. but create a handlers when starting from the annotations. I do not know if this is a good idea, or not. but the question is how to do it. and the second question is how can you do otherwise?

if abstractly, then the logic is:

  1. Client send request like this:

    class ExternalRequest{ private Element any; //org.w3c.dom.Element contains any type }

  2. I get this request in my soap service in methode:

public ExternalResponse request(ExternalRequest external request)

  1. I extract type of internalRequest and InternalRequest by this type.

  2. I redirect internal request to specific handler.

Design Pattern - Is generic applicable?

Current classes

AMetric{ field1; field2.. etc }

AMetricGetter{

       AMetric getMetric(A aobject) 
       // A class contains same fields as AMetric class.                
       // Ametric class contains a few extra fields which are calculated in this method.
}

Now the problem is, a new class has to be created called BMetric which has a few fields similar to AMetric but is totally different type so no inheritance between them.

What i dont want to do is copy the whole code structure above for class B, as there is significant overlap here.

Class A and B also share some fields, but also have different fields, so theres no inheritance between them.

I thought of using generics

 getMetric(T tobject)

where tobject can either be class A or class B, but it doesnt help as some fields are specific to A or B, so i have to know the type of T in order to do transformation to AMetric or BMetric.

Any other design pattern?

How to pass variable between 2 java modules per-thread-context without overloading?

Good morning. I have 2 java modules. Let's call it module A and module B. A module is responsible for pure db interaction. B module is service layer. In B for example on some event which it receive starting flow(Let's imagine it's like step 1, step 2, ..) we creating a context and after some step it's using static method from module A and increment db counter if there is such record or add new.

Problem: In db to this table we need to add 1 more column, it's some id which we can only receive from Context. Each thread have their own context. The program working like: we receiving some event -> INIT(context is created) -> step 1(do smth) and call static method increment from module A The context is passed all over the steps in module B.

In A module there is a place where if i would have my id(which is different per each context) from B, it would work.

increment(Enum, id)

Enum(int id1, int id2, int id3). There is a base interface which each enum is implementing and in each enum class it's creating object and in flow used like increment(EnumRealisation.someObject, int id)

Issue

The obvious way is to overload this static increment in A and add this variable from context where increment is called, the problem is that there is like > 600 calls of this method and we can do this but this is the long way. I'm trying to find the solution that I would be able to keep, pass or autowire somehow my variable from context and retrieve it in module A. Guys, maybe you know some way how can I implement my issue? Or some library.

lundi 24 septembre 2018

How to parse query parameters in Java that works with all delimiters?

So according to this answer, it seems that any character can be used to separate query parameters in a URL.

Hence a regex matcher for & delimiter, such as the following, will fail when ; or | or something else is used for example:

private static final Pattern MATCHER = Pattern.compile("name=([^&#]*)");

So is there a GENERIC way of extracting query parameters from a URL, given that ANY valid delimiter could have been used in that URL ?

Serializing class object to prevent huge contructors inside code

If I have a class with a huge constructor, that independent of what happen will not change (but there will be multiple objects with different data) can I create one object, serialize it and just load the serialized object, instead of having a long chain of constant parameters in the code?

For example, imagine we have the class VeryLongClass, that has a constructor with 50+ parameters, that will not change, but there will be multiple instances of that class that are different between them, so the parameters are needed. Would be acceptable with I created a class instance and serialized it in a file let's say verylongclass1.dat and loaded it when the program started?

Depending on interfaces instead of framework services

For example I use SomeFramework which have mechanism to deal with controllers/actions. And I want to write MyService some methods of which depend on current action name.

Obviously I can do relation in MyService on MechanismInterface provided by SomeFramework.

But will it be better if I will create an interface ActionResolver and its implementation SomeFrameworkActionResolver?

SomeFrameworkActionResolver will depend on MechanismInterface, but MyService will depend on ActionResolver interface.

Problems in refactoring code / figuring out the design pattern to use

Chiranjeev Thomas shared a link. 2 hrs Issues in refactoring the code :

So , I had quite a few lines of code to be executed in the main method of the Application (Main) class of a java project . To get rid of all the clutter , I ended up refactoring it using the extract method refactoring technique , but then I got a lot of static methods in the Main class which I'm not a fan of .... What would be a better way to get a clean main Application method ? Should I use a singleton class perhaps ?What other design pattern / technique should I use to avoid having all these static methods in my main class and keeping the main method as succinct as possible ?

Initial Code :

import controller.Statistics;
import model.primary.customer.CustomerInfo;
import model.primary.movie.MovieInfo;
import model.primary.rating.RatingInfo;
import util.FileParsing.FileParser;
import util.mapping.CustomerMapper;
import util.mapping.MovieMapper;
import util.mapping.RatingsMapper;
import view.DisplayStatistics;
import view.UserInterface;

public class Application {

    public static void main(String[] args) {
        Statistics statistics = processStatistics();
        DisplayStatistics displayStatistics = new DisplayStatistics(statistics);
        initiateUI(displayStatistics);
    }

    private static Statistics processStatistics() {
        MovieInfo movieInfo = processMovies();
        CustomerInfo customerInfo = processCustomers();
        RatingInfo ratingInfo = processRatings();

        return new Statistics(customerInfo, movieInfo, ratingInfo);
    }

    private static void initiateUI(DisplayStatistics displayStatistics) {
        UserInterface userInterface = new UserInterface(displayStatistics);
        userInterface.start();
    }

    private static RatingInfo processRatings() {
        FileParser ratingsFile = new FileParser("ratings.dat", "::");
        RatingsMapper ratingsMapper = new RatingsMapper(ratingsFile, 4);
        return new RatingInfo(ratingsMapper.getCustomerIDMovieIDRatingAndTimeMap());
    }

    private static CustomerInfo processCustomers() {
        FileParser customerFile = new FileParser("users.dat", "::");
        CustomerMapper customerMapper = new CustomerMapper(customerFile, 5);
        return new CustomerInfo(customerMapper.getIdCustomerMap());
    }

    private static MovieInfo processMovies() {
        FileParser movieFile = new FileParser("movies.dat", "::");
        MovieMapper movieMapper = new MovieMapper(movieFile, 3);
        return new MovieInfo(movieMapper.getIdMovieMap());
    }

}

Changed Code after using Singleton (Processor ):

import controller.Statistics;
import view.DisplayStatistics;
import view.UserInterface;

public class Application {

    public static void main(String[] args) {

        Statistics statistics = Processor.getInstance().processStatistics();

        DisplayStatistics displayStatistics = new DisplayStatistics(statistics);

        UserInterface userInterface = new UserInterface(displayStatistics);

        userInterface.start();
    }


}

Singleton Class (Processor) code :

import controller.Statistics;
import model.primary.customer.CustomerInfo;
import model.primary.movie.MovieInfo;
import model.primary.rating.RatingInfo;
import util.FileParsing.FileParser;
import util.mapping.CustomerMapper;
import util.mapping.MovieMapper;
import util.mapping.RatingsMapper;


public class Processor {
    private static Processor ourInstance = new Processor();

    public static Processor getInstance() {
        return ourInstance;
    }

    private Processor() {

    }

    static Statistics processStatistics() {

        MovieInfo movieInfo = processMovies();
        CustomerInfo customerInfo = processCustomers();
        RatingInfo ratingInfo = processRatings();

        return new Statistics(customerInfo, movieInfo, ratingInfo);
    }

    private static RatingInfo processRatings() {

        FileParser ratingsFile = new FileParser("ratings.dat", "::");
        RatingsMapper ratingsMapper = new RatingsMapper(ratingsFile, 4);
        return new RatingInfo(ratingsMapper.getCustomerIDMovieIDRatingAndTimeMap());
    }

    private static CustomerInfo processCustomers() {

        FileParser customerFile = new FileParser("users.dat", "::");
        CustomerMapper customerMapper = new CustomerMapper(customerFile, 5);
        return new CustomerInfo(customerMapper.getIdCustomerMap());
    }

    private static MovieInfo processMovies() {

        FileParser movieFile = new FileParser("movies.dat", "::");
        MovieMapper movieMapper = new MovieMapper(movieFile, 3);
        return new MovieInfo(movieMapper.getIdMovieMap());
    }
}

Kotlin chain of responsibility pattern with generics

Using the chain of responsibility pattern I ran into a problem where next chain element was expected to have the same generic type of the first element. I know why this happens: The first handler expects the second handler to use the generic type "Apple". I just don't know exactly how to solve it.

There is an answer on how to handle it in java here, but since java doesn't have reified types and all that the approach should look different in Kotlin, right?

There are different options that come to my mind:

  1. Don't use generics - would lead to casting the collection types to specific subtypes and wouldn't look clean
  2. Try to use reified types (how?)

To illustrate the problem I am posting a demo code below.


data class Apple(val name:String, val color:Int) 
data class Orange(val circumference:Double)

object Main{
    @JvmStatic
    fun main(args: Array<String>) {
        val first = FirstHandler()
        val second = SecondHandler()
        first.setNextHandler(second)  // !!! wrong type here since <Apple> is expected
        first.process()
    } 
}

abstract class ChainHandler<T>{
    protected var nextHandlerInChain:ChainHandler<T>? = null
    fun setNextHandler(handler: ChainHandler<T>): ChainHandler<T> {
        this.nextHandlerInChain = handler
        return handler
    }

    abstract fun peel(): Collection<T>
    abstract fun process():MutableMap<String,Any> }

class FirstHandler : ChainHandler<Apple>() {
    override fun peel(): Collection<Apple> {
        return Collections.emptyList<Apple>()
    }
    override fun process(): MutableMap<String, Any> {
        val peeledApples = peel()
        val map = nextHandlerInChain?.process()
        map?.put("apples",peeledApples) ?:kotlin.run {
            val map = mutableMapOf<String,Any>()
            map.put("apples",peeledApples)
        }
        return map!!
    } }

class SecondHandler : ChainHandler<Orange>() {
    override fun peel(): Collection<Orange> {
        return Collections.emptyList<Orange>()
    }
    override fun process(): MutableMap<String, Any> {
        val peeledOranges = peel()
        val map = nextHandlerInChain?.process()
        map?.put("oranges",peeledOranges) ?:kotlin.run {
            val map = mutableMapOf<String,Any>()
            map.put("oranges",peeledOranges)
        }
        return map!!
    } 
}

CQRS/Event sourcing and MVVM

I have an application built with WPF and PRISM. This is a large project, and is event driven.

Logging is really important, so I was looking at incorporating CQRS and Event sourcing principles so we can log more, and better.

We also have some 'state' like displaying and setting the computername.

Now I am trying to wrap my head around a couple things:

  1. Things that are not event-based like the computer name (Which would not be in my control/database) How would I read and set the value?

  2. Some dataflow will come from the UI, thus being a command. Some will also come from external systems (lets say I poll a server and have a 'changed' event) How would this work? would I need to generate a Command or inject in directly into the event store?

  3. How would this work with MVVM? Would I need to get rid of MVVM - or should i use these patterns in conjunction etc.

Note: The main goal is logging - although replaying and all other pro's event sourcing provides would be handy too.

Also - some examples/sources tackling a broaders spectrum would be helpfull.

Avoiding circular dependencies in game unit targeting

I was working on the uml for a game I'm currently developing and got a bit stuck thinking about how to do Unit targeting.

So to explain, currently I have a UnitManager class that has a list of Units which it updates once every frame.

I want some of the units to be able to target one of the other units if it is within a certain distance. To do this I imagine I need to get a reference to the other units in the UnitManager list and check which of them are in range in some way.

Question: How can a Unit target another Unit without having a circular dependency between Unit and UnitManager (or anywhere else)?

Thanks in advance, Vidar.

How to use strategy pattern with custom sorting strategies?

I would like to know if the approach that I am using is the best or not for this situation.

I'm developing a REST API and I have an endpoint which has to return a list of person objects. Let's say that person class has age (int), hair and vegan (both booleans), for example.

That endpoint should return persons sorted by age (younger first), if they have the same age, then those who have hair, and then those who are vegan.

That sorting strategies can be changed, as they are read from configuration file. So the endpoint could have to return first those who are vegan, then those who have hair and then by age.

As I see there are different strategies to be applied, I thought that the best approach would be use strategy pattern (I also considered decorator but as the strategy can be changed I don't know how to apply it). I created a interface which returns a comparator, and then I have the strategies implementation that can be applied (hair, age and vegan), which return a comparator. I read the strategies from a configuration file and I save them into a string array.

As at this moment there are only three strategies I use

array.stream.sorted(strategy[0].compare().thenComparing(strategy[1].compare()).thencomparing...)

but I see a obvious problem, that this is not escalable, because if I add one strategy more it would not be processed.

So I have two questions here, is strategy pattern the best design pattern for this situation of sorting? And how could I proceed to make more generic the strategies array that are applied?

writing formula as a function and apply for each values

I have some MembershipTypes in my applications as follows:

sealed class MembershipType(val label: String) {
    abstract val interestOptions: List<BigDecimal>
    abstract val price: BigDecimal

    object GOLD : MembershipType("Gold") {
        override val price: BigDecimal = BigDecimal(1)
        override val interestOptions: List<BigDecimal> = listOf(BigDecimal(100), BigDecimal(200), BigDecimal(300))
    }

    object SILVER : MembershipType("Silver") {
        override val price: BigDecimal = BigDecimal(0.8)
        override val interestOptions: List<BigDecimal> = listOf(BigDecimal(300), BigDecimal(400), BigDecimal(500))
    }
}

Their properties are one price, and list of interestOptions.

I want to calculate all value (V) / interest(I) calculation combinations and return a list of Quotes List<Quote> using the following formula:

(R^max/R) × V × (1 - I/V) × 0.0015 × P
where 1 <= R <= R^max is the risk score with R^max = 3500, V > 0 is the value, I is the interest, 
and P is price. 

There are other types of MembershipType objects, however the GOLD and SILVER types have a set of pre-defined values so I define them in a QuoteMaker class:

class QuoteMaker {

    private val membershipToValue: MutableMap<MembershipType, List<BigDecimal>> = mutableMapOf()

    init {
        membershipToValue.put(MembershipType.GOLD, listOf(BigDecimal(2500), BigDecimal(5000)))
        membershipToValue.put(MembershipType.SILVER, listOf(BigDecimal(1000), BigDecimal(2000)))
    }


    fun generateQuotes(request1: Request) {

        val risk = request1.riskRate
        val membershipChosen = request1.membershipChosen   //list of MemberShipType selected

        generateMembershipQuote(riskRate, membershipChosen)

    }

    private fun generateMembershipQuote(riskRate: Int, membershipChosen: List<MembershipType>) : List<Quote> {
            //return membershipChosen.stream()
            //.forEach {  }...
    }

}

I receive the R(risk) and the selected list of Membership types in a Request object.

In the generateMembershipQuote(), I need to iterate through all the membership selected and then iterate over the values in membershipToValue for that type and calculate all the combinations for value/interest and return a result.

I want to create the formula as a function and then apply for each value/interest and return a result for that MembershipType. How could I implement this?

A Quote should have the info about the total price, the value and interest used to calculate the total and for which membership

data class Quote(
    val risk: Int, //r
    val value: BigDecimal, //v
    val interest: BigDecimal, //i
    val rate: BigDecimal, //0.0015
    val price: BigDecimal //p

) {

fun sum(): BigDecimal {
   //sum total
}

}

Python function with many optional arguments

I currently have a function with many optional arguments, something like this:

def many_argument_function(required1, required2, optional1=1, optional2=2,
                           optional3=None, optional4="Test", optional5="g",
                           optional6=2, optional7=(0, 255, 0), optional8=0.5):
                           # Do stuff

But in reality, it has over 20 optional arguments which take five lines even with 120 line limit.

Is there a design pattern to simplify this/make it prettier?

P.S. I have considered making a separate configuration file for this function, but then calling it would be annoying since most of the time only one or two optional arguments are used.

How to get the request and response information and send them as a post request in Jersey?

For example, when a user calls GET /API1/employee to get all the information about the employees in the database. I want to create a class and implement serval methods to get the request and response information like userid, timestamp when the api is called. And then send the JSON data to another api as a post request? Any reference or example about it?

Decorator pattern mess

I'm having a problem figuring out if I'm using the decorator pattern the right way. Let's suppose I have a console application. In this application I have defined a simple IConfigPathProvider interface, which will provide a configuration file path to some class.

public interface IConfigPathProvider
{
    string GetConfigPath();
}

The path is stored in the appSettings section of the console application's app.config file.

public class AppSettingsConfigPathProvider : IConfigPathProvider
{
    public string GetConfigPath()
    {
        return System.Configuration.ConfigurationManager.AppSettings["configPath"];
    }
}

The thing is this path is also encrypted, so...

public class DecryptingConfigPathProvider : IConfigPathProvider
{
    private readonly IConfigPathProvider _provider;
    private readonly IStringDecrypter _decrypter;

    public DecryptingConfigPathProvider(IConfigPathProvider provider, 
        IStringDecrypter decrypter)
    {
        _provider = provider ?? throw new ArgumentNullException(nameof(provider));
        _decrypter = decrypter ?? throw new ArgumentNullException(nameof(decrypter));
    }

    public string GetConfigPath()
    {
        var path = _provider.GetConfigPath();
        //decrypting method of IStringDecrypter interface
        return _decrypter.DecryptString(path);
    }
}

But, wait: it's not over. I have to add a specific portion to the path to get it right.

public class AppendSectionConfigPathProvider : IConfigPathProvider
{
    private readonly IConfigPathProvider _provider;

    public AppendSectionConfigPathProvider(IConfigPathProvider provider)
    {
        _provider = provider ?? throw new ArgumentNullException(nameof(provider));
    }

    public string GetConfigPath()
    {
        var path = _provider.GetConfigPath();

        return System.IO.Path.Combine(
            System.IO.Path.GetDirectoryName(path),
            "section", 
            System.IO.Path.GetFileName(path));
    }
}

And now - why not? - let's add some logging.

public class LoggingConfigPathProvider : IConfigPathProvider
{
    private readonly static ILog _log = 
        LogManager.GetLogger(typeof(LoggingConfigPathProvider));

    private readonly IConfigPathProvider _provider;

    public LoggingConfigPathProvider(IConfigPathProvider provider)
    {
        _provider = provider ?? throw new ArgumentNullException(nameof(provider));
    }

    public string GetConfigPath()
    {
        _log.Info("Getting config path...");
        var path = _provider.GetConfigPath();

        _log.Info("Config path retrieved successfully!");
        return path;
    }
}

Divide et impera

Of course the instant outcome is the separation of concerns, BUT what about the added complexity in instantiating the object? You need to know which decorator comes first and in which order they should be chained, otherwise you'll end up with a buggy IConfigPathProvider.

new LoggingConfigPathProvider(
    new AppendSectionConfigPathProvider(
        new DecryptingConfigPathProvider(
            new AppSettingsConfigPathProvider(), 
            decrypter));

And this is just a simple provider. In a rather complex application you'd likely come across multiple components with multiple references...this could easily led to a maintenance nightmare. Now, is this a well-known drawback or I'm just using this pattern in the wrong way?

dimanche 23 septembre 2018

Unit testing with MVVM Architecture

I am trying to create MVVM architecture with unit testing. I create MVVM architecture by flowing this link.

How I have to write unit testing for this I am very new to unit testing, see the code give below.

viewcontroller:

func initViewModel(){

    //code for updating activity indicator in the view.
    loginViewModelObj.updateLoadingStatus = { [weak self] () in
        DispatchQueue.main.async {
            let isLoading = self?.loginViewModelObj.isLoading ?? false
            if isLoading {
                Utils.showCustomisedActivityIndicator((self?.view)!, height: 35, width: 35)
            }else {
                Utils.HideActivityIndicator((self?.view)!)
            }
        }
    }


    loginViewModelObj.checkLoginType =  { [weak self] () in
        DispatchQueue.main.async {

            let LoginType = (self?.loginViewModelObj.shouldCheckLoginType)!

            if (LoginType == 0)
            {
                self?.verifyEmailView.isHidden = true
                self?.verifyPasswordView.isHidden = false
                self?.verifiedIdTextField.text = self?.loginViewModelObj.email
                self?.passwordTextField.text = ""

            }
        }
    }
    }

I am calling this in viewdidload and api calling is done under UIButton:

let paramDict   =   ["user_input":userIdTextField.text!] as [String : Any]
        let siginDict   =   ["variables" : paramDict]


        //call api method in the ViewModel
        loginViewModelObj.makeApiCall(paramsDict: siginDict as [String : AnyObject])

in view model, I am parsing the response using kvc and in view model I am doing the following code:

class LoginViewModel: NSObject {

var deafults = RewardsUserDefaults()


var checkLoginType : (() -> ())?




var shouldCheckLoginType :Int = -1
{
    didSet {
        self.checkLoginType?()
    }

}




override init() {
    super.init()
}



func makeApiCall(paramsDict : [String:AnyObject]){

    self.isLoading = true

    ApiCallManager.sharedManager.CallApiWithMethod(suffixUrl: “XXXXXXX", methodType: .post, joseToken: "", parameters: paramsDict as Dictionary<String,Any> as Dictionary<String, AnyObject>) { (result, error) in

        self.isLoading = false

        if error! == APICallsError.RequestSuccess {
            if let dataDict = result!["data"] as? [String:AnyObject]{

                if let userIdentityDict     =   dataDict["validateUserIdentity"] as? [String:AnyObject]{

                    if userIdentityDict["success"] as? Int == 1 {

                        let successObj = (LoginModel(response: Utils.getResultDictionary(result: result, error: error)))
                        self.email = successObj.email
                        self.shouldCheckLoginType = successObj.userLoginType


                        UserDefaults.standard.setValue(successObj.auth_token, forKey: "at")


                        return
                    }
            }
        }else{
            print("API Call failed")

        }
    }
}

This the correct way of creating MMVM architecture, if yes how to apply unit testing for viewmodel, else if it is wrong can please suggest when I did the wrong.

php type hinting extending variable type

Consider this case, I have an abstract class, which children take a blueprint and do different actions with it. Now I have multiple classes which extend this and perform slightly different actions with the blueprint, thus I have extended versions of said blueprint, which I need each of the child classes to get.

As such I want to define / type hint the property or respective function input property in the abstract class as any and then specify the property type in each of the child classes.

But I cannot do this, because PHP 7 gives me an error

Declaration B::setBlueprint() must be compatible with A::setBlueprint()

The blueprint classes

class Blueprint {
    public $id;
}

class ChildBlueprint extends ParentBlueprint {
    public $someOtherPropINeedOnlyInThisClass;
}

and the abstract classes that consume those blueprints

abstract class A {
    abstract public function setBlueprint( ParentBlueprint $_ );
}

class B extends A {
    public function setBlueprint( ChildBlueprint $_ ) {}
}

I mean I need a blueprint that is derived from the in all of the A, B, C, ..., X, Y classes and as such it makes no sense to leave it out of the abstract class.

What are good OOP solutions to this issue?

Singleton & "sequential execution" design patterns

I'm implementing a game library for mobile using Singleton design pattern as below

Game.initialize("game_id")
.downloadMap()
.showMap()
.setAutoAdjustMapResolution(true)

I have no problem with Singleton & Builder design pattern but my problem is

downloadMap() -> need to wait until initialize("game_id")
showMap -> waits until downloadMap() finishes
showMap -> depends on setAutoAdjustMapResolution(true)

I don't know what kind of design pattern I can apply in this case I'm thinking of Chain of Responsibility but no sure

Please give me your idea or advice. Thank you

How to architect nested Fragments in a ViewPager?

I have a ViewPager, which holds 3 Fragments. One of the fragments is a ScrollView, with several distinct sections (an About Me screen with photo uploading, details, settings sections).

I'm decoupling business logic with using MVVM, but still the Fragment is quite large (700 lines of code), as all of the sections need a great deal of UI logic (RecyclerViews, reactive fields, onActivityResult-related stuff).

If the Fragment was an Activity instead, I could just add all 3 sections as separate Fragments and manage communication with the Activity, but since it's a Fragment I'm not sure how to organise these nested sections so that they are not in one class but can still communicate with each other.

DRY support for multiple interacting libraries

I've researched many different approaches to abstracting away multiple implementations, but none seem to address the issue of mixing and matching supported implementations.


Consider this scenario:

Subsystem A is implemented using Library A or Library B.

Subsystem B may be implemented using Library C or Library D.

The problem arises from the fact that Subsystem A's implementation may vary slightly depending on the implementation used for Subsystem B.

A concrete example is a windowing API and a graphics API. If SDL is chosen for the windowing API, the setup code varies slightly depending on which graphics API is chosen (OpenGL, Vulkan, DirectX, etc.). This may be true of other windowing as well.

This means that a "one size fits all" windowing wrapper implementation may not necessarily exist.


With the requirement that all supported implementations must be contained in a single binary, how could this be accomplished? Is there a clean pattern that achieves this while keeping code duplication to a minimum? I'd like to avoid making an entire special implementation for every foreseeable combination of libraries.

In what layer are the DTOs stored with CQRS?

The Domain has the Domain Models.

The Infrastructure layer has Commands and Queries, forming CQRS.

Commands return Domain Models, and Queries return DTOs.

In any API, the DTOs are stored in the Application layer, never in the Domain, but if Queries return DTOs, must the DTOs be stored in the Domain? Is it a good idea?

Is it better to subscribe to changes or a full data set?

Let's say that I have two services A and B. Service A has a set of items like [ "foo", "bar" ] and is the service responsible for bringing the items into the system. Service B needs to subscribe to this data set. There are 2 ways it could do that:

  1. Subscribe to the full data set
  2. Subscribe to the changes

To give a concrete example, let's say the data set goes through evolutions like

  • [ "foo", "bar" ]
  • [ "foo", "bar", "baz" ]
  • [ "foo", "baz" ]
  • [ "foo", "baz", "buz" ]

The messages sent to service B with each change could be exactly what's above or it could be like

  • { add: [ "foo", "bar" ], subtract: [] }
  • { add: [ "baz" ], subtract: [] }
  • { add: [], subtract: [ "bar" ] }
  • { add: [ "buz" ], subtract: [] }

The question is which would be better. My view is that the first is better for the following reasons

  • Eventual consistency. In the first, if a message gets lost or there's some other failure so that B doesn't process a message, it will always be corrected when it successfully processes another message. In the second, there would be a lot of complexity to be added to the system to automatically correct these fail scenarios.
  • Idemptoency. Similar to the above point, if service A sends duplicate messages by accident, that's totally fine in the first design, whereas as the second design that case would require extra complexity to treat.
  • Delta is not really an optimization. Initially it sounds like an optimization to say "The rest of our system will only process the changes," but the thing is that someone has to compute the changes, so why should A rather than B, and how does this reduce the total number of operations?

Unit of work with repository design pattern issue resolve

How to resolve this issues.

An unhandled exception occurred while processing the request.

InvalidOperationException: Unable to resolve service for type 'UnitOfWorkWithRepositoryPartens.Interface.Repository.ITestRepository' while attempting to activate 'UnitOfWorkWithRepositoryPartens.BusinessServise.TestServise'.

Git repository - Git Repository link https://github.com/Kasunjith-Bimal/DesignPartens-

Issue

error

project structure and startup class

Project Structure and startup class

Git repository - Git Repository link https://github.com/Kasunjith-Bimal/DesignPartens-

samedi 22 septembre 2018

Java program to print a string pattern

if the input string is "ADMINISTRATIONS" the pattern should be like this A DM INI STRA TIONS

The last row should be completely filled

if the input string is "COMPUTER" the pattern should be like this C OM PUT ER**

the incomplete last row should be filled with *

Help me to solve this.

Is there a name for a design pattern where collections are updated in sequence and the last is considered the source of truth?

Let's say I'm trying to transform SQL storage to no-SQL storage (e.g. SQL Server to Cosmos DB). I have three related tables A, B, C which I want to convert to document collections X, Y, Z. But I don't have the advantage of being able to update all the documents transactionally like I would in SQL. So how I design the update to the documents in my workflow is a sequential update like

1. Update X
2. Update Y
3. Update Z

Such that any of the following scenarios

1 -> FAIL
2 -> FAIL
3 -> FAIL


1 -> SUCCEED
2 -> FAIL
3 -> FAIL


1 -> SUCCEED
2 -> SUCCEED
3 -> FAIL


1 -> SUCCEED
2 -> SUCCEED
3 -> SUCCEED

may leave the data in an "inconsistent state," but I use the repository pattern to query the data with a query like

Get data from Z
Get matching data from Y
Get matching data from X

so that all the update scenarios are covered.

Is there a name for this pattern [or did I invent something new :) ]?

Is this a pattern or an anti-pattern?

Is there a better way?

Separate View object for data manipulation and presentation

I have two Domain Models - Employee and Department. The class structures look like below

Employee

@Entity
@Table(name="emp")
class Employee {
@Column(name="name")
private String name;

@Id
private UUID id;

@ManyToOne
@JoinColumn(name="dept_id")
private Department dept;
....
}

Department

@Entity
@Table(name="dept")
class Department {
@Id
private UUID id;

@Column(name="name")
private String name;

@Column(name="description")
private String description;
....
}

These domain objects are used only in service and repository layers. Controllers use only View objects.

I have following two views

  1. Creates an employee object. Along with employee attributes, it also accepts department reference.
  2. Displays employee information along with department details.

Should I be creating two different view objects as below

Create/Edit

class EmployeeVO {
private String name;
private UUID id;
private UUID deptID;
}

(Intention is to avoid passing department name and other department details while creating/editing Employee. Also, I do not want API doc generators to list all irrelevant attributes.)

View

class EmployeeViewVO {
  private String name;
  private UUID id;
  private DepartmentViewVO deptView;
}

class DepartmentViewVO{
  private id;
  private name;
}

(Retrieve employee information in one API call.)

What is the recommended approach for such a scenario, is it good practice to have one View Object meant for data manipulation and another view object for presentation?

vendredi 21 septembre 2018

Callback vs object reference

Design question: Suppose we have parent and child object. Sometimes child object says "Parent, you've got to update your state." So, is there any critical difference between

  1. Passing parent object reference into child contructor

and

  1. Passing parent object callBack function into child constructor

of course, Except the case when child has to be revoked any chance to affect parent object other than using this callBack function.

Electricity Billing System for Home in OOPS

I recently appeared for interview for code-pairing round and I was asked following question: Electricity Billing System for home“. The corresponding power usage of home appliances(Fan, AC, Fridge, Light) was given:

Appliance | Per hour unit consumption
Fan 4
Light 2
AC 10
Fridge 8

The slab chart was given as:

Slab 1 - 0 to 1000 unit: INR Rs 20 per unit
Slab 2 - 1001 to 3000 unit: INR Rs 30 per unit
Slab 1 - 3001 to 6000 unit: INR Rs 40 per unit
Slab 1 - 6001 and above unit: INR Rs 50 per unit

Input:

Appliance | CountOfAppliance | TotalUasgePerDayInHours
Fan 2 4
Light 1 4
AC 1 12
Fridge 1 5

Output:

200000 INR
Units Per Day : (2*4*4 + 1*4*2 +1*12*10 + 1*5*8) = 200
unitsPerMonth = 6000
totalBill = 1000*20 + 2000*30 + 3000*30 + 3000*50 = 200000

I had modeled the code using "Factory Design Pattern" for appliance. But my Code for Price Slab was something the interviewer was not happy with the hardcoding. Though I modified it by using Constants file for slabs but the interviewer was still expecting something better. Kindly let me know how it can be improved.

My Code:

IElectricComponent

public interface IElectricComponent {
    public enum Unit{
           FAN(4), LIGHT(2), AC(10) , FRIDGE(8);
           private int value;
           private Unit(int value) {
                this.value = value;
           }
           public int getValue(){
            return value;
           }
       }
    public int claculateUnitForSingleDay();
}

Fan

public class Fan implements IElectricComponent{

    private int noOfComponents;
    private int perDayUsage;
    public Fan(int noOfComponents, int perDayUsage){
        this.noOfComponents=noOfComponents;
        this.perDayUsage=perDayUsage;               
    }

    public int claculateUnitForSingleDay(){
        return noOfComponents*perDayUsage*Unit.FAN.getValue();      
    }   
}

The same way for Fridge,Light and Ac

Factory : ApplianceFactory

public class ApplianceFactory {

        public static IElectricComponent getInstance(String appliance, int countOfAppliance ,int perDayUsage ){

            switch(appliance){

                case ApplianceConstants.FAN:
                    return new Fan(countOfAppliance,perDayUsage);

                case ApplianceConstants.LIGHT:
                    return new Light(countOfAppliance,perDayUsage);

                case ApplianceConstants.AC:
                    return new AC(countOfAppliance,perDayUsage);

                case ApplianceConstants.FRIDGE:
                    return new Fridge(countOfAppliance,perDayUsage) ;

                default :
                    return new IElectricComponent() {

                        @Override
                        public int claculateUnitForSingleDay() {
                            // TODO Auto-generated method stub
                            return countOfAppliance*perDayUsage;
                        }
                    };
            }

        }
    }

Constants:

public interface ApplianceConstants {

    public String FAN = "Fan";
    public String LIGHT = "Light";
    public String AC = "AC";
    public String FRIDGE = "Fridge";

    public int Slab1 = 20;
    public int Slab2 = 30;
    public int Slab3 = 40;
    public int Slab4 = 50;
}

PriceSlab:

public class PriceSlab {

    HashMap<String,Integer> slabs = new HashMap<>();

    public int calculateBill(int units){

        slabs.put("A", ApplianceConstants.Slab1);
        slabs.put("B", ApplianceConstants.Slab2);
        slabs.put("C", ApplianceConstants.Slab3);
        slabs.put("D", ApplianceConstants.Slab4);

        return calculateBillTotal(units);
    }

    private int calculateBillTotal(int units) {

        int total = 0;
        if(units <= 1000){
            total = units*slabs.get("A") ;
        }
        else if (units <= 3000){
            total = 1000*slabs.get("A") + (units-1000)*slabs.get("B");
        }
        else if (units <= 6000){
            total = 1000*slabs.get("A") + 2000*slabs.get("B") +(units-3000)*slabs.get("C");
        }
        else{
            total = 1000*slabs.get("A") + 2000*slabs.get("B") + 3000*slabs.get("D")
                +(units-6000)*slabs.get("C");
        }
        return total;
    }
}

Main class:

public class BillGenerator {

    public static void main(String[] args) {

        Scanner scn = new Scanner(System.in);
        ApplianceFactory factory = new ApplianceFactory();
        int inputOfAppliance = scn.nextInt();
        String appliance="";
        int countOfAppliance;
        int perDayUsage;
        int unitsPerDay=0;
        for(int t=0 ; t<inputOfAppliance ;t ++){
            appliance = scn.next();
            countOfAppliance = scn.nextInt();
            perDayUsage = scn.nextInt();
            IElectricComponent electricComponent = factory.getInstance(appliance, countOfAppliance, perDayUsage);
            unitsPerDay += electricComponent.claculateUnitForSingleDay();
        }
        System.out.println("unitsPerDay = "+unitsPerDay);
        int unitsPerMonth = unitsPerDay * 30;
        System.out.println("unitsPerMonth = "+unitsPerMonth);

        PriceSlab slab= new PriceSlab();
        int totalBill = slab.calculateBill(unitsPerMonth);
        System.out.println("totalBill = "+totalBill);
    }

}

I thought a lot about how to remove hardcoding from price-slab function but couldn't think of anything better. Please let me know how it can be improved or if any other design pattern could be used for it.

Thanks in advance.