lundi 31 octobre 2016

Conditonaly inject Dependancy injection

I am injecting dependancy in action method of mvc controller .

Scenerio - i want to use interface in action method of mvc controller. This interface is implemented by 2 classes . for example modelA and modelB both are inherited from interfaceA . on runtime when user change the value in dropdown according to the value of dropdown dependancy injection should determine it should inject modelA object or modelB object .

Also i am not sure is DI is the solution or any other solution exists . or factory patter not sure .

Best practices to load multiple views for same resource

I'm having a bad time figuring out the best way to load multiple views of the same resource in Laravel. I'll explain the problem:

I have a resource called Books, which has a controller called BooksController with the basic restfull methods (index, store, etc.). Now I want that, in my home page, these books to be loaded with different stuff from different resources, but I also want these books to be loaded with different resources in different pages too, and this is where I'm having trouble finding the controllers I should use.

When should I use the BooksController GET requests, since it will never only show something related to the books only?

Should I create a controller for each page? Like a HomeController to show the books with the different resources, and the same for any other -Page-Controller, leaving the BooksController only for updating and storing?

Maybe I should not use rest at all and just create a controller for each page?

I really need a light here to help me better understand this Pages and Controllers flow using MVC and REST, thanks in advance!

GoLang live connections in function

I had question about better code usage in golang.

What is the best case of usage live connection like database in few packages.

It is better to add database connection like

1.

func (database DB) getRows(){

}

or 2.

func getRows(database *DB){

}

or 3.

func getRows(){
  init database connection...
}

For 1 usage we need create local struct for DB

type DB struct{
connection
}

in different package I need move DB connection with creating local struct in each package or when some package did not use database connection but imported package use? How to send one configuration and create only one connection? Singleton is good idea?

Are you have any tips and trick for this case usage?

Custom Design Pattern, e.g. IDisposable Pattern

Short version: How can I create my own pattern binded to a interface, just like IDisposable Pattern Snippet?

Long version: Whenever I implement a "IDisposable", Visual Studio 2015 offers me an option to implement IDisposable Pattern and it writes some code to my class... So, how can I have my own pattern to implement with a certain interface (create by me)?

The idea is that all the developers can have an clue of how to implement a certain interface with the correct "pattern".

JSF-Managed Beans and Design Patterns

Lets assume, i have a student.xhtml form that has radiolists&dropdownmenu populated from its @ManagedBean Student(). As u know, in order to populate form from managedbean i need to have List<Object> fields in Student class. But i also want my Student class to be pure meaning it should have fields only related to itself, not the possible values it can get (i mean List<>). So i want to seperate my Student class from @ManagedBean. So i will have two classes at the end one of is pure Student class and StudentBean class which controls the view.

So my question is, is it good practice have two classes like below or i should go with one class? Two classes method duplicates fields so i don't know whether it affects performance to a bad extent.. What do you suggest?

Not wanted BeanClassWithStudent Pattern;

 import java.util.ArrayList;
 import java.util.List;

 import javax.annotation.PostConstruct;
 import javax.faces.bean.*;

  @ManagedBean
  public class Student {

private String firstName;
private String lastName;
private String country;
private String favLanguage;

private List<String> countryList;
private List<String> favLanguageList;

@PostConstruct // generate DropDownList Combobox and radiobuttons From class fields
public void init() {
    generateCountries();
    generateFavLanguages();
}

public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
public String getCountry() {
    return country;
}
public void setCountry(String country) {
    this.country = country;
}
public String getFavLanguage() {
    return favLanguage;
}

public void setFavLanguage(String favLanguage) {
    this.favLanguage = favLanguage;
}
public List<String> getCountryList() {
    return countryList;
}

public List<String> getFavLanguageList() {
    return favLanguageList;
}

private void generateCountries(){
    countryList = new ArrayList<>();
    countryList.add("Turkey");
    countryList.add("France");
    countryList.add("Senegal");
    countryList.add("USA");
}

private void generateFavLanguages(){
    favLanguageList = new ArrayList<>();
    favLanguageList.add("Java");
    favLanguageList.add("Ruby");
    favLanguageList.add("C++");
    favLanguageList.add("Visual Basic");
}

}

My wanted seperate classes; Student.class

  public class Student {

private String firstName;
private String lastName;
private String country;

public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
public String getCountry() {
    return country;
}
public void setCountry(String country) {
    this.country = country;
}

Wanted StudentControllerBean;

 import java.util.ArrayList;
 import java.util.List;

 import javax.annotation.PostConstruct;
 import javax.faces.bean.*;

  @ManagedBean
  public class StudentBean {

private String firstName;
private String lastName;
private String country;

private List<String> countryList;
private List<String> favLanguageList;

@PostConstruct // generate DropDownList Combobox and radiobuttons From    class fields
public void init() {
    generateCountries();
    generateFavLanguages();
}

public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
public String getCountry() {
    return country;
}
public void setCountry(String country) {
    this.country = country;
}
public List<String> getCountryList() {
    return countryList;
}

public List<String> getFavLanguageList() {
    return favLanguageList;
}

private void generateCountries(){
    countryList = new ArrayList<>();
    countryList.add("Turkey");
    countryList.add("France");
    countryList.add("Senegal");
    countryList.add("USA");
}

private void generateFavLanguages(){
    favLanguageList = new ArrayList<>();
    favLanguageList.add("Java");
    favLanguageList.add("Ruby");
    favLanguageList.add("C++");
    favLanguageList.add("Visual Basic");
}

}

How to parameterize Commands without the caller "knowing" anything about the Command ahead of time

My question is similar to (but not exactly the same as) this question. This question was also helpful but it is less similar to my current question than the previous question that I linked to.

I have a framework that runs automated testing. Basically, an XML "script" has data on which methods to call against our API; our engine runs the specified methods with reflection.

Due to how the logs are generated, sometimes we want to replace certain method calls with another one. (There's not really any way around that). A factory "knows" that

// Originally we called this a "Command" pattern but it may be more accurate to call it a Strategy
// See if we're supposed to replace this method call with something else
bool wereAnyCommandsRun = await ExecuteCommandsIfThereAreAny(interfaceName, methodName);

// If we're NOT supposed to replace this method call, go ahead and execute it
if (!wereAnyCommandsRun)
{
   // Do the method call
   // ...
}

We do the XML mapping like this:

<map method="CaptureDomain" interface="IFrameworkInterface" command="ApplyXsltCommand"/>

Right now "Commands" (probably more accurately "Strategies") are completely standard - they implement an interface with an Execute() method.

Now I need to add parameters to this. I don't know in advance which parameters they will need, so I'm trying to come up with something that wouldn't be completely hideous and fragile. My main requirements are that I don't want the design to become overly complicated; also, the primary point of this is to make my engine as "future-proof" as possible, so I want to make sure that it doesn't require modification if I add or refactor a method or a new requirement comes in (meaning that the Command and its caller have to be loosely coupled).

A few ideas I had and rejected:

  • Accept a params array and use reflection to decide whether the caller passed in values of the correct type. I don't like this though because it dramatically increases the coupling between the command, and the whole point of the mechanism is to reduce the coupling.
  • Create parameter "objects" for each possible type. This, too, would create a lot of "coupling."
  • Parameterized factories

Some ideas I'm seriously considering:

  • Have a Context object like one of the answers in the question I linked to suggested. If I'm reading the question I linked to correctly, the advantages here would be that the caller wouldn't have to "know" anything about command in advance. Obviously, though, there could be a performance hit if I end up capturing too much information about the caller.
  • I have a MethodInfo object and parameter info for the method I'm replacing - maybe add this as a third "item" in the Factory's mapping. The problem I see here is similar to the downside of the previous solution: the fact that a parameter is necessary for the method being called doesn't imply that it's also necessary for the Command. Also, my Commands may be called by several different methods, so it's important that there be no coupling at all between them (so it's more complicated than just "if you see this parameter list, use that command").
  • Try to implement some kind of a Visitor pattern instead of the Strategy pattern. However, I'm a little hazy on how that would actually work to tell the truth, and it seems like it could just complicate things.

I'm hoping that this isn't too broad or opinion-based (please let me know if so and I'll edit - I'm definitely not trying to ask a "gimme teh codez" type question), but does anyone see a problem with these solutions? Are there any other possibilities (besides what I've listed here and in the other question) that would be better?

Use empty class(java)

I m doing my best to speak in english to you, sorry for mistakes.

I have a school project about walmart's software.

My walmart has different sectors(food,technology,hygiene etc) and, products have also sectors ( an orange is food, a cd-rom is technology etc).

So i m going to create an abstract class sectors .and food , technology ,hygiene etc, will extends sectors.

BUT all their classes are empty: no field and methods, only extends stuff. So i m wondering if i should do it like that or this is awful.

Indeed i need, for example, a walmart that sell only food and technology, to know the products that are food or technology.

public class walmart{
set<sector> sectors //can be for example only food, only technology or both
//field and methods
}

public class product{
sector type
//field and methods
}
public abstract class sectors{//almost empty
}
public abstract class food extends sectors{//also empty
}
public abstract class technology extends sectors{//still empty}

Thanks

IDisposable Pattern suggestion, Visual studio 2015

Whenever I implement a "IDisposable", Visual Studio 2015 offers me an option to implement IDisposable Pattern and it writes some code to my class... So, how can "suggest" a pattern to implement a certain interface (create by me)? This way all the developers can have an idea of how to implement a certain interface with the correct "pattern".

Triangle programs in Java [on hold]

I want a code to print the following output:

                         1  
                       2 1 2
                     3 2 1 2 3 
                   4 3 2 1 2 3 4 
                 5 4 3 2 1 2 3 4 5

And also with the following output I need code: (1,1) (1,2) (1,3) (1,4) (1,2) (1,3) (1,4) (1,3) (1,4) (1,4)

dimanche 30 octobre 2016

C++ singleton in constructor

Is this possible?

class A {
    static A *instance = NULL;

public:
    A () {
        if (instance) {
            this = instance;
        } else {
            instance = this;
        }
    }
}

Does it have leak memory?

Do I need to oveload new operator?

Expose methods to test code but not to end-users?

Given:

public class Dummy
{   
  /**
   * Constructor meant to be used for test code.
   * @param scope test-specific "globals"
   * @param value some user-supplied value
   */
  public Dummy(SingletonScope scope, int value)
  {
    // ...
  }

  /**
   * Constructor meant to be used by end-users.
   * @param value some user-supplied value
   */
  public Dummy(int value)
  {
    scope = someDefaultValue();
    // ...
  }
}

Is there a design pattern that will allow me to expose the first method to test classes that are scattered across multiple packages, and the second method to end-users?

I don't want to expose the first constructor to end-users because it clutters the API specification and I don't want it to form a de-facto standard (similar to sun.misc.Unsafe). The solution cannot use dependency injection or reflection.

What is the best practice for setting/determining the concrete types in a List

If I have either:

List or List

Where many types implement the interface iCanSpeak or use the abstract class Animal as a base class.

What is the best practice for determining/setting the concrete types that are in my actual list?

I know C# offers .TypeOf and I have seen examples that use an enumeration in the base class or interface to make determining easier, but what is the best practice and why?

Potentially off-topic follow-ups:

Also, what is TypeOf doing under the hood? Is it up casting? Why aren't the properties of the different concrete classes lost when put into a list?

Does... List == List

If the defined methods and properties are the same?

How to automatically create wrapper for generic classes in autofac

I have simple code: public interface ICommand { }

public class CommandA : ICommand {}

public class CommandB :ICommand{}

public interface IHandler<in TCommand> where TCommand: ICommand { void Handle(TCommand command); }

public class Handler1: IHandler<CommandA> { public void Handle(CommandA command) {}}

public class Handler2: IHandler<CommandA> { public void Handle(CommandA c) {} }

public class Handler3: IHandler<CommandB> { public void Handle(CommandB c) {} }
public class Handler4: IHandler<CommandB> { public void Handle(CommandB c) {} }
}

I register all handlers using AsClosedTypesOf

builder.RegisterAssemblyTypes(myAssembly).AsClosedTypesOf(typeof(IHandler));

I have also dispacher class which should find all handler for given command and execute them

public class Dispatcher {
void Dispatch<TCommand>(TCommand command) where TCommand : ICommand {
    var handlers = context.Resolve<IEnumerable<IHandler<TCommand>>>();
    foreach (var handler in handlers) { handler.Handle(command); }}}

I have several problems here: 1) I want to have Dispatcher in different project and want to get rid of coupling to autofac

2) Really cannot find way to get/resolve all handlers from autofac. (I cannot register command because they can have other dependencies not known at registration)

3) I want to have another dispatcher which can user kind of wrapper on Handlers like this:

public class ActorHandler<TCommand> where TCommand : ICommand {
private IHandler<TCommand> _handler;

public ActorHandler(IHandler<TCommand> handler){
    _handler= handler;}
public void OnReceive(object obj) { var command = (TCommand)obj; _handler.Handle(command); }}

I'm not sure I can do it automatically for all handlers I have problem when I want to make kind of wrapper for every Handler

How to improve object and data layer - LINQ TO SQL

I have been using Layered Architecture in my web application. Can anyone please advise if my data layer classes (both Linq and booking class) can be improved?

I have just started learning about solid design principles and Dependency injections. Does my object or data layer classes achieve any of the SOLID principles?

Object Layer

        [Table()]
        public class Clerks
        {
            [Column(CanBeNull = false, IsPrimaryKey = true, IsDbGenerated = true)]
            public Int32 ClerkID { get; set; }
            [Column()]
            public string Name { get; set; }
            [Column()]
            public string Email { get; set; }
            [Column(IsVersion = true, IsDbGenerated = true)]
            public byte[] Version { get; set; }
        }

LINQ Class in Data Layer

            /// <summary>
        /// LinqDatabase Class extends DataContext
        /// Entry point for the LINQ to SQL framework
        /// </summary>
        public class LinqDatabase : DataContext
        {

            private const Int32 timeOut = 20;

            private static string connStr = ConfigurationManager.ConnectionStrings["SQLConnection"].ConnectionString;



            public LinqDatabase(bool objTrack = false): base(connStr)
            {
                base.CommandTimeout = timeOut;
                //to track the original value and object identity
                base.ObjectTrackingEnabled = objTrack;
            }

            public Table<Clerks> Clerks;
            public Table<Authorities> Authorities;
            public Table<Bookings> Bookings;


            public static DataTable ToDataTable<T>(IEnumerable<T> collection, string tableName)
            {
                DataTable tbl = ToDataTable(collection);
                tbl.TableName = tableName;
                return tbl;
            }


            public static DataTable ToDataTable<T>(IEnumerable<T> collection)
            {
                DataTable dt = new DataTable();
                Type _t = typeof(T);
                PropertyInfo[] pia = _t.GetProperties();

                //Create the columns in the DataTable
                foreach (PropertyInfo pi in pia)
                {
                    dt.Columns.Add(pi.Name, Nullable.GetUnderlyingType(pi.PropertyType) ?? pi.PropertyType);
                }

                //Populate the table
                foreach (T item in collection)
                {
                    DataRow dr = dt.NewRow();
                    dr.BeginEdit();
                    foreach (PropertyInfo pi in pia)
                    {
                        dr[pi.Name] = pi.GetValue(item, null);
                    }
                    dr.EndEdit();
                    dt.Rows.Add(dr);
                }

                return dt;
            }
        }

Booking Data Layer Class

    public class BookingsDB
    {

        private LinqDatabase db = new LinqDatabase();

        public void Dispose()
        {
            db.Dispose();
        }

        public static void Insert(Bookings l)
        {
            LinqDatabase dbs = new LinqDatabase(true);

            try
            {
                dbs.Bookings.InsertOnSubmit(l);
                dbs.SubmitChanges();
            }
            catch (Exception ex)
            {
                //log error

            }
            finally
            {
                dbs.Dispose();
                dbs = null;
            }
        }


        /// <summary>
        /// Get Report in specific date range
        /// </summary>
        /// <param name=" p_startDate, p_EndDate">Passing date range to get a report</param>
        public DataTable GetReport(DateTime p_startDate, DateTime p_EndDate)
        {

            dynamic query = (from b in db.Bookings
                             join a in db.Authorities on b.AuthorityID equals a.AuthorityID
                             join c in db.Clerks on b.ClerkID equals c.ClerkID
                             where b.BookingDate >= p_startDate && b.BookingDate <= p_EndDate
                             orderby a.Name , b.BookingDate 
                             select new { AuthorityName = a.Name, b.BookingDate, ClerkName = c.Name, c.Email });

            return LinqDatabase.ToDataTable(query);

        }
    }

A better approach to include unique meta tags across pages that share a universal header

I currently have a website that uses PHP to include a header.php file across all of my pages. This file contains the HTML for my menu bar and head tags that include my meta tags, links to my scripts and style sheets. The problem I am having with this approach is that I do not want all of my pages to share the same meta tags.

What is considered the best practice to include unique meta tags for each page but still achieve the benefits of a template approach where a universal header is used across all pages on a website.

I am looking for answers that propose a better design principle in general rather than a particular solution in PHP, I am open minded to any frameworks, languages or server side platforms that may be needed to achieve better design practices overall.

Redesigning a C# client app which communicates through a serial port with a control unit

I'm writing a c# app which communicates with a control unit over a serial port, and showing data about hardware units(which connected to the control unit) on a windows forms. the app changes their settings, and can record data recieved from them.

the app has many design problems, because I wrote it without much experience. almost all the code is located under the main form, and I'm barely using Object Oriented principles and design patterns. All the code that deals with serial communication, parsing commands, sending commands and a graph that shows data from the hardware units is located inside this form. I even did not make yet a object for the hardware units, im just storing the data on the windows forms controllers(numeric up-down, etc..).

after learning OOP course in the university, I clearly see this app is poorly designed, and I need to redesign it.

The problem is, I have no idea how to sort the code out, because its the first time I deal with this kind of app. Unfortunately, I haven't learned yet how to do a good design for systems. For start, I thought about splitting the serial communication from the main form, so the main form would not have to deal with the communication.

But, this is not sufficient. the app needs to be robust, and well coded. The app is required to:

With those requirements, what design patterns and class hierarchy would you guys recommend for an app like this?

the app needs to:

*communicate with the control unit using an explicit communication protocol, so there is a part that needs to parse the answers from the control unit and understand what to do. it sends requests and wait for response from the control unit. -where should this part be in the hierarchy and with what parts of the system should it interact?

*manage data about some hardware units, show it on the main form, while the data and the settings of the units is received by request from the control unit. -where should the hardware unit objects to be stored? within the main form? singleton class which holds them?

I would be really grateful if you could suggest some good solutions and design ideas that will help me with fixing this application. Even links to the right places with the right information will do much for me.

with much thanks, David

Design a java based menu so that it's easier to add new options

I am trying to create a java application which displays a Menu with few options. Each option selection performs some independent operation say executing a script or performing some db operation etc
eg:
1 option1title
2 option2title
3 option3title
...

I need to design this such that I should be able to add new options easily. say just by adding a new class.
Some options might show a submenu as well.

Design thoughts that I have

Have an interface say "IOption" with methods like optionTitle, optionAcion. So each "Option" in the menu would implement this interface and write its action & title.
How do I display the menu ?
I can have a class which where each option is registered. Say a list of all the options. Then my main program would iterate over this classes and shows the menu. Option selection would call the action of that particular class.
Else I can use reflection/annotation to get the all the classes which implement this interface and show the menu ----> This might be an overkill.

Is there any better way to design this ? Any design patterns that I can bring in ? My priority is good design.
With my solution also If I want to add a new option, I would need to register each option in a list, implement the class etc.
Instead of adding to a list in register class, how about having the optionTitle <-> class info in an xml file or something ?
And I'll have submenus as well. Other than writing this in the itemAction method, any better way to design this ?

Let me know If I need to add more info.

Hosmer-Lemeshow goodness of Fit test in Python

I have estimated a glm in python. How can I perform Hosmer-Lemeshow goodness

of fit test for this model in python?

Handling Database Exceptions gracefully

I have a executor service, where the thread runs 2-3 multiple process on the context object , and logs the state into the database, after each process is completed. Current code defines try and catch block after each logging statement , so that any database exceptions can be handled , and the worker moves to next process.

Is there a design pattern, or a more graceful way of doing this. The code has multiple try and catch blocks inside a single function which is not readable

how can Avoid to repeat same method

I work on a project with ASP.NET MVC and , my project architechture is N Layer . I have a method that name's is IsExists in all of Services. belowe I put two of them :

 bool IsExists(string title,Guid? parentId, Guid? id=null); // in service 1
 bool IsExists(string title, Guid? id = null);// in service n

is there a pattern to avoid repeat them ? I repeated same method by same doing work in all of services

Sample of implement :

  public bool IsExists(string title, Guid? parentId, Guid? id = default(Guid?))
    {
        Expression<Func<AssetGroup, bool>> ex = row => row.Title == title && row.ParentId == parentId;
        if (id.HasValue)
            ex = row => row.Id != id.Value;
        return _groups.Any(ex);

    }

*-I call IsExists Method in Create and Edit Methods before saveChanges

samedi 29 octobre 2016

Design Pattern to transform object to detailed version

Lets say I have an object Foo and I wish to transform it to a FooDetailed object. In order to do so, I have to augment certain aspects of Foo to have more detail. The details are fetched from a helper class. See below for an example:

public class Foo {
   String name;
   IBar bar;
}

public class ExtendedFoo {
   String name;
   IBar bar; // this has to be an extendedBar implementation.
}



public interface IIBar {
   public int getId();

   default int getType()
   { 
      return null;
   }
}

public class Bar implements IBar {
   public int getId();
}

public class ExtendedBar implements IBar {
   Bar bar;

   public int getId() { 
      bar.getId()); 
   }

   public int getType(){};
}

public static Helper {
   public static ExtendedBar convert(Bar bar) { 
      // makes some db calls to get type info to create an Extended Bar
   }
}

Is there a design pattern or some Builder esque approach to create a FooConverter that internall has all the info to convert a Foo->ExtendedFoo using the Helper etc where I can just do the following:

List<Foo> foos;

List<ExtendedFoo> extendedFoos = FooConverter.get().process(foos).transform();

Keeping in mind, that in the future, I may add to Foo other simple -> detailed transformations within Foo like a IBizz with a SimpleBiz and ExtendedBiz implementations

What is pseudo-decorator design pattern?

There are few mentions on the web about "pseudo decorator" pattern. For example:

So what we have is an example of how to extend sObject functionality in Apex with behavior at runtime, rather than through inheritance using a pseudo decorator pattern.

Source: http://ift.tt/2eTVOBe

Is there a formal definition for it? How is it different from normal decorator?

Role of polymorphism in the deployment of the strategy design pattern

What is the role of Polymorphism in the deployment of the strategy design pattern?I'm confused with this topic.

How to detect when pattern matcher find finds invalid input?

Matcher.find() looks for any expression specified in the regular expression given to the pattern, but how can we detect when an expression not specified in the regex?

    String input = "& 9 then %"
    Pattern pattern = Pattern.compile(\\(|then|def|then|[0-9]+);
    Matcher match = pattern.Matcher(input);

       while (match.find()) {
       ...
       ...
    }

The input has the symbol & and % which will not be detected, but I want to throw an exception when these symbols are not, so how can I detect that?

Combine builder pattern with some kind of validation

I've a builder pattern with some properties that I want to validate. If validation of a property is incorrect change the content of the property before builder pattern build the object.

Is there any other pattern to combine with builder pattern to achieve this? If no What is the best practice to do this.

Any help would be appreciated

Understanding Builder Pattern in C#

well i have a code sample of Builder Pattern like this

class Director
    {
        // Build a Product from several parts
        public void Construct(IBuilder builder)
        {
            builder.BuildPartA();
            builder.BuildPartB();
            builder.BuildPartB();
        }
    }

    interface IBuilder
    {
        void BuildPartA();
        void BuildPartB();
        Product GetResult();
    }

    class Builder1 : IBuilder
    {
        private Product product = new Product();
        public void BuildPartA()
        {
            product.Add("PartA ");
        }

        public void BuildPartB()
        {
            product.Add("PartB ");
        }

        public Product GetResult()
        {
            return product;
        }
    }

    class Builder2 : IBuilder
    {
        private Product product = new Product();
        public void BuildPartA()
        {
            product.Add("PartX ");
        }

        public void BuildPartB()
        {
            product.Add("PartY ");
        }

        public Product GetResult()
        {
            return product;
        }
    }

    class Product
    {
        List<string> parts = new List<string>();
        public void Add(string part)
        {
            parts.Add(part);
        }

        public void Display()
        {
            Console.WriteLine("\nProduct Parts -------");
            foreach (string part in parts)
                Console.Write(part);
            Console.WriteLine();
        }
    }

    public class Client
    {

        public static void Main()
        {
            // Create one director and two builders
            Director director = new Director();

            IBuilder b1 = new Builder1();
            IBuilder b2 = new Builder2();

            // Construct two products
            director.Construct(b1);
            Product p1 = b1.GetResult();
            p1.Display();

            director.Construct(b2);
            Product p2 = b2.GetResult();
            p2.Display();

            Console.Read();
        }
    }

Now, i have made some changes in the above code. Is the below code still represent a Builder Pattern?

class Director
    {
        public void Construct(IBuilder builder)
        {
            builder.BuildPartA();
            builder.BuildPartB();
            builder.GetResult();
        }
    }

    interface IBuilder
    {
        void BuildPartA();
        void BuildPartB();
        void GetResult();
    }

    class Builder1 : IBuilder
    {
        List<string> product = new List<string>();
        public void BuildPartA()
        {
            product.Add("PartA ");
        }

        public void BuildPartB()
        {
            product.Add("PartB ");
        }

        public void GetResult()
        {
            foreach (var p in product)
            {
                Console.WriteLine("the product created is :" + p);
            }
        }
    }

    class Builder2 : IBuilder
    {
        List<string> product = new List<string>();
        public void BuildPartA()
        {
            product.Add("PartX ");
        }

        public void BuildPartB()
        {
            product.Add("PartY ");
        }

        public void GetResult()
        {
            foreach (var p in product)
            {
                Console.WriteLine("the product created is :" + p);
            }
        }
    }
    public class Client
    {

        public static void Main()
        {

            Director director = new Director();
            IBuilder b1 = new Builder1();
            IBuilder b2 = new Builder2();
            director.Construct(b1);
            director.Construct(b2);

            Console.Read();
        }
    }

note:

I have removed the product class from the second sample code.

What is a good design pattern to avoid recalculations or double queries during a request?

When working with web based applications, usually query results (or the results of complex calculations that require substantial computing power) that don't change frequently would be cached in memory, or in a file based data store. When these results are likely to change for every request, but are consumed by a number of classes in your application, what would be the best way to go about caching this information for the duration of your request while keeping things SOLID?

The most straight forward solution I see, and what I'm implementing right now, is for every such instance checking if the result has already been calculated/retrieved, and if not, calculating it and storing it in a variable.

public function getSomething()
{
    if( ! isset($this->something) )
    {
        $this->something = $this->calculateSomething();
    }

return $this->something;
}

The problems I see with this approach are as follows:

  • I have to make sure that everywhere I require "something", I have access to the same object instance (or I could use static variables which would be even worse). This can be achieved by using dependency injection and making sure that every time I request an instance from that class, the same one is returned, but somehow I can't help but feel I am applying an okay solution to the wrong problem. Eventually my app will be filled with specific instance dependencies. I'm not even really sure if this is a bad thing or not, feel free to correct me.
  • My classes will be filled with these if statements that are all essentially doing the same thing. (checking if a variable has been set, and if not, setting it, and then return said variable.) Yikes!

I have spent the night looking for a better solution, but could not come up with anything but caching results for one request only (using the decorator pattern to keep my classes clean), which also felt wrong.

What would be an elegant way to solve this common problem and is there a known design pattern that I could implement to do so?

State pattern java

I am learning design pattern in java

I was doing through some of links.I am trying to design a washing machine by state pattern

I have a query regarding the implementation of state design pattern

public interface State {

   public void openLid();
   public void closeLid();
   public void start();
   public void stop();
   public void washing();
  } 

 public class Idle implements State{
 //implementing overidden methods
 .......

 }

 public class Washing implements State {
       //implementing overidden methods
       .......
  }


 public class WashingMachine {
   State state;

   public WashingMachine(State state) {
    this.state =  new Idle();
   }

  public State getState() {
    return state;
   }

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

 }

I want to know when switching between state between idle to washing the implementation there can be two ways which is saw over net

1.WashingMachine class implements State interface and switch state from Idle to washing or vice versa based on some condition

2.Idle and Washing class has WashingMachine as member variable.

Please any one can suggest I am a bit confused about the implementation part.

Why shouldn't services hold state?

Why is it recommended to design services that do not hold any state?

As a visualization, a somehow contrived example would be those two approaches:

1) Here the service maintains its state (often seen as bad practice)

$service->addSubjectForProcessing($subject1);
$service->addSubjectForProcessing($subject2);
$service->addSubjectForProcessing($subject3);
$service->processSubjects();

vs

2) Here the service does not maintain state (generally considered a good practice):

foreach([$subject1, $subject2, $subject3] as $subject) {
    $service->processSubject($subject);
}

Of course there are good pieces of software out there that use both approaches for their tasks, and this is not contested.

However, why is it often advised to avoid state in services?

Observer Pattern: Internal vs. External Registration

What is be the best choice to register an observer? I did not find anything on this subject. Mostly "push vs. pull" is discussed, but there are also a couple of options to register an observer.

public static void main(String[] args)
{
    Subject subject = new ConcreteSubject();
    // External registration
    Observer observerExternal = new ConcreteObserverExternal();
    subject.registerObserver(observerExternal);
    // Internal registration, option 1
    Observer observerInternal1 = new ConcreteObserverInternal1(subject);
    // Internal registration, option 2
    ConcreteObserverInternal2 observerInternal2 = new ConcreteObserverInternal2(subject);
}

interface Observer
{
    void inform();
}
class ConcreteObserverExternal implements Observer
{
    @Override
    public void inform()
    {
        // do sth.
    }
}
class ConcreteObserverInternal1 implements Observer
{
    public ConcreteObserverInternal1(Subject subject)
    {
        subject.registerObserver(this);
    }

    @Override
    public void inform()
    {
        // do sth.
    }
}
class ConcreteObserverInternal2
{
    public ConcreteObserverInternal2(Subject subject)
    {
        subject.registerObserver(() -> inform());
    }

    private void inform()
    {
        // do sth.
    }
}
interface Subject
{
    void registerObserver(Observer obs);

    void unregisterObserver(Observer obs);
}
class ConcreteSubject implements Subject
{
    @Override
    public void registerObserver(Observer obs)
    {
        // register
    }

    @Override
    public void unregisterObserver(Observer obs)
    {
        // unregister
    }

    private void foo()
    {
        // ...
        notifyObservers();
    }

    private void notifyObservers()
    {
        // notify observers
    }
}

Here are three cases I have in my code:

  • An observer is registered at program start and is never unregistered. In this case, all of the 3 options would be possible.
  • An observer is registered somewhere and needs to be unregistered when some external event occurs. The observer does not know about this external event and obviously it must be registered externally (option 1).
  • An observer is registered somewhere and needs to be unregistered when some external event occurs. The observer knows what happened, because it is also an observer of this external event. In this case, all of the 3 options would be possible.

In the case where all 3 options are possible, which one is the best from an OO and clean-code point of view?

Here is a list of some pros and cons I think each option has.

1. External registration

Pros:
- Less parameters in the constructor of the observer.
- Subject does not need to be abstracted to promote loose coupling.

Cons:
- One must not forget to register the observer in the client code.
- Client code is responsible for registration.

Neutral:
- The observer as an additional public method.
- Observer can be registered / unregistered by client code.

2. Internal registration, option 1: Concrete observer implements the Observer interface

Pros:
- Observer is responsible for registration.
- Registration cannot be forgotten, because one is forced to pass the Subject to the Observer's constructor.

Cons:
- One more parameter in the constructor of the observer.

Neutral:
- The observer as an additional public method.
- Observer can be registered / unregistered by client code.
- Observer can register / unregister itself.

3. Internal registration, option 2: Concrete observer does NOT implement the Observer interface

Pros:
- Observer is responsible for registration.
- Registration cannot be forgotten, because one is forced to pass the Subject to the Observer's constructor.
- Observer does not have and additional public method that could be abused by anything not related to "Subject notifying Observer".

Cons:
- One more parameter in the constructor of the observer.

Neutral:
- Observer can only register / unregister itself.

delegate or proxy or others

I want to handle different result by its type. And here is my codes public interface Handler { void handle(Result result) }

public class HandlerA implement Handler {
   public handle(Result result) {
      //do something
   }
}
public class HandlerB implement Handler {
   public handle(Result result) {
      //do something
   }
}
//....
public class HandlerImpl implement Handler {
  //..
    Handler A = new HandlerA();
    Handler B = new HandlerB();
  //..
  public void handle(Result result) {
    switch (result.getType()){
      case A:
       A.handle(result);
       break;
      case B:
       B.handle(result);
       break;
       //....
    }
  }
}

the service

public class Service{
   Handler handler = new HandlerImpl();
   public process() {
     //..
     Result result = .....
     handler.handle(result);
     //...
   }
}

But I feel wired about HandlerImpl for I think maybe it should not implement Handle. I have read some blogs about Proxy/Delefate design pattern, I didn't get some better implements. Anyone has some better suggestion about how to implment this funciton. Many thanks

vendredi 28 octobre 2016

Handling many states asynchronously in javascript

I am currently learning how to create bigger javascript projects and stumbled on an problem (Question below)

Here is a scenario:

var dialogOpen = 0;
var purchaseMode = 0;
var editMode = 0;
var currentlyEditing = 0;
var helper = 0;

I mean just an example of some flags that could be used for some purpose, all async of course. My question is, is there a better way to handle a crazy amount of states that need to be handled without having to spread state changes all over my application in an inconsistent manner?

if (editMode) { 
    editMode = 1;
   // Let the user edit all text
} else {
   editMode = 0;
}


if (target == purchaseButton) {
   purchaseMode = 1;
}

if (purchaseMode) {
   // allow purchases
}

I mean this is a small example, its harmless but I hope you understand the predicament im in. Imagine a software with 10.000 lines of code. Oh crap that would be pretty evil and extremely hard to maintain. What are some best practices to solve such a problem for larger scale programs?

BizTalk file/ message splitting

I have a requirement in which I have to split the file contents based on value of the first column of the comma separated values in the source file.
Number of files to be generated in output depends on the number of unique values in the first column.

Eg:

FileName.txt
Code001,value11,value12,value13,value14
Code002,value21,value22,value23,value24
Code003,value31,value32,value33,value34
Code001,value15,value16,value17,value14
Code003,value37,value38,value39,value31

Output has to be number of files as the unique values in first column of the file content.

Ex Output: It should be 3 seperate files with name and contents as below

Code001.txt
Code001,value11,value12,value13,value14
Code001,value15,value16,value17,value14

Code002.txt
Code002,value21,value22,value23,value24

Code003.txt
Code003,value31,value32,value33,value34
Code003,value37,value38,value39,value31

Duplicate conditional statements in the factory

How to get rid of them? I'm wondering if there is a pattern or something that addresses this problem. Basically I need to instantiate a concrete child class based on the type property of another class, i.e. if type=1 then new A, else if type=2 then new B etc. I've ended up with this kind of a factory in the class with the type property:

/**
 * Get a ticket decorator based on the ticket type
 * @return ReferralService\TicketDecorator
 * @throws Exception
 */
public function getTicketDecorator(): ReferralService\TicketDecorator
{
    if (!$this->code) {
        throw new Exception("Couldn't create a ticket wrapper based on the type without a code");
    }

    /**
     * The debug service
     * @var Debug\Service $debugService
     */
    $debugService = app(Debug\Service::class);
    $debugService->setDebug(config('referral.debug'));

    switch ($this->code) {
        case self::TYPE_FEEDBACK:
            return new ReferralService\TicketDecorator\FeedbackTicketDecorator($debugService);
            break;
        case self::TYPE_BIRTHDAY:
            return new ReferralService\TicketDecorator\BirthdayTicketDecorator($debugService);
            break;
        case self::TYPE_NEW_PARTNER:
            return new ReferralService\TicketDecorator\PartnerTicketDecorator($debugService);
            break;
        default:
            throw new Exception(sprintf("Couldn't instantiate a ticket decorator based on the %s type", $this->code));

    }
}

/**
 * Instantiate a private page based on the ticket type
 * @param ReferralService\Service $service
 * @param Referrer $referrer
 * @param Ticket $ticket
 * @return ReferralService\Page\PrivatePage
 * @throws Exception
 */
public function getPrivatePage(ReferralService\Service $service, Referrer $referrer, Ticket $ticket): ReferralService\Page\PrivatePage
{
    if (!$this->code) {
        throw new Exception("Couldn't create a private page based on the type without a code");
    }

    switch ($this->code) {
        case self::TYPE_FEEDBACK:
            return new ReferralService\Page\PrivatePage\EmailReference($this->service, $referrer, $ticket);
            break;
        case self::TYPE_BIRTHDAY:
            return new ReferralService\Page\PrivatePage\Birthday($this->service, $referrer, $ticket);
            break;
        case self::TYPE_NEW_PARTNER:
            return new ReferralService\Page\PrivatePage\Partner($this->service, $referrer, $ticket);
            break;
        default:
            throw new Exception(sprintf("Could't find a page for the type", $this->code));
    }
}

Every method in the factory tests the type field, this looks clumsy for me. I thought to have a separate child class for every type and use factory methods without conditional statements, but I can't do so with Laravel models.

Access object context from prototype functions JavaScript

I am not professional developer, I have problems with object scope.

Here is my class code

// Table list module
        function DynamicItemList(data, settings, fields) {
            if (!(this instanceof DynamicItemList)) {
                return new DynamicItemList(data, settings, fields);
            }
            this.data = data;
            this.settings = settings;
            this.fields = fields;
            this.dataSet = {
                "Result": "OK",
                "Records": this.data ? JSON.parse(this.data) : []
            };
            this.items = this.dataSet["Records"];
            this.generateId = makeIdCounter(findMaxInArray(this.dataSet["Records"], "id") + 1);
            this.dataHiddenInput = $(this.settings["hidden-input"]);
        }

        DynamicItemList.RESULT_OK = {"Result": "OK"};
        DynamicItemList.RESULT_ERROR = {"Result": "Error", "Message": "Error occurred"};
        DynamicItemList.prototype = (function () {
            var _self = this;
            var fetchItemsList = function (postData, jtParams) {
                return _self.dataSet;
            };
            var createItem = function (item) {
                item = parseQueryString(item);
                item.id = this.generateId();
                _self.items.push(item);
                return {
                    "Result": "OK",
                    "Record": item
                }
            };
            var removeItem = function (postData) {
                _self.items = removeFromArrayByPropertyValue(_self.items, "id", postData.id);
                _self.dataSet["Records"] = _self.items;
                _self.generateId = makeIdCounter(findMaxInArray(_self.dataSet["Records"], "id") + 1);
                return DynamicItemList.RESULT_OK;
            };
            return {
                setupTable: function () {
                    $(_self.settings["table-container"]).jtable({
                        title: _self.settings['title'],
                        actions: {
                            listAction: fetchItemsList,
                            deleteAction: removeItem
                        },
                        fields: _self.fields
                    });
                },
                load: function () {
                    $(_self.settings['table-container']).jtable('load');
                },
                submit: function () {
                    _self.dataHiddenInput.val(JSON.stringify(_self.dataSet["Records"]));
                }
            };
        })();

I have problems with accessing object fields.

I tried to use self to maintain calling scope. But because it is initialized firstly from global scope, I get Window object saved in _self.

Without _self just with this it also doesn't work . Because as I can guess my functions fetchItemsList are called from the jTable context and than this points to Window object, so I get error undefined.

I have tried different ways, but none of them work.

Please suggest how can I solve this problem.

Thx.

jeudi 27 octobre 2016

Using Autofac to switch a concrete implemetation of an abstract factory

I am humbling with a problem related to AutoFac and the the abstract factory pattern. My Example is a a service to use an IRepositoryFactory to create a Repository based on JSON or InMemory related to the user input.

// Abstract Factory
public interface IRepositoryFactory{
    IRepository Create(string databaseIdentifier);
}

// JSON
public class JsonRepositoryFactory{
    public IRepository Create(string databaseIdentifier){
        return new JsonRepository(databaseIdentifier); 
    }
}

// InMemory
public class MemoryRepository{
    public IRepository Create(string databaseIdentifier){
        return new MemoryRepository(databaseIdentifier);
    }
}

The Service should pull the Factory by Constructor Injection.

public interface IShopService{
     public string Name {get;}
} 

public class BeerShop : IShopService {
     public string Name {get; private set;}
     private readonly IRepository _repository;

     public BeerShop(IRepositoryFactory repositoryFactory){
         Name = "beershop";
         _repository = repositoryFactory.Create(Name);
     } 
}

So far I am good with this. But the initialization is not my favorite.

var builder = new ContainerBuilder();
var userInput = ReadInput();

if(userInput = "json")
    builder.RegisterType<IRepositoryFactory>().As<JsonRepositoryFactory>();
else
    builder.RegisterType<IRepositoryFactory>().As<MemoryRepositoryFactory>();

builder.RegisterType<IShopService>.As<BeerShop>();

var container = builder.build();

[...]    

var service = container.Resolve<IShoptService>();
// and so on ...

Is this the right approach to solve it? I am not convinced by my own design because it forces the user input before the initialization of the container. What if the user has to change the Repository while runtime? Is the abstract factory pattern the right tool to solve this problem?

Stateless Factory with EJB

I have a requirement to get pdf documents from my system. I'm using Apache Fop for this - and this library is using 2 files to generate pdf - xsl file with structure and styling and xml with data. So I'm getting xsl file from web resources, but now I need to generate xml with data from database. I tried this solution: I have this interface:

public interface PrintableDocument {
    Object getJaxBOjbect(Long personId);
}

That's one of the stateless bean to get object, I need 10 more beans like this to get different data for different documents.

@Stateless
@PrintableDocumentOneQualifier
public class PrintableDocumentOne implements PrintableDocument {

    @Inject
    private SomeRepository repository;

    public Object getJaxBOjbect(Long personId) {
    // Getting information from database
    // formulating Object with data and returning it
    }
}

So now I want to create Factory like this one:

@Stateless
@LocalBean
public class PrintableDocumentsFactory {

    @Inject
    @PrintableDocumentOneQualifier
    private PrintableDocument printableDocumentOne;

    @Inject
    @PrintableDocumentTwoQualifier
    private PrintableDocument printableDocumentTwo;

    private Map<String, PrintableDocument> map = new HashMap<>();

    public void init() {
        map.put("one", printableDocumentOne);
        map.put("two", printableDocumentTwo);
    }

    public PrintableDocument getPrintableDocument(String type) {
        return map.get(type);
    }

}

And on the service bean I want to use this factory:

@Stateless
@Local(DocumentService.class)
public class DocumentServiceBean {

    @Inject
    private PrintableDocumentsFactory factory;

    public byte[] getPdf(InputStream xsl, Long id, String type) {
        PrintableDocument printableDocument = 
             factory.getPrintableDocument(type);
        Object jaxBOject = printableDocument.getJaxBObject(id);
        //Use this object to get pdf and return it to web controller.
    }

}

But now I'm getting null from getPrintableDocument from factory. I think the problem is that I need stateless beans, and they are getting picked back to EJB container, when getPrintableDocument method ends. So my question is: how can I manage this kind of situation?

Understanding Decorator Design Pattern in C#

I just started to learn Decorator Design Pattern, unfortunately i had to go through various refrences to understand the Decorator pattern in a better manner which led me in great confusion. so, as far as my understanding is concern, i believe this is a decorator pattern

interface IComponent
    {
        void Operation();
    }
    class Component : IComponent
    {
        public void Operation()
        {
            Console.WriteLine("I am walking ");
        }
    }
    class DecoratorA : IComponent
    {
        IComponent component;
        public DecoratorA(IComponent c)
        {
            component = c;
        }
        public void Operation()
        {
            component.Operation();
            Console.WriteLine("in the rain");
        }
    }
    class DecoratorB : IComponent
    {
        IComponent component;
        public DecoratorB(IComponent c)
        {
            component = c;
        }
        public void Operation()
        {
            component.Operation();
            Console.WriteLine("with an umbrella");
        }
    }
    class Client
    {
        static void Main()
        {
            IComponent component = new Component();
            component.Operation();

            DecoratorA decoratorA = new DecoratorA(new Component());
            component.Operation();

            DecoratorB decoratorB = new DecoratorB(new Component());
            component.Operation();

            Console.Read();
        }
    }

but can the below code also be Decorator Pattern?

class Photo
{
    public void Draw()
    {
        Console.WriteLine("draw a photo");
    }
}
class BorderedPhoto : Photo
{
    public void drawBorder()
    {
        Console.WriteLine("draw a border photo");
    }
}
class FramePhoto : BorderedPhoto
{
    public void frame()
    {
        Console.WriteLine("frame the photo");
    }
}
class Client
{
    static void Main()
    {
        Photo p = new Photo();
        p.Draw();

        BorderedPhoto b = new BorderedPhoto();
        b.Draw();
        b.drawBorder();

        FramePhoto f = new FramePhoto();
        f.Draw();
        f.drawBorder();
        f.frame();
    }
}

My Understanding

from the second example given by me, we can call all the three methods, but from the first example i wont be able to get access to all the three methods by creating a single object.

Symfony 2 - Anti pattern?

I've been asking myself why Symfony pass the DI Container to controllers? A DI container isn't supposed to be used only on the Composition Root (AppKernel)?

Design Pattern for PHP that uses 3rd Party Template Engine

I am familiar with the MVC design pattern, but I am curious what pattern this would be considered.

A project I am looking at uses the Tiny but Strong (TBS) template engine and PHP for the back-end. For every PHP file there is a TBS template. The PHP is not OOP, nor employs any functions, so looks just procedural. (It sucks as I have been tasked with updating it and there is duplicate code in every single file... there is like 100 files).The PHP files do both the communicating with the database and dictating which TBS template to use.

Not sure if it would just be MV, CV, or if it is just procedural PHP with a template engine.

Design pattern for storing customer specific requirements

tldr; Looking for a design pattern that is good at handling a variety of requirements customers have on database fields.

Been looking and have not come across anyone with a similar issue, but if I missed one please let me know! Also, I suspect I may be either over-complicating the issue, or trying to do too much at once. Sorry for the wall of text incoming.

Okay, so I am designing a new application in C# for a company I have worked with in the past. I am writing this application to replace the VB6 application they have in place now. This new application's scope will be for the initial information gathering phase.

The company is for roadside assistance; trucks breaking down for companies with big rig trucks. They assist hundreds of customers, and each customer has its own requirements. The company bends over backwards for each customer, and therefore I need to come up with a manageable design to handle these customer specifications. All previously developed applications had in-line "if else" logic for literally hundreds of customers and I still have nightmares about it.

Example:

A user will take a phone call from a customer and collect information, which they input into this application. They will be calling to report an event such as a flat tire. Sometimes the person calling in is the driver. Other times the driver has called the company they work for, and a representative calls to report the incident and request help. Let's focus on a few pieces of information so I may paint the picture.

  1. Customer Reference Number
  2. Odometer
  3. List item

Not every customer requires a reference number. Some customers require a reference number adhere to a certain mask, for example "Reference Number must start with BD-XXX-XXXX-XX" or something similar. Other customers don't even have reference numbers, so there is no point capturing this data (it doesn't exist).

Some customers require an odometer reading of the mileage, some don't.

So you might begin to see my issue. Customer A doesn't need a reference number. Customer B needs a reference number. It's not as simple as NOT NULL vs NULL though, because B also needs their reference number to match an input mask.

Types of requirements:

  • Field value must be Greater than/Less than X
  • Field must adhere to Input Mask
  • Field Not collected at all
  • Field Required
  • Field Optional
  • Field value dictates whether other information must be/must not be collected. If one specific field is null, another becomes required

I would like to store customer requirements in the database (SQL) and perhaps be able to load a class with this data that will be able to handle the requirements for the UI portion of the application.

Components of the project are required to be: C# Windows app WCF Service for data (will be used between multiple applications & web) SQL Server 2012

Regex/Java Pattern : Finding occurrences of a sub string in a string with fault tolerance of 1 or more characters

How to find occurrences of a sub string in a string with fault tolerance of 1 or more characters?

Example.

Source : John Smith

With Fault tolerance 1 Character:

  • Sub String 1: Jahn should result to 1
  • Sub String 2: Jonn should result to 1
  • Sub String 3: Johm should result to 1
  • Sub String 4: johm should result to 1 //ignore case

With Fault tolerance 2 Character:

  • Sub String 1: Jann should result to 1
  • Sub String 2: Joom should result to 1 and etc...

Any Regex Solution ?? Java Pattern Matching? In this case, a method like this

int countOccurrenceWithFaultTolerance(String source, String subString, int faultTolerance) {
    // TODO
    return 0;
}

Thanks in Advance.

Is there someway to restrict the access to a member of an object only to the object that owns it by composition?

I really feel like there must be a way around this.

Imagine I have a large number of objects as components of an owner class. I want to offer easy access to the clients of this owner class to its members, so I make all those objects public. Each of those objects also have all their members public. But one member of the components should not be accessible to the clients of their owner, only by their owner itself:

public class ComponentObject
{
    public int int_field;
    public float float_field;
    public Object object_field;

    public Object public_method1()
    {
        //something;
    }

    public Object public_method2()
    {
        //something;
    }

    public Object restricted_to_owner_only()
    {
        //something;
    }
}

//all clients of Owner should be able to access all the members of its components, except
//restricted_to_owner_only, which only Owner should be able to access
public class Owner
{
    public ComponentObject component1;
    public ComponentObject component2;
    public ComponentObject component3;
    //... lots of others
    public ComponentObject component300;
}

Is there a way to achieve this? Note that any class from any package can own a ComponentObject, so using package level visibility at restricted_to_owner_only doesn't seem to be an option. ComponentObject is like a utility class, reusable in other applications.

How to remove smell from a pluggable DAL

I am working with an application that is composed of several different, disconnected, components and each piece has a dependency on up to three different Data Stores (SQL Server, Doc Storage, BLOB Storage).

The SQL Server connection details are always known at design / deployment time, however the Doc and BLOB storage (both currently in Azure) details are sometimes provided at design time and sometimes provided at run time depending on the specific component I am working with. Since there is consistent cost in using Azure my requirement is to build a pluggable data access layer that, in the event that the organization wanted to move away from Azure, there would be minimal effort in implementing a new data provider. While the solution that I have come up fulfills the requirement, there are some code smells that I am looking to remove, but I am unsure on how I would achieve them (in the cleanest manner possible). Below is a brief explanation of the structure that I have.

Data Mappers

public interface IBaseProvider
{
    void Configure(IDictionary<string, object> configValues);
}

public interface ISqlProvider : IBaseProvider
{
    ///CRUD omitted for clarity
}

public interface IBlobProvider : IBaseProvider
{
    ///CRUD omitted for clarity
}

public interface IDocProvider : IBaseProvider
{
    ///CRUD omitted for clarity
}

public class SqlDataProvider : ISqlProvider
{
     public void Configure(IDictionary<string, object> configValues)
     {
           //Do stuff
     }
}

public class DocDataProvider : IDocProvider
{
     public void Configure(IDictionary<string, object> configValues)
     {
           //Do stuff
     }
}

public class BlobDataProvider : IBlobProvider
{
     public void Configure(IDictionary<string, object> configValues)
     {
           //Do stuff
     }
}

The smell here is obviously Configure(IDictionary<string, object> configValues) and the reason for it is because:

  • My implementation reaches into the configuration system to determine the type that I should be using
  • In the event that I was providing connection details at runtime, I needed a way to pass those details into the provider class while pulling its type from the configuration system.

To actually provide instances of these objects to the applications, I wrote a Service Locator as such

Service Locator

public interface IProviderLocator
{
    T CreateInstance<T>(IDictionary<string, object> configValues) where T : IBaseProvider;

}

public sealed class ProviderLocator : IProviderLocator
{
     protected IDictionary<string, object> configValues;
     public T CreateInstance<T>(IDictionary<string, object> configurationValues) where T : IBaseProvider
    {
        configValues = configurationValues;
        return Initialize<T>();
    }

    private T Initialize<T>() where T : IBaseProvider
    {
        //reach into the configuration system to get providerType
        var provider = (T)Activator.CreateInstance(providerType);
        provider.Configure(configValues);

        return provider;
    }
}

The non-DI way to then get a concrete provider could then be something like

var database = new ProviderLocator().CreateInstance<ISqlProvider>(null);

The Service Locator implements both the locator pattern and provider "pattern" (someone check to see that Mark Seemann hasn't had a stroke ;] ), but despite the compelling arguments that Mark makes against these patterns here and here I am not sure how to come off of this implementation.

The quick answer here is to probably use an Abstract Factory and to remove the dependency on the configuration system.

Abstract Factory

public interface IProviderFactory<T>
{
    T CreateInstance<T>(IDictionary<string, object> configValues)
}

public sealed class SqlProviderFactory : IProviderFactory<ISqlProvider>
{
     public T CreateInstance<T>(IDictionary<string, object> configurationValues)
    {
         return new SqlDataProvider(configurationValues);
    }
}

My two biggest concerns against implementing this pattern are:

  • My classes will now have up 3 factory dependencies (one for each data provider); this isn't a huge concern since my DI container will build my object graph but it does add a certain amount of clutter to the class.
  • The Abstract Factory violates SOLID if and when I have to change the concrete provider (e.g. SqlDataProvider becomes AzureDataProvider)

TL;DR / Overall Question

My question is: does a pattern exist (or can one of the ones above be modified) that allows me the flexibility I am looking for that isn't as smelly while still being DI friendly?

Avoid If-else code smell with creation of objects which depend upon specific conditions

Is there a better way to deal with an instanciation of an object (Product) which depends upon another object type (Condition) than using if-else paired with instanceof as the following code shows?

import java.util.ArrayList;
import java.util.List;

abstract class AbstractProduct {
    private AbstractCondition condition;
    public AbstractProduct(AbstractCondition condition) {
        this.condition = condition;
    }
    public abstract void doSomething();
}

class ProductA extends AbstractProduct {
    AbstractCondition condition;
    public ProductA(AbstractCondition condition) {
        super(condition);
    }

    @Override
    public void doSomething() {
        System.out.println("I'm Product A");
    }
}

class ProductB extends AbstractProduct {    
    public ProductB(AbstractCondition condition) {
        super(condition);
    }   

    @Override
    public void doSomething() {
        System.out.println("I'm Product B");
    }
}

class AbstractCondition { }

class ConditionA extends AbstractCondition { }

class ConditionB extends AbstractCondition { }

public class Try {
    public static void main(String[] args) {
        List<AbstractCondition> conditions = new ArrayList<AbstractCondition>();
        List<AbstractProduct> products = new ArrayList<AbstractProduct>();

        conditions.add(new ConditionA());               
        conditions.add(new ConditionB());               
        conditions.add(new ConditionB());               
        conditions.add(new ConditionA());

        for (AbstractCondition c : conditions) {
            tryDoSomething(c);
        }
    }

    public static void tryDoSomething(AbstractCondition condition) {
        AbstractProduct product = null;
        if (condition instanceof ConditionA) {
            product = new ProductA(condition);
        } else if (condition instanceof ConditionB) {
            product = new ProductB(condition);
        }
        product.doSomething();
    }
}

The difference with the code above of my real code is: I have NO direct control over AbstractCondition and its subtypes (as they are in a library), but the creation of a concrete subtype of AbstractProduct depends on the concrete condition.

My goal being: try to avoid the if-else code smell in tryDoSomething().

I would also like to avoid reflection because it feels like cheating and I do think it's not an elegant, clean and readable solution.

In other words, I would like to tackle the problem just with good OOP principles (e.g. exploiting polymorphism) and pheraps some design patterns (which apparently I don't know in this specific case).

How many times grep loops over file1 when patterns are provided in a separate file2 ( -f option )

When using grep with the -f option, does the grep get executed as many times as there are patterns in the -f pattern.txt ? Is

grep -f pattern.txt myfile.txt

faster than

grep -e "one" -e "two" -e "three" myfile.txt

if pattern.txt contains

one
two
three

?

how do i align a multidimensional array?

import java.io.PrintStream;

public class JavaApplication16 {

    public static void main(String[] args) {
        // Create 2-dimensional array.
        String[][] values = new String[12][4];
        String format;
        format = "|%1$-30s|%2$-10s|%3$-20s|\n";

        // Assign three elements in it.
        values[0][0] = "Mnd";
        values[0][1] = "Stroom";
        values[0][2] = "Water";
        values[0][3] = "Telefoon";
        values[1][0] = "Jan";
        values[1][1] = "1000";
        values[1][2] = "1500";
        values[2][0] = "Feb";
        values[3][0] = "Mrt";

        values[3][2] = "3";

        // Loop over top-level arrays.
        for (String[] sub : values) {
            // Loop and display sub-arrays.
            for (String sub1 : sub) {
                PrintStream printf;
                printf = System.out.printf(sub1 + " ");
            }
            System.out.println();
        }
    }
}

Output is:

Mnd Stroom Water Telefoon
Jan 1000 1500 null
Feb null null null
Mrt null 3 null
null null null null
null null null null
null null null null
null null null null
null null null null
null null null null
null null null null
null null null null

Allow 10 or 20 characters in a form input

In a form input, where the user fills a sequence of characters (from a barcode scanner), I want to apply a form control where the input can accept only 10 or 20 length sequence of characters.

If I wanted just one of them, lets say 10 I could use:

<input type="text" pattern=".{10,10}" name="barcode" />

Is there a way to enable the above control? I tried

<input type="text" pattern=".{10,10}+.{20,20}" name="barcode" /> 

but it didn't work..

Java bean validation uppercase letters with range

I have a little issue with pattern for java bean validation. I have a pattern for my variable inside java class

@Pattern(regexp = "[\\p{Upper}]+[\\p{Space}]?[\\p{Upper}]+[\\p{Punct}]?[\\p{Upper}]+[\\p{Digit}]?.", message = "")

private String name;

And actually it's working, but now I have to add a range {0,32} to uppercase words. When I added [A-Z]{0,32} it breaks down

The name should fit values below

  1. PROFILE - true
  2. P - true
  3. PRO - true
  4. PROFILEPROFILEPROFILEPROFILEPROF - true
  5. PROFILEPROFILEPROFILEPROFILEPROFI - false
  6. profilename - false
  7. PROFILE1 - true
  8. PROFILE100 - true
  9. PROFILE1000 - true
  10. PROFILE1000000 - true
  11. 1111 - false
  12. PROFILEPROFILE123456789PROFILE123 - false
  13. profile_name - false
  14. *^^@ - false
  15. PROFILE NAME - true
  16. PROFILE_NAME - true
  17. PROFILE. - true
  18. &)12p - false
  19. 11PROFILE - true
  20. 1234PROFILE - true
  21. $%#PROFILE - true
  22. nothing - false

Is the -Impl suffix a legitimate naming convention for a Hook method in Java?

I was going over some old code and found the following naming convention at a template method implementation.

// TEMPLATE METHOD
// Check condition and fail fast if condition is met.
// Otherwise call the hook method (to be implemented by subclasses).
@Override
public boolean accept(String text) {
    if (condition) {
        return false;
    }

    // call to the hook method. Each subclass implements its own logic
    return acceptImpl(text);
}

// HOOK METHOD
protected abstract boolean acceptImpl(String text);

I would expect the hook method to be named doAccept() or acceptHook() instead of acceptImpl().

Is the "-Impl" suffix used in practice for hook methods? or Is it a confusing naming practice?

Why does 'visitor pattern' asks each class to inherit VisitorHost interface class which has accept() function?

I am learning a design pattern, vistor pattern, in c++.

At first, I copy my two practice codes below. First one is "my test code", and the second one is a simplified code of "normal visitor pattern" in my text book. I would like you to read the first code but the second one is just a reference code of normal visitor pattern.

My question is why visitor pattern asks each class to inherit VisitorsHostInterface class which has virtual function, accept(); please refer to the second code, "normal visitor pattern", below if necessary. In my understanding, it is not necessary to use accept() function to scan all instances, like the first code, "my test code". I suppose "my test code" is simpler than "normal visitor pattern". Please tell me the reason why visitor pattern asks accept() function to each class? Thank you very much.

(1) my test code

class ClassD;

class ClassC {
public:
    ClassC(int new_value, ClassD* new_next_object) : value_(new_value), next_object_(new_next_object) {};
    void print() { std::cout << "ClassC value_ = " << value_ << std::endl; }
    int value() { return value_; }
    std::shared_ptr<ClassD> next_object(void) { return next_object_; }
private:
    int value_=0;
    std::shared_ptr<ClassD> next_object_;
};

class ClassD {
public:
    ClassD(int new_value, ClassC* new_next_object) : value_(new_value), next_object_(new_next_object) {};
    void print() { std::cout << "ClassD value_ = " << value_ << std::endl; }
    int value() { return value_; }
    std::shared_ptr<ClassC> next_object(void) { return next_object_; }
private:
    int value_=0;
    std::shared_ptr<ClassC> next_object_;
};

class VisitorFuncInterface {
public:
    virtual ~VisitorFuncInterface() = default;
    virtual void visit(ClassC* obj) = 0;
    virtual void visit(ClassD* obj) = 0;
};

class VisitorFunc : public VisitorFuncInterface {
public:
    virtual ~VisitorFunc() = default;
    void visit(ClassC* obj) {
        if (obj) {
            obj->print();
            this->visit(obj->next_object().get());
        }
    }
    void visit(ClassD* obj) {
        if (obj) {
            obj->print();
            this->visit(obj->next_object().get());
        }
    }
};

void test_visitor_without_host(void) {

    ClassD* d0 = new ClassD(0, nullptr);
    ClassC* c0 = new ClassC(1, d0);
    ClassD* d1 = new ClassD(2, c0);

    VisitorFunc v;
    v.visit(d1);

    delete d1;

}

The result of test_visitor_without_host() is following,

ClassD value_ = 2
ClassC value_ = 1
ClassD value_ = 0

(2) normal visitor pattern code

class ClassA;
class ClassB;

class VisitorInterface {
public:
    virtual ~VisitorInterface() = default;
    virtual void visit(ClassA* obj) = 0;
    virtual void visit(ClassB* obj) = 0;
};

class VisitorsHostInterface {  // = visitor's host
public:
    virtual ~VisitorsHostInterface() = default;
    virtual void accept(VisitorInterface& v) = 0;
};

class VisitorsHost : public VisitorsHostInterface {
public:
    virtual ~VisitorsHost();
    void accept(VisitorInterface& v) {};
};

class ClassA : public VisitorsHostInterface {
public:
    ClassA(int new_value, ClassB* new_next_object) : value_(new_value), next_object_(new_next_object) {};
    void print() { std::cout << "ClassA value_ = " << value_ << std::endl; }
    int value() { return value_; }
    std::shared_ptr<ClassB> next_object(void) { return next_object_; }
    void accept(VisitorInterface& v) { v.visit(this); };
private:
    int value_=0;
    std::shared_ptr<ClassB> next_object_;
};

class ClassB : public VisitorsHostInterface {
public:
    ClassB(int new_value, ClassA* new_next_object) : value_(new_value), next_object_(new_next_object) {};
    void print() { std::cout << "ClassB value_ = " << value_ << std::endl; }
    int value() { return value_; }
    std::shared_ptr<ClassA> next_object(void) { return next_object_; }
    void accept(VisitorInterface& v) { v.visit(this); };
private:
    int value_=0;
    std::shared_ptr<ClassA> next_object_;
};

class Visitor : public VisitorInterface {
public:
    virtual ~Visitor() = default;
    void visit(ClassA* obj) {
        if (obj) {
            obj->print();
            this->visit(obj->next_object().get());
        }
    }
    void visit(ClassB* obj) {
        if (obj) {
            obj->print();
            this->visit(obj->next_object().get());
        }
    }
};

void test_visitor(void) {

    ClassB* b0 = new ClassB(0, nullptr);
    ClassA* a0 = new ClassA(1, b0);
    ClassB* b1 = new ClassB(2, a0);

    Visitor v;

    b1->accept(v);

    delete b1;

}

The result of test_visitor() is following,

ClassB value_ = 2
ClassA value_ = 1
ClassB value_ = 0

mercredi 26 octobre 2016

How can i use simple aspect oriented concept to handle exception handling without postsharp?

i want to use AOP to handle my error exception in Console application. ( it is not MVC i used attribute vase programing to handle errors in mvc but this is console app) My code below: ( if error occurs ,it should throw an error yo my attribute side code )

 [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class HandleError : Attribute
{
     public HandleError(string description)
    {
        try
        {
            this.Description = description;
        }
        catch (Exception)
        {

            throw;
        }

    }
    public string Description { get; set; }


}

this will call from my method :

   [HandleError("Error occurs here")]
    public static void MyMethod(string data)
    {
        throw new Exception();

Actually; i want to use AOP to handle exceptions inside my method. i have to call attributes if it error occurs. But How? ( please don't offer postsharp, it needs money. but i am open for opensource also)By the way; why it is not easy ,i don't understand.

How to better design a program with extended and specific methods being called

Its hard to phrase what I want in the title but here's what I'm trying to build:

I created a series of StaticAPI classes for every webservice I want to consume and they all implement the Storable interface which requires 2 methods: getInputStream() and getUniqueIdentifier(). So every StaticAPI class has a standard method to call its particular webservice but they also have each their own getInputStream(Params...) methods for the specific parameters each one could request:

interface Storable {
    InputStream getInputStream();
    String getUniqueIdentifier()
}

abstract class StaticAPI implements Storable {}

class TireAPI extends StaticAPI {
    InputStream getInputStream() {
        return getInputStream("16");
    }

    InputStream getInputStream(String diameter) {
        return HTTPRequest.request("tire/", diameter);
    }

    String getUniqueIdentifier() {
        return "tire_service_default";
    }

    String getUniqueIdentifier(String diameter) {
        return "tire_service_"+diameter;
    }
}

class WindShieldAPI extends StaticAPI {
    InputStream getInputStream() {
        return getInputStream("fume", "123");
    }

    InputStream getInputStream(String tone, String size) {
        return HTTPRequest.request("wind-shield/", String[] {tone, size});
    }

    String getUniqueIdentifier() {
        return "wind_shield_service_default";
    }

    String getUniqueIdentifier(String tone, String size) {
        return "wind_shield_service_"+tone+"_"+size;
    }
}

I then created a DataDriver interface that allows me to create several different methods of storing the data from these apis: FileSystemDataDriver, SQLDataDriver, CouchDBDataDriver and so on. The DataDriver interface expects a Storable object to be able to call the getInputStream() method but it also expects a uniqueIdentifier/inputStream to be able to store data coming from those specific methods with multiple parameters:

interface DataDriver {
    boolean exists(Storable api);
    boolean exists(String uniqueIdentifier);
    InputStream read(Storable api);
    InputStream read(String uniqueIdentifier);
    void save(Storable api)
    void save(String uniqueIdentifier, InputStream inputStream);
}

class FileSystemDataDriver implement DataDriver {

    Path directory;

    FileSystemDataDriver(Path directory) {
        this.directory = directory;
    }

    boolean exists(Storable api) {
        exists(api.getUniqueIdentifier());
    }

    boolean exists(String identifier) {
        return Files.exists(directory.resolve(identifier));
    }

    InputStream read(Storable api) {
        return read(api.getUniqueIdentifier());
    }

    InputStream read(String uniqueIdentifier) {
        return Files.newInputStream(directory.resolve(uniqueIdentifier));
    } 

    void save(Storable api) {
        save(api.getUniqueIdentifier(), api.getInputStream());
    }

    void save(String uniqueIdentifier, InputStream inputStream) {
        FileUtils.copyInputStreamToFile(inputStream, directory.resolve(uniqueIdentifier).toFile());
    }
}

So all of this code is just to explain what I dont think is looking too good in my code. I created another class to abstract the download and storage of all these apis. The idea is for the entire program to only call static methods from the DataStore class and this class will make sure that if I dont have the data stored and accessible through a DataDriver that it is downloaded and stored before it is returned:

class DataStore {

    DataDriver dataDriver;

    DataStore(DataDriver dataDriver) {
        this.dataDriver = dataDriver;
    }

    static InputStream getTire() {
        StaticAPI tireAPI = new TireAPI();
        if(!dataDriver.exists(tireAPI))
            dataDriver.save(tireAPI);
        return dataDriver.read(tireAPI);
    }

    static InputStream getTire(String diameter) {
        TireAPI tireAPI = new TireAPI();
        if(!dataDriver.exists(tireAPI.getUniqueIdentifier(diameter)))
            dataDriver.save(tireAPI.getUniqueIdentifier(diameter), tireAPI.getInputStream(diameter));
        return dataDriver.read(tireAPI.getUniqueIdentifier(diameter));
    }

    static InputStream getWindShield() {
        StaticAPI windShieldAPI = new WindShieldAPI();
        if(!dataDriver.exists(windShieldAPI))
            dataDriver.save(windShieldAPI);
        return dataDriver.read(windShieldAPI);
    }

    static InputStream getTire(String tone, String size) {
        WindShieldAPI windShieldAPI = new WindShieldAPI();
        if(!dataDriver.exists(windShieldAPI.getUniqueIdentifier(tone, size)))
            dataDriver.save(windShieldAPI.getUniqueIdentifier(tone, size), windShieldAPI.getInputStream(tone, size));
        return dataDriver.read(windShieldAPI.getUniqueIdentifier(tone, size));
    }
}

So what is really bothering me here is that I have to always use getUniqueIdentifier(Params...) and getInputStream(Params...) to store the data from an api that has different parameters and these methods are not part of any interface or anything so its not looking really OO.

Is there another design pattern I could follow here to be able to allow for a StaticAPI class to have specific parameters set when the getInputStream(Params...) method is called and still be able to save it with a DataDriver by only passing the Storable class as a parameter? Is there a better way of writing this program to achieve this feature of storing the data in multiple different ways? The only other option I see is for the user to specify the parameters in the constructor or in a setDiameter() kind of thing, but I'm not sure that looks good either.

Any suggestions?

Can I use the Blade templating engine outside of Laravel?

i'm want to creating a design pattern and use the "Blade templating engine". Can I use the Blade templating engine outside of Laravel?

What is the best way to create an object oriented design of Store Credit Card Terminal?

I want to create an object oriented design of Store Credit Card Terminal.

Please let me know what design pattern can i user here

Java: link object to a variable in another object

This is a bit difficult to explain so I wrote up and example to illustrate the concept. In the following example I have a stock class which models the figures that affect a stock simulation program. I also have a MarketModifier class which represents events which would affect the stocks in different ways.

public class ExampleArea  
{
    public static void main(String cvhfg[]) 
    {  
        Stock test = new Stock(1f,1f,1f,1f);
        MarketModifier worldEvent = 
            new MarketModifier("Bad publicity",-2.5f,"publicOpinion");
    }   
}
class MarketModifier
{
    public MarketModifier(String name, float modifier, String variable) {
        super();
        this.name = name;
        Modifier = modifier;
        this.variable = variable;
    }
    String name;
    float Modifier;
    String variable;
}
class Stock
{
    public Stock(float value, float integrity, float publicPresence, float publicOpinion) {
        super();
        this.value = value;
        this.integrity = integrity;
        this.publicPresence = publicPresence;
        this.publicOpinion = publicOpinion;
    }
    float value;
    float integrity;
    float publicPresence;
    float publicOpinion;
    //...other variables...
}

My question is how would I link the marketModifer to the variable in the Stock model (in the example above it is "publicOpinion" set in the "variable" String) without using a string. Strings have the problem of possibly mistyping them, and I would need a switch to identify which variable the modifier was affecting.

I thought of using an enum but I would still need a switch table to check them and I would also have to update the enum values every time a stock has a different variable which could be affected (there could be additional variables in the subclasses of Stock). The other option I thought of was reflection but this solution, though I think it would work, seems overly complicated, and adds more difficulty in reading than it solves.

So again, is there a better way to link the an object to the variable(s) that it affects in another object (maybe some kind of observer/watcher pattern?).

Basic job scheduling and possible implementations

I am trying to implement the Job Scheduling problem: m jobs x n machines. What I have is jobs read from a file, each job has multiple different steps and a number of machines also read from a file.

My question is, for this problem, is there a design pattern that'd be helpful to use? Factory, Builder, Singleton, prototype?

Two-way OOP design-pattern

This is kind of a general question, let me formulate it in a particular scenario. I am coding a pricing system. In one hand there are several "engines", on the other, several "instruments". I created class hierarchies for both of them.

My problem comes now that I want to implement a pricing mechanism. Given a specific engine AND an a specific instrument, together they determine the algorithm to calculate a price. It would be nice to code it in 2-entries table. Both instances contain vital information, none seems more important than the other. In OOP methods belong to one class, so I see no decent design to deal with this: the "pricing" method should be in the Instruments class, or the Engines?

Whatever way I go I have the same problem. Suppose I decide it should be in the engines. Then, inside the pricing methods I should have an 'if-then-else' instruction dealing with each possible InstrumentClass? This seems way too ugly (and tight coupling!), specially if I am going to have to check it with something like

isinstance(inst, InstrClass1)

I can imagine similar situations arise in many contexts. What is the best design-pattern to deal with them?

I want to return a value of true or false but force it to randomly return false 3% of the time [duplicate]

This question already has an answer here:

From user input of either char a or char b as an answer. I want to return a value of true or false from user input. Then count the number of selections between two possibilities per individual user input. Then force it to randomly return false 3% of the time. The purpose is to alter the expected outcome with a reward.

How do I go about doing this? I am new to this concept.

Extend/wrap an object ad-hoc with more functionality

The following question adresses a problem I often encounter. Basically, there are solutions like the adaptor pattern, but I find it a bit unsatisfying.

Suppose I have a class Polygon which implements an - uhm - polygon with quite some functionality. Many of those Polygon live in my program, some as lonely variables, some in collection structures.

Now, there's a function that needs an argument type that is basically a Polygon, but with some additional features. Let's say, a Polygon who can return some metrics: his volume, center of gravity, and angular mass. Plus, the function also needs the methods of the original Polygon.

A first idea is:

class Polygon:
# defines my polygon

class PolygonWithMetrics(Polygon):
# - extends polygon with the metrics
# - takes Polygon as argument upon construction
# - would need to delegate many functions to Polygon

def functionUsingPolygonWithMetrics(p):
# use functions of Polygon and PolygonWithMetrics

# driving code:
p = Polygon(some args here)
... more code ...
p_with_metrics = PolygonWithMetrics(p) # Bummer - problem here...
functionUsingPolygonWithMetrics(p_with_metrics)

The problem: It would require to delegate many many functions from PolygonWithMetrics into the original Polygon.

A second idea is:

class Polygon:
# defines my polygon

class PolygonMetrics:
# takes a polygon and provides metrics methods on it

def functionUsingPolygonWithMetrics(p):
# use functions of Polygon and PolygonMetrics

# driving code:
p = Polygon(some args here)
... more code ...
p_with_metrics = PolygonMetrics(p)
functionUsingPolygonWithMetrics(p, p_with_metrics) # Bummer - problem here...

This idea takes the original Polygon as an argument, plus a second object that provides the metrics functions. The problem is that I would need to change the signature of functionUsingPolygonWithMetrics.

What I would really need is an idea how to extend an existing object ad-hoc with some more functionality, without the problems given in idea 1 and 2.

I could imagine an idea roughly like this, where the job is mostly done by PolygonWithMetrics:

class Polygon:
# defines my polygon

class PolygonWithMetrics(maybe inherits something):
# - takes a Polygon and provides metrics methods on it
# - upon construction, it will take a polygon
# - will expose the full functionality of Polygon automatically

def functionUsingPolygonWithMetrics(p):
# use functions of Polygon and PolygonWithMetrics

# driving code:
p = Polygon(some args here)
... more code ...
p_with_metrics = PolygonWithMetrics(p)
functionUsingPolygonWithMetrics(p)

Three questions arise:

  • Does this pattern have sort of a name?
  • Is it a good idea, or should I resort to some more adviced techniques?
  • How to do it in Python?

mardi 25 octobre 2016

Looking for approach to design two classes and one interface

 public interface ISaveData
  {
     void DeleteFile(); // this is common method
     //void ChangeBucket(); I don't need this method in GoogleCloudSaveFile. Should I remove this from here
     // void AssignPermission(); // I don't need of this method in AzureSaveData. Should I remove this from here?
  }



  public class AzureSaveData : ISaveData
  {
     void ChangeBucket()
     {...}

     void DeleteFile()
    {...}
  }

  public class GoogleCloudSaveFile() : ISaveData
  {
     void AssignPermission()
     {...}
     void DeleteFile()
     {.....}
  }

I want to expose Interface to my presentation layer.

How can I design above three classes (2 classes and 1 interface) to expose all methods to my presentation layer. All methods means. - Delete()
- ChangeBucket()
- AssignPermission()

Please ask me if you need more explanation

Presentation layer could be like

void Main()
{
     ISaveData saveFiles = new GoogleCloudSaveFile(); // This is just example. I will inject this via Dependency Injection framework

    saveFiles.Delete();

}

ChangeBucket() and AssignPermission() are just example methods. I wanted to say, our child classes could have different methods like these two.

One solution is I can define these two methods in interface and can leave method body empty of one method but I don't think it will be good approach

Can an adapter-patter adapter store state in its object or class?

An adapter would ideally be a bridge between two interfaces. However, when it needs to do relatively complex work, how do we decide what state is passed in, versus what state is 'hard coded' within the class or object?

Design Pattern to be used for supporting different filter set on a student relational table in JAVA

I have a SQL table with schema

[student_id, standard, home_city, home_state, country, num_of_subjects]

Now, I want to support api end point over this table as below:

GET /students?home_state=?&country=?&home_city=?&standard=? 

All the filters are optional.

Now, I want to know a good code design for this requirement. For technology I am using JAVA for web-app and a library querydsl for runtime query construction.

I have some ideas floating, but looking for a concrete and extensible approach, which can handle cases, so when a new filter column is added(let us say fav_subject), it should be minimum code change.

For ideas, I am thinking of a Filter interface with a method

public interface Filter { 
   void addFilter(Map<String, String> apiCallParameters, List<QueryFilters> addToList); //if apiCallParameters contains this filter key ,add filter to addToList
}

, all possible filters will be a class each, implementing this interface. Now, the query construction class can have List<Filter> , with each having addFilter deciding whether this filter will be added or not.

I want to better understand how this seemingly very common case is handled in code design.