mardi 30 juin 2015

I was just wondering why java.util.Scanner is implementing java.util.Iterator.

Scanner is implementing the remove method and throws an UnsupportedOperationException.

But shouldn't a class, when implementing an interface, suppose to fulfill the contract of the interface?

What is the use of implementing iterator and adding a method that throws an exception?

Why not just avoid the implementation of the interface and keep it simple?

One can argue that it is defined so that the class which might extend Scanner could implement the method, like AbstractList has an add method that throws an UnsupportedOperationException. But theAbstractList is an abstract class, where as Scanner is a final class.

Is it not a bad design practice..?

All Your Design Patterns Are Belong To Us

One team I'm on right now is in the process of building a massive application on Laravel. As we've added more design patterns, its obviously gotten more confusing. I'm here to ask you all if it sounds like we're using these design patterns properly and/or for the right purposes, and then for you to recommend the next pattern we incorporate.

We started out simply, using blades, controllers, and Eloquent models. Mostly using the models for defining the fields/attributes, defining relationships, etc.

Soon after, we started using repositories to do more conceptual cross-model queries, such as ->with(). I wouldn't say we're using them as purely "aggregate root" repositories as some people might suggest, but it's in that direction. We're also doing some functional model manipulations there, like fill() and making a record inactive (which then calls the model's store()).

We've also built our first Service Provider and Facade, in order to generalize one of our common UI elements. So we dipped our toe in that pool.

But now that we're getting deeper into the functionality, the business logic, etc, it seems like we have slightly outgrown our set of design patterns again. We're looking at Jobs (commands), we're looking at Service Providers and more Facades, but we're not completely sold on either yet. When do you use which? And why? And/or, are there other design patterns we should be examining to manage business logic? There's got to be a hairy class somewhere that pulls in all the dependencies and uses them. Just need to know where those should be.

Example: When storing an address, depending on the country and postal code, there are hidden fields that need to be filled out. Part of the decisions there include calls to other models/repositories to get reference/configuration data. We could do that: * In the repository, but then you're passing a second repository in as a dependency. Bad. * In a Service Container, but then you're littering static calls via Facades all over. Not great. * In a Job, but then you're abstracting the actual processing so far away from the CRUD operation, you start to lose the plot.

The kicker, of course, is building all this not just in a functional way, but in a SOLID way so we can have actual unit test coverage.

How to share external library interfaces between wrapper classes?

I want to wrap an external library so that other projects in the solution only have a reference to my wrapper code, and have no knowledge of the external library. My problem is with communicating the internals of the wrapper classes and interfaces between the other wrappers.

Say I have for example, the External Library:

namespace ExternalLibrary
{
    public interface IExtAlpha
    {
            ...
    }

    public interface IExtBeta
    {
        int DoTheThing(IExtAlpha extAlpha);
    }
}

And I create a Wrapper Project with appropriate interfaces:

namespace WrapperLibrary
{
    public interface IWrapExtAlpha
    {
            ...
    }

    public interface IWrapExtBeta
    {
        int DoTheThing(IWrapExtAlpha wrapExtAlpha);
    }
}

And a Wrapper Core project (containing the wrapper implementations)

namespace WrapperLibraryCore
{   
    public interface ICoreWrapExtAlpha : IWrapExtAlpha
    {
        ExternalLibrary.IExtAlpha ExtAlpha { get; }
    }

    public class WrapExtBeta : IWrapExtBeta
    {
        private readonly IExtBeta _extBeta;

        public WrapExtBeta(IExtBeta extBeta)
        {
            _extBeta = extBeta;
        }

        public int DoTheThing(IWrapExtAlpha wrapExtAlpha)
        {
            // The cast down to the ICoreWrapExtAlpha is where I'm concerned.
            var extAlpha = ((ICoreWrapExtAlpha)wrapExtAlpha).ExtAlpha;
            return _extBeta.DoTheThing(extAlpha);
        }
    }
}

What is the correct way to communicate the ExternalLibrary.IExtAlpha, wrapped by the IWrapExtAlpha, to the IWrapExtBeta wrapped by the WrapExtBeta class, when the IWrapExtAlpha cannot expose that IExtAlpha interface publically?

The solution I have so far is to down cast the interface (which feels wrong) to an interface that can share the external interface to other classes within that core library, with the requirement that any implementation of IWrapExtAlpha must actually implement the ICoreWrapExtAlpha instead. Is there a more idiomatic method?

What should be a correct JSON response for actions on certain object(s)

What should be a correct JSON response for actions on certain object(s). I would like to perform a certain action on User(s).

I am assuming the REST syntax for such actions (either single or multiple) look fine, what should a sample JSON response look like in case of success or failures.

e.g.

a. Archive a certain User http://foo:port/users/1/archive
b. Archive User(s) http://foo:port/users/archive?userIds=1,2,3
c. Remove a certain User http://foo:port/users/1/remove
d. Remove User(s) http://foo:port/users/remove?userIds=1,2,3

How do I implement this solution (strategy design pattern) in python? I have some rough code here

I am trying to implement this solution in python using the strategy design pattern. I am totally new to OOP, currently working with my professor on this problem.

Basically the question is to have an abstract class( or rather an interface), and 2 concrete child classes (car and bus), that have the method "find()" that returns the cost of taking the transportation. After they return their respective costs, the abstract parent class will choose the cheaper transportation and output a print statement "I choose bus".

Here is the rough code. Appreciate someone who can help me out! I believe my code is very wrong somewhere.

from abc import ABCMeta, abstractmethod

class transporter(metaclass=ABCMeta):
    'abstract parent class'
        @abstractmethod
        def find(self, cost):
            pass

    class car(transporter):
        def find(self):
            return "Cost of car travel is 50"

        def cost(self):
            return C = 50


    class bus(transporter):
        def find(self):
            return"Cost of bus travel is 20"

        def cost(self):
            return B = 20



    if __name__ == "__main__" :


        find_car = car()
        find_bus = bus()

        find_car.cost().execute()
        find_bus.cost().execute()

Finding patterns across rows of data.table in R

I am trying to find patterns across rows of a data.table while still maintaining the linkages of data across the rows. Here is a reduced example:

Row ID Value
1   C  1000
2   A  500
3   T  -200
4   B  5000
5   T  -900
6   A  300

I would like to search for all instances of "ATB" in successive rows and output the integers from the value column. Ideally, I want to bin the number of instances as well. The output table would look like this:

String Frequency Value1 Value2 Value 3
ATB      1        500   -200    5000
CAT      1        1000   500    -200

Since the data.table packages seems to be oriented towards providing operations on a column or row-wise basis I thought this should be possible. However, I haven't the slightest idea where to start. Any pointers in the right direction would be greatly appreciated.

Thanks!

Java: Updating Data Source through a Row Data Gateway

I have a member application which keeps tracks of members of a club (Name, ID). Currently I can add and I can delete but the problem is Updating. I have a hard time wrapping my head around accomplishing this with Java in the existing architecture (see below).

For adding, I have an ActionListener that will call CommandAddMember using the Name from the TextField.

memberNameButton.addActionListener(new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e) {
    CommandAddMember command = new
    CommandAddMember(addMemberNameTextField.getText());
    ModelFacade.getSingleton().queueCommand(command);
    }
});

The CommandMember looks like this:

public class CommandAddMember extends Command
{
    String memberName;
    public CommandAddMember(String name) {
    memberName = name;
    }

    @Override
    protected boolean execute() throws DatabaseException
    {
    MemberRowDataGatewayMock gateway = null;
    gateway = new MemberRowDataGatewayMock(memberName);
    int memberId = gateway.getMemberID();
    MemberResponseReport report = new
    MemberResponseReport(memberId, memberName, new ArrayList<String>());       
    QualifiedObservableConnector.getSingleton().sendReport(report);
    return true;
    }   
}

So here we access the MemberRowDataGatewayMock. The memberId is populated from gateway.getMemberID(); which uses a Hashmap and nextKey++ to increment by one (my guess is by whichever is last, like a real database sequence would). How can I simply update the existing MemberName while leaving the ID untouched? in SQL terms this would be

UPDATE table SET MemberName = 'NewName' where ID = 12;

For reference, here is the MemberRowDataGatewayMock:

public class MemberRowDataGatewayMock implements MemberRowDataGateway
{

    private class MemberInfo
    {
        private String memberName;

        public MemberInfo(String memberName)
        {
            this.memberName = memberName;
        }

    }


    private static HashMap<Integer, MemberInfo> memberInfo;
    private static int nextKey = 1;
    private int memberID;
    private MemberInfo info;

    /**
     * Finder constructor - will initialize itself from the stored information
     * 
     * @param memberID
     *            the ID of the member we are looking for
     * @throws DatabaseException
     *             if the memberID isn't in the data source
     */
    public MemberRowDataGatewayMock(int memberID) throws DatabaseException
    {
        if (memberInfo == null)
        {
            resetData();
        }

        if (memberInfo.containsKey(memberID))
        {
            info = memberInfo.get(memberID);
            this.memberID = memberID;
        } else
        {
            throw new DatabaseException("Couldn't find member with ID "
                    + memberID);
        }
    }

    public MemberRowDataGatewayMock(String memberName)
    {
        if (memberInfo == null)
        {
            resetData();
        }
        memberID = nextKey;
        nextKey++;

        info = new MemberInfo(memberName);
        memberInfo.put(memberID, info);
    }

    /**
     * Just used by tests to reset static information
     */
    public MemberRowDataGatewayMock()
    {
    }

    /**
     * @see datasource.MemberRowDataGateway#resetData()
     */
    @Override
    public void resetData()
    {
        memberInfo = new HashMap<Integer, MemberInfo>();
        nextKey = 1;
        for (MembersForTest p : MembersForTest.values())
        {
            memberInfo.put(nextKey, new MemberInfo(p.getMemberName()));
            nextKey++;
        }
    }

    /**
     * @throws DatabaseException 
     * @see datasource.MemberRowDataGateway#getMemberID()
     */
    @Override
    public int getMemberID() throws DatabaseException
    {
        if (info == null) {
            throw new DatabaseException("Member has already been deleted.");
        }
        return memberID;
    }

    /**
     * @see datasource.MemberRowDataGateway#persist()
     */
    @Override
    public void persist()
    {
        memberInfo.put(memberID, info);
    }

    /**
     * @throws DatabaseException 
     * @see datasource.MemberRowDataGateway#getMemberName()
     */
    @Override
    public String getMemberName() throws DatabaseException
    {
        if (info == null) {
            throw new DatabaseException("Member has already been deleted.");
        }
        return info.memberName;
    }

    @Override
    public String addMemberName()
    {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void deleteMember()
    {
        memberInfo.remove(memberID);
        info = null;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((info == null) ? 0 : info.hashCode());
        result = prime * result + memberID;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        MemberRowDataGatewayMock other = (MemberRowDataGatewayMock) obj;
        if (info == null) {
            if (other.info != null)
                return false;
        } else if (!info.equals(other.info))
            return false;
        if (memberID != other.memberID)
            return false;
        return true;
    }

}

java regex Pattern.compile multiple characters

I need to write a java pattern to identify all special characters except "0123456789" OR "(" OR ")" OR "|" OR "-" OR spaces. Can somebody help me to get an answer

I wanted to user Pattern.compile and pattern.matcher to find out this.

proper way to handle these RESTful calls for handling state

So, I have done a couple of projects where a call comes up for toggling state on an item. It is usually like whether an item is enabled or liked or something similar. It has to be a binary element though.

I have usually said that the proper way to do this is posting / deleting but that a quicker way is to do something like

/api/toggle_enabled/23/item

or

/api/toggle_liked/28/item

and have the state be reconciled on the server and return in the response the resulting state like:

{
 id:23,
 is_enabled: true / false
}

or

{
 id:28,
 is_liked: true / false
}

Usually other developers groan (as do I) when I see this but has always worked well and simplified client-side code by handling things like state for a user pressing a button multiple times very quickly. How do other developers handle this type of situation and is there another good option for handling? I know that this breaks RESTful principles but the simplicity seems to be worth it.

Dealing with duplicate and cross-tenant accounts in a multi-tenancy environment

Is there a good "vetted" way to handle having multiple copies of the same account for different tenants? Are there some recommended design patterns?

In my situation, our application routes tenant based on the URL:

http://ift.tt/1GXibvq  --> selects "ten_a" tenant
http://ift.tt/1BUXOQu  --> selects "ten_b" tenant

I am running into this problems:

Bob, who has account at ten_a, tries to login to ten_b.software.com, or even softare.com. If Bob is simply typing URLs in his browser, it is not much to let him know to use the correct address, but this gets more complicated when another entity is trying to authenticate Bob through, say, OAuth2 exchange. That third party may not know which tenant to direct its auth request. I only see two solutions here:

  1. Ask Bob to enter his tenant information alongside his username/password. Big minus is user experience and UI overhead.
  2. Implement a tenant router based on usernames. Big minus here is this seems like a minefield. It gets further complicated when Bob has an account on two different tenants.

Am I missing anything here?

Creating hypothesis Adaboost

I have been struggling for a couple of days with this, without being able to find a clear answer. I am learning Adaboost algorithm, but how the different hypothesis are created stays very unclear for me. I have read about Decision stumps as a base learner, but I am interested in Bayesian approach. Let's say I have this simple data set: enter link description here -- link to google drive with the sample data set ( I am new user and cannot post images) where D1 is the expected output. I have read how to reweight and calculate the error, but how do we create the hypothesis h(x) in the first place I could not understand.

I have started calculating the weights directly, so for the first row each data point has equal 1/8 weight and 3 data points make an error. So the error rate should be 1/8+1/8+1/8. Then I calculate the new weights - 1/2*(W(s)/1-E) for the right classified entries and 1/2*(W(s)/E) -for the wrong ones, where E is the error rate . But this just seems not to be the correct way.(on the second picture there is the only example with value calculation in every step) Thanks in advance

Java design pattern for analytics calculation

I have to calculate around 300 different analytics for example 1. Calculate mean of a given set 2. Calculate median of a given set Etc These calculators will be used in a batch process to calculate analytics from a set of data. I am planning to create an AbstractCalculator that will have all the common logic and then core implementation will be available in each of the child class's calculate method. I want to know is there a better way or is there an existing design pattern that I can refer to for such requirement. Only problem that I çan see is it will be difficult to manage 300 child classes.Is there a better way to handle such requirement Thanks Shakti

How to access members of child class by using reference of parent class?

Let there are classes:

class Parent {
     public Parent getParent() {
         ...
     }
}

class Child extends Parent{
     public Parent getChild() {
         ...
     }
}

//instantiating Child by using reference of Parent
Parent parent = new Child();

when I use:

//Works fine
Parent parentObject = parent.getParent();

When I use:

//Doesn't works
Child childObject = parent.getChild();

But when type cast object:

//Works fine
Child childObejct = ((Child)parent).getChild();

being as programmer this is something hectic to type cast explicitly for every call where I wanted to use child members by reference of parent class.

Class design patterns - best practices

men and women!

My problem is I don't really know what is the best way to design so I defined 2 classes 1'st one is:

class color
{
private $id = NULL; 
private $name = '';
private $rgb = NULL; 
private $cmy = NULL;
private $wavelength = NULL; 
private $frequency = NULL; 

public function __construct($name, $rgb, $cmy, $wavelenght, $frequency)
    {
    setName($name);
    setRGB($rgb);
    setCMY($cmy);
    setWavelength($wavelength);
    setFrequency($frequency);
    }

public function __destruct()
    {

    }

public function setName($name)
    {
    $this->name=$name;
    }

public function setRGB($rgb)
    {
    $this->rgb=$rgb;
    }

public function setCMY($cmy)
    {
    $this->cmy=$cmy;
    }

public function setWavelength($wavelength)
    {
    $this->wavelength=$wavelength;
    }

public function setFrequency($frequency)
    {
    $this->frequency=$frequency;
    }

public function getId()
    {
    return $this->id;
    }

public function getName()
    {
    return $this->name;
    }

public function getRGB()
    {
    return $this->rgb;
    }

public function getCMY()
    {
    return $this->cmy;
    }

public function getWavelength()
    {
    return $this->wavelength;
    }

public function getFrequency()
    {
    return $this->frequency;
    }

public function toJSON()
    {
    return "{'id':'".$this->id."', 'name':'".$this->name."', 'rgb':'".$this->rgb."', 'cmy':'".$this->cmy."', 'wavelength':'".$this->wavelength."', 'frequency':'".$this->frequency."'}";
    }

public function toCSV()
    {
    return $this->id . ", " . $this->name . ", " . $this->rgb . ", " . $this->cmy . ", " . $this->wavelength . ", " . $this->frequency;
    }

public function toHTML()
    {
    return "<p>ID: " . $this->id . "</p><p>Name: " . $this->name . "</p><p>RGB: " . $this->rgb . "</p><p>CMY: " . $this->cmy . "</p><p>Wavelength: " . $this->wavelength . "</p><p>Frequency: " . $this->frequency . "</p>";
    }

and 2'nd class looks like

class CRUD_color
{
public function create_color($parameters)
    {
    $color=new color();
    $color->setName($parameter['name']);
    $color->setRGB($parameter['rgb']);
    $color->setCMY($parameter['cmy']);
    $color->setWavelength($parameter['wavelength']);
    $color->setFrequency($parameter['frequency']);

    $entitymanager->persist($color);
    $entitymanager->flush();
    }
public function request_color($parameters)
    {
    $color=$entitymanager->find($parameter['id']);
    echo $color->toJSON($parameter['name']);
    }
public function update_color($parameters)
    {
    $color=$entitymanager->find($parameter['id']);
    $color->setName($parameter['name']);
    $color->setRGB($parameter['rgb']);
    $color->setCMY($parameter['cmy']);
    $color->setWavelength($parameter['wavelength']);
    $color->setFrequency($parameter['frequency']);

    $entitymanager->persist($color);
    $entitymanager->flush();
    }
public function delete_color($parameters)
    {
    $color=$entitymanager->delete($parameter['id']);
    }
}

now my question is if maybe it is better to have only one class color and include the functions from the second class in the 1st one? or let them apart?

why is one better than the other or vice versa? the design pattern is important to me so why choose one over the other..

Is there a problem if lets say we have the function create_color in witch we instantianate the class itself like new color() ????

lundi 29 juin 2015

Avoid type checking when function dependant on two distinct classes

I'm trying to code a game hub of sorts that is basically a collection of board games or games that can be easily played at the command line. (Tic Tac Toe, Connect Four, etc.) The user also has the option of making any of the two players computers. If I were making only Tic Tac Toe this wouldn't be an issue since I could just have "move" implemented in the human and computer subclass of Player and then invoke the correct one polymorphically, but with the addition of other games I'm not sure how to get away from type checking. For instance, if move is a function within player, how else other than through type checking would the function know whether to move according to the rules of Tic Tac Toe or Connect Four?

I was toying with the idea of having a separate move class with different subclasses for each scenario but I'm not sure if that's correct or how to implement it.

This is being written in C++ by the way.

OOP - Where does the responsibility go

I have a class named as A and another Class named as B. Class A contains Class B as a property.

I have a business logic. Based on the value of a property in Class B, I have to calculate the value of another property in Class A. To do this calculation, I have to call a SOAP service, get a value and then, based on the value of a property in Class B, i have to do a mathematical calculation on the returned value from the SOAP service and then set the value for property in Class A.

public Class A{
  public string Property1{get;set;}
  public int Property2{get;set;}
  public B Property3{get;set;}
}

public class B{
 public string Property1{get;set;}
 public string Property2{get;set;}
}

The logic in pseudocode

  1. If classB.property1 = "Something1" then call soap service,get some integer value, perfome some arithmatical calculation using a constant, and assign the result to classA.Property2
  2. Else If classB.property1 = "Something2" then call soap service,get some integer value, and assign the result to classA.Property2
  3. Else then set classA.Property2 to a default value.

I dont like the If else, it doesnt follow the OCP. I was thinking of doing this with a decorator. The second option is to use a builder pattern and encapsulate the if else logic, but still it would break the OCP. Or a completely new Domain service that would perform this?But still the OCP is being broken if If else even if i chose to go the Domain service way.

The above logic is being performed in a business logic class.

So where does the responsibility for above logic of calculation go? Also how to avoid that if else?

Template method design pattern using Java 8

I want to refactor template method using java 8 new default method. Say I have a flow of process define in abstract class:

public abstract class FlowManager{
public void startFlow(){
    pahse1();
    pahse2();
}
public abstract void phase1();
public abstarct void pahse2();
}

and I have few subclass's that extend the above flow manager and each subclass implements its own phase1 and phase2 mathod. I wonder if its make any sense to refactor the code to an interface like this:

public interface FlowManager{
public default startFlow(){
    this.phase1();
    this.phase2();
}
public void phase1();
public void phase2();
}

What do u think? Thank u in advance

How to write a class that can encompass other related classes?

Is it possible to write a class that acts like the super class of two other classes.

For example I have class A and class B. A and B share similar properties, but since I did not code A or B they do not extend an interface or class. Is it possible for me to create this super class so that when I generalize my code it can handle class A or B.

If this super class could be created this is some of what I would like to do in my class

class A
{
    string Name { get; set;}
    //does stuff
    //I can't change this class
}

class B
{
    string Name { get; set;}
    //does similar stuff
    //I can't change this class either
}

class MyClass
{
    //I would like to create a list that can include both class B and class A
    List<(pseudo superclass of A and B)> list;

    //Both class A and class B have a name, I would like to get the name given a type of A or B
    public (pseudo superclass of A and B) GetName((pseudo superclass of A and B) AorB)
    {
        //Write that name to the console
        Console.WriteLine(AorB.Name);
    }

}

Is this kind of wrapping possible, or will I need to do more work inside of MyClass (such as overloading methods) in order to accomplish what I need.

How do I create and use Java Builder Classes in Matlab?

I'm currently trying to import and use a class in Matlab 2015a that uses the Java Builder pattern and I can't seem to figure out how to instantiate an instance of the object. I can get the classes in my jar file imported into Matlab, but since the outer object has no constructor, I can't figure out how to instantiate the outer class in order to access the inner builder class and build the entire object. Does anyone have any insight into how I can instantiate and build the class in Matlab?

Below is my class setup.

package testJavaBuilder;

public class NutritionalFacts {
    private int sodium;
    private int fat;
    private int carbo;

    public static class Builder {
        private int sodium;
        private int fat;
        private int carbo;

        public Builder(int s) {
            this.sodium = s;
        }

        public Builder fat(int f) {
            this.fat = f;
            return this;
        }

        public Builder carbo(int c) {
            this.carbo = c;
            return this;
        }

        public NutritionalFacts build() {
            return new NutritionalFacts(this);
        }
    }

    private NutritionalFacts(Builder b) {
        this.sodium = b.sodium;
        this.fat = b.fat;
        this.carbo = b.carbo;
    }
}

Any apparent security concern or downside of a browser-based client?

I am tasked with a web application project involving a lot of dynamic design.

I am going to build a RESTful API with Node.js with token-based authentication, and initially I thought about building another Node.js application for web-based UI, but now that I have a basic design of the API, I was wondering if it is feasible to implement all of the UI logic with JavaScript on the browser?

It would involve a HTML page, which has JavaScript that will GET/POST data from the API, and update the DOM accordingly, furthermore, I would save authentication token in cookie, and the JavaScript in browser would do everything ranging from login to updating/deleting/creating all kinds of data through the RESTful API.

I haven't heard anything quite like this, is there any security concerns? Off the top of my head, the API server would get tremendous amount of requests if attacked.

Dependency Inversion Principle (SOLID) vs Encapsulation (Pillars of OOP)

I was recently having a debate about the Dependency Inversion Principle, Inversion of Control and Dependency Injection. In relation to this topic we were debating whether these principles violate one of the pillars of OOP, namely Encapsulation.

My understanding of these things is:

  • The Dependency Inversion Principle implies that objects should depend upon abstractions, not concretions - this is the fundamental principle upon which the Inversion of Control pattern and Dependency Injection are implemented.
  • Inversion of Control is a pattern implementation of the Dependency Inversion Principle, where abstract dependencies replace concrete dependencies, allowing concretions of the dependency to be specified outside of the object.
  • Dependency Injection is a design pattern that implements Inversion of Control and provides dependency resolution. Injection occurs when a dependency is passed to a dependent component. In essence, the Dependency Injection pattern provides a mechanism for coupling dependency abstractions with concrete implementations.
  • Encapsulation is the process whereby data and functionality that is required by a higher level object is insulated away and inaccessible, thus, the programmer is unaware of how an object is implemented.

The debate got to a sticking point with the following statement:

IoC isn't OOP because it breaks Encapsulation

Personally, I think that the Dependency Inversion Principle and the Inversion of Control pattern should be observed religiously by all OOP developers - and I live by the following quote:

If there is (potentially) more than one way to skin a cat, then do not behave like there is only one.

Example 1:

class Program {
    void Main() {
        SkinCatWithKnife skinner = new SkinCatWithKnife ();
        skinner.SkinTheCat();
    }
}

Here we see an example of encapsulation. The programmer only has to call Main() and the cat will be skinned, but what if he wanted to skin the cat with, say a set of razor sharp teeth?

Example 2:

class Program {
    ICatSkinner skinner;

    public Program(ICatSkinner skinner) {
        this.skinner = skinner;
    }

    void Main() {
        this.skinner.SkinTheCat();
    }
}

... new Program(new SkinCatWithTeeth());

Here we observe the Dependency Inversion Principle and Inversion of Control since an abstract (ICatSkinner) is provided in order to allow concrete dependencies to be passed in by the programmer. At last, there is more than one way to skin a cat!

The quarrel here is; does this break encapsulation? technically one could argue that .SkinTheCat(); is still encapsulated away within the Main() method call, so the programmer is unaware of the behavior of this method, so I do not think this breaks encapsulation.

Delving a little deeper, I think that IoC containers break OOP because they use reflection, but I am not convinced that IoC breaks OOP, nor am I convinced that IoC breaks encapsulation. In fact I'd go as far as to say that:

Encapsulation and Inversion of Control coincide with each other happily, allowing programmers to pass in only the concretions of a dependency, whilst hiding away the overall implementation via encapsulation.

Questions:

  • Is IoC a direct implementation of the Dependency Inversion Principle?
  • Does IoC always break encapsulation, and therefore OOP?
  • Should IoC be used sparingly, religiously or appropriately?
  • What is the difference between IoC and an IoC container?

Is there an elegant way to make every method in a class start with a certain block of code?

I have a class where every method starts the same way:

class Foo {
  public void bar() {
    if (!fooIsEnabled) return;
    //...
  }
  public void baz() {
    if (!fooIsEnabled) return;
    //...
  }
  public void bat() {
    if (!fooIsEnabled) return;
    //...
  }
}

Is there a nice way to require (and hopefully not write each time) the fooIsEnabled part for every public method in the class?

match a pattern in a matrix

I would like to find missingness patterns in a matrix and extract data matching a particular pattern. So, I have this matrix below (mydata) and identified 4 missingness patterns in the matrix (pattern), but I couldn't extract data from the matrix matching a particular pattern. For example the pattern "1 NA NA" (second row of the pattern matrix) should only extract rows 5 and 10 of the matrix:

[5,]   87   NA   NA
[10,]  96   NA   NA

.

mydata <- cbind(c(78, 84, 84, 85, 87, 91, 92, 94, 94, 96, 99, 105, 
                 105, 106, 108, 112, 113, 115, 118, 134),
                c(13, 9, 10, 10, NA, 3, 12, 3, 13, NA, 6, 12, 14, 
                  10, NA, 10, 14, 14, 12, 11),
                c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 7, 10, 
                  11, 15, 10, 10, 12, 14, 16, 12)
               )
mydata

       [,1] [,2] [,3]
 [1,]   78   13   NA
 [2,]   84    9   NA
 [3,]   84   10   NA
 [4,]   85   10   NA
 [5,]   87   NA   NA
 [6,]   91    3   NA
 [7,]   92   12   NA
 [8,]   94    3   NA
 [9,]   94   13   NA
[10,]   96   NA   NA
[11,]   99    6    7
[12,]  105   12   10
[13,]  105   14   11
[14,]  106   10   15
[15,]  108   NA   10
[16,]  112   10   10
[17,]  113   14   12
[18,]  115   14   14
[19,]  118   12   16
[20,]  134   11   12


pattern <- unique(ifelse(!is.na(mydata), 1, NA))
pattern

      [,1] [,2] [,3]
[1,]    1    1   NA
[2,]    1   NA   NA
[3,]    1    1    1
[4,]    1   NA    1

Confusion about Stateless Strategies

In Strategy design pattern, stateless strategies are mentioned. Could anyone please help me to understand it by answering following question : 1. What is this stateless strategy ? 2. What problem does it solve and how ? 3. Where to use & not use this ? 4. Dis(a)dvantages for same

And I will highly appreciate if all this could be explained by giving an example.

Regards, SJ

Which design pattern/s should I use when writing a parser?

I am writing XSD parser , which will be used to generate asp.net controls on a form according to the parsed XSD .

The XSD is loaded from some location ( for example from DB) to a XsdSchema object , and then using .NET classes (Schema Object Model) to read the elements of that schema to produce list of controls to be rendered on a form .

Which patterns you think are the best to be used in this scenario ?

(Currently I've created classes to represent different kinds of controls -text , date , list and etc. , and my xsd parser class has a method that returns a list of those classes according to the parsed XSD .

Those "Ui Element" classes were created to somehow not to tie the parser to asp.net layer )

I want to write the parser in some smart manner according to some design patterns for a simpler changes in the future .

Thanks.

Using statement or GC to dispose of a connection

I'm using a pattern where I constructor inject an IDbConnection instance into my class which is then assigned to a local variable before being used with Dapper to populate a List with objects from a database.

I understand that best practice is to wrap the connection object in a using statement, however when I try and reuse the connection to reload objects, I cannot because the connection has already been disposed. Would it be ok for me to just open and close the connection in the LoadValues method, and trust the class destructor to dispose of my object instead of having a using statement? Perhaps there's a better way that I've not considered?

Here is my class:

Public Class AmountLookup : Implements INAmountLookup
    Private _listOfRecords As New List(Of NAmount)
    Private ReadOnly _mfConnection As IDbConnection
    Private ReadOnly _fRepository As IFRepository

    Sub New(mfConnection As IDbConnection,
            fRepository As IFRepository)
        _mfConnection = mfConnection
        _fRepository = fRepository
        LoadValues()
    End Sub

    Public Sub LoadValues() Implements INAmountLookup.LoadValues
        LoadValues(DateGateway.GetLastWorkingDayOfPreviousMonth)
    End Sub

    Public Sub LoadValues(currentNDate As Date) Implements INAmountLookup.LoadValues
        _listOfRecords.Clear()

        Dim sql = String.Format(SqlFactory.GetSql(DBC.SQLs.ValidatedNAmounts),
                                _fRepository.GetFormattedListOfFsForSqlSearch,
                                Format(currentNDate, DBC.DateFormats.MfDate))

        Using _mfConnection
            _mfConnection.Open()
            _listOfRecords = _mfConnection.Query(Of NAmount)(sql).ToList
            _mfConnection.Close()
        End Using
    End Sub

    Public Function Find(fCodeValue As String) As NAmount Implements INAmountLookup.Find
        Dim myList = _listOfRecords.Where(Function(x) x.FCode = fCodeValue)
        Return myList.SingleOrDefault()
    End Function
End Class

dimanche 28 juin 2015

Fully worked out software design examples

Seeking: Full software design examples

Interviews often ask open-ended design questions like "Design a spreadsheet program". The expectation is too draw a UML-like diagram with program elements like Cell, Toolbar, Menu, MenuItem, ... should demonstrate knowledge of the Model-View-X pattern, etc.

Is there any good repository for such application designs? Ideally, such examples would also include explanations like: Cell is implementing the Observer/Observable pattern; MenuItem takes a Command item which implements the Command pattern.

Most available information is on the level of individual Design Patterns. That is, how to implement a specific Pattern like Command. I have found scant examples of full systems. It seems surprising to me that such questions are so standard and yet fully worked out, real-life sample artifacts are so difficult to find.

Though it doesn't include UML diagrams, here's one great design document which I found: http://ift.tt/1xEuSG6

Strategy Design Pattern in OBJ-C

Im come from Java, and Im revisiting the Head First Design Patterns book, this is the bible to Design patterns according to some developers. Im trying to recreate the Duck Simulator from the book from Java to obj-c, this is what I have so far:

http://ift.tt/1CCCpGJ

This simulator uses the Strategy Pattern that is applied using protocols. I have 2 problems with my implementation:

1- I cant have the Duck class to be abstract like in the Java version, on the Java version the method "display()" is abstract and should be implemented by children classes.

2- I had to expose the Duck class properties so children classes have access to them, this is not like in Java in which private properties can be seen by children classes.

What would be the ideal design for this solution?

Thank you

should c# static getter be thread safe

I am wondering if this class is thread safe

can I use Currencies as getter?

Should I lock GetLiveExchangeRates() method?

public class CurrencyManager
{
    public static List<CurrencyModel> Currencies { get; private set; }
    private static readonly object LockObj = new object();

    public CurrencyManager()
    {
        Currencies = new List<CurrencyModel>();
    }

    public static void GetLiveExchangeRates()
    {
        lock (LockObj)
        {
            Currencies = GetSomeFooLiveDataFromInternet();
        }
    }
}

EDIT

How would you refactor it?

How to Abstract Creation of Singleton Using XML Serialization

I'm trying to create a generic repository using the Singleton pattern which persists to an XML file. There are currently 3 concrete repositories, each of which are loaded from different XML files. I cannot figure out how to properly abstract the creation of the repository from the XML file. Here are my classes for one implementation of this repository.

Models

public interface IEntity
{
    string Name { get; }
}

public class Game : IEntity
{
    [XmlElement("Name")]
    public string Name { get; set; }

    [XmlElement("ExecutablePath")]
    public string ExecutablePath { get; set; }

    private Game() { } // Required for XML serialization.

    public Game(string name, string executablePath)
    {
        Name = name;
        ExecutablePath = executablePath;
    }
}

Repository

public interface IRepository<TEntity> where TEntity: IEntity
{
    List<TEntity> Items { get; }

    void Add(TEntity entity);
    void Delete(TEntity entity);
}

public abstract class Repository<TEntity> : IRepository<TEntity> where TEntity : IEntity 
{
    public abstract List<TEntity> Items { get; set; }

    private static Repository<TEntity> _instance;
    public static Repository<TEntity> Instance
    {
        get
        {
            if (_instance == null)\
                _instance = RepositoryFactory<Repository<TEntity>>.LoadFromFile();

            return _instance;
        }
    }

    public void Add(TEntity entity)
    {
        Items.Add(entity);
    }

    public void Delete(TEntity entity)
    {
        Items.Remove(entity);
    }
}

public static class RepositoryFactory<TRepository> 
{
    public static TRepository LoadFromFile() 
    {
        using (TextReader reader = new StreamReader("Games.xml"))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(TRepository));
            return (TRepository)serializer.Deserialize(reader);
        }
    }
}

[XmlRoot("Games")]
public class GameRepository : Repository<Game>
{
    [XmlElement("Game")]
    public override sealed List<Game> Items { get; set; }

    private GameRepository()
    {
        Items = new List<Game>();
    }
}

When trying to call 'GameRepository.Instance', I get this very generic exception: {"<Games xmlns=''> was not expected."}

This is admittedly one of my first times trying to gel these design patterns (singleton/factory) together, so this approach may have been completely wrong from the start. I can't diagnose exactly what is wrong from the exception (inner exception is null), so I'm hoping someone who knows these patterns can help me out.

Calling one DAO from another DAOFactory

Currently, my application architecture flows like this:

View → Presenter → Some asynchronous executor → DAOFactory → DAO (interface) → DAO (Impl)

For the time being, this kind of architecture works; mainly because I've only been needing one kind of DAO at the moment. But as the requirement grows, I'd need to expand to multiple DAOs, each with their own implementation on how to get the data.

Here's an illustration to my case:

enter image description here

The main headache comes from FooCloudDao which loads data from an API. This API needs some kind of authentication method - a string token that was stored during login (say, a Session object - yes, this too has its own DAO).

It's tempting to just pass a Session instance through FooDaoFactory, just in case there's no connection, but it seems hackish and counter-intuitive. The next thing I could imagine is to access SessionDAOFactory from within FooDaoFactory to gain instance of a Session (and then pass that when I need a FooCloudDAO instance).

But as I said, I'm not sure whether or not I could do a thing like this - well, may be I could, but will it be ethical?

Trying to create a Listener pattern style class, observers won't get notified

I'm now learning about the Listener or Observer-Observable design patter, i tried to implement my own class using the supplied Java library Observer interface and Observable class.

My Observable subject is an empty class that extends Observable.

Here are my two Observer classes:

public class CatObserver implements Observer {
    private String status = "Sleeping...";
    @Override
    public void update(Observable o, Object arg) {
        System.out.println("Updated!");
        this.status = "Awake!";
    }

    public void getStatus(){
        System.out.println(status);
    }
}

public class DogObserver implements Observer {
    private String status = "Sleeping...";
    @Override
    public void update(Observable o, Object arg) {
        this.status = "Awake!";
    }

    public void getStatus(){
        System.out.println(status);
    }
}

Here is my main program:

public class Listener {
    public static void main(String[] args) {
        AnimalSubject subject = new AnimalSubject();

        CatObserver mitsy = new CatObserver();
        DogObserver ozil = new DogObserver();

        mitsy.getStatus();
        ozil.getStatus();

        subject.addObserver(mitsy);
        subject.addObserver(ozil);

        synchronized (subject){
            subject.notifyAll();
        }

        mitsy.getStatus();
        ozil.getStatus();

    }

My output is 4 lines of "Sleeping...", when it should be 2 lines of "Sleeping..." and 2 lines of "Awake!".

When debugging it won't even go into the update() functions.

What am I doing wrong here?

samedi 27 juin 2015

Python regex: Matching a URL

I have some confusion regarding the pattern matching in the following expression. I tried to look up online but couldn't find an understandable solution:

imgurUrlPattern = re.compile(r'(http://i.imgur.com/(.*))(\?.*)?')

What exactly are the parentheses doing ? I understood up until the first asterisk , but I can't figure out what is happening after that.

Trivia game design pattern

I need help with some design issues on creating a trivia quiz game. Before moving on i could use some advice if following approach is OK/Improvable/prone to failure/.. . This is what I have come up with so far:

public class Question {
    private String question;
    private List<Answer> answers;
    private int statisticsCorrectness;
}

public class Answer {
    private String answer;
    private boolean correct;
}

I than create questions in a holder class which I can use to get a set of questions (This is where im unsure, seems wrong to put it in a class, have never seen it before)

public class StaticStuff {

    public Module getModuleOne(){
        Module module;


        //Question1
        Answer a = new Answer("Ten", true);
        Answer a1 = new Answer("Five", false);
        Answer a2 = new Answer("Six", false);
        Answer a3 = new Answer("Eight", false);
        Answer a4 = new Answer("10", true);
        Answer[] listOfAn = new Answer[]{a, a1, a2, a3, a4};

        Question q1 = new Question("What is 5 plus 5", Arrays.asList(listOfAn));
        //End Question1

        //Question2
        //....
        //End Question2

        //Add all questions
        Question[] questionsForFirstModule = new Question[]{q1};

        //Create the module that will be returned
        module = new Module("Introduction", Arrays.asList(questionsForFirstLession));

        return module;
    }
}

The way I planned to use it would be to get each Module object saved in the SharedPreferences the first time the app runs (Using Json or parcelable). Than when I need the set of questions I just get the object from the SharedPreferences and send it back "updated" to SharedPreferences.

If a clear cut question need to be specified it would be: is there much drawback saving objects this fashion compared to using a database. Maybe I should go for a database approach (Something I just realized after writing all this) ?

I looked at the first three pages on google "Trivia game java tutorial" but didn't really get enough info from that.

Basic API in golang antipattern?

Correct me if I'm wrong but for my unterstanding an API is something that allows me to modify and request data through an interface which is what I want to do in golang. For example I have a user interface:

interface IUser {
  GetId() int
  GetName() string
  GetSignupDate() time
  GetPermissions() []IPermission
  Delete()
}

This already looks to me like active record and if I want to create a new user with a new id I would have to use new since go doesn't support static functions as far as I know, which means I would also need a commit function in my interface which makes it even worse for me, what am I doing wrong here?

Design pattern with task processor

Currently I am working on piece of code which takes data and process it using processor and version. Eg

IProcessor aProcessor = new AProcessor(new AProcessorVersion1Translator());
aProcessor.GetResult("sample data");

Currently I am using Factory method to get processor according to type:

IProcessor aProcessor = processorFactory.GetProcessor("A");

Each processor will have various number of version translators, and there is my problem. Where should I use the version translator factory, should I pass it to processor factory object? Or maybe should I create separate factories for each individual processor?

Are global functions considered good practice in OOP?

Some OOP code I've seen, uses global functions to obtain data or return an object. For example, in Laravel we have functions like app(), config(), view() etc.

Is it considered a good practice to create global functions in addition to/instead of injecting dependencies? What are the benefits and what are the drawbacks?

A best practice for multithreading within a function that returns a value, Swift

I have a question that might be not specifically about implementation but rather a tip/best practice thing.

I am working on a class in Swift that gets data from an online source in JSON format. I want to have specific methods in this class that connect to the online source and give the result back in a Dictionary type. The function might be like this:

func getListFromOnline()->[String:String]{

    var resultList : [String:String]=[:]
    ...
    /*
    Some HTTP request is sent to the online source with NSURLRequest

    Then I parse the result and assign it to the resultList
    */
    ...

    return resultList
}

What I get right now in this implementation, without the multithreading, the resultList is apparently returned before fetching from the online source is done. Not surprisingly, it leads to failure in the program.

Any idea or tip how I can achieve the opposite? I am a bit confused with multithreading in this instance, because I want to call this public method asynchronously later from another class and I know how to do that, but I don't get how to make the method that returns an argument have multithreading within itself.

Or is it not about multithreading at all and I am not seeing an obvious solution here?

Design/Patterns - should I use interfaces or abstract classes?

I have following problem: I am creating an aplication for creating UML diagrams. Right now just to simplify everything I assume only couple of available diagram elements:

  1. class
  2. interface
  3. generalization
  4. interface implementation
  5. association
  6. aggregation

I decided to create one common abstract class for all of that elements:

abstract DiagramElement which has 2 subclasses also abstract:

  1. DiagramRelation
  2. DiagramObject

Nextly DiagramRelation has 4 subclasses:

  1. Generalization
  2. InterfaceImplementation
  3. Assosication
  4. Aggregation

And DiagramObject has 2 subclasses:

  1. Interface
  2. Class

I really wanted to post a picture so it would be all much more simplier but I don't have enough reputation points so sorry.

I came across following problem: each of this element have a different visual representation, ie: interface has only methods etc so each of this element will need to be show differently - I don't want to use multiple "if" instructions for it.

I use WPF and I decided that every control will place it's contest into StackPanel which will be placed inside MyContextControl (inherits after ContextControl and add interface atribute):

public interface IDiagramElementDraw
{
    public StackPanel Draw();
}

public MyContextControl : ContextControl
{
    private IDiagramElementDraw _drawingInterface;
    private StackPanel context;
    public DrawControl()
    {
        context = _drawingInterface.Draw();
    }
} 

But I don't know which class should implement IDiagramElementDraw interface - I don't want to implement it at the level of Interface, Class, Generalization etc classes because I want them to only represent logical information about each element.

I would appreciate any help, feel free to post complete different solution - this one may be completely wrong, this was just my idea.

Object oriented design discussion/review

Requirements: Index of items needs to be created or updated if already present. This index can be of two types:

  1. For a document (to index its contents): DocIndex
  2. For a document container that can contain many documents (to index contents of all documents in the container): ContainerIndex

DocIndex creation can be via:

  • UI
  • API

ContainerIndex creation can be via:

  • UI
  • API

Additionally, DocIndex can also be created as part of ContainerIndex creation, via both UI and API.

Also:

  1. The initial "setup" is different for both DocIndex and ContainerIndex.
  2. The core algorithm is "mostly" same for generation of both DocIndex and ContainerIndex, with the exception of some minimal differences in certain steps. Examples of differences:

    2a. An alert is required at a point in the code flow when DocIndex is generated via UI, only if it's not generated as part of ContainerIndex. API route has no alerts for both.

    2b. There is no logging required for ContainerIndex (for now), but DocIndex requires different logging in the following routes:

    2b.1. create via UI

    2b.2. create via API

    2b.3. update via UI

    2b.4. update via API

To model the above system in an OO design , I considered the following design patterns (and their variations thereof):

  1. Template Method: Have a base Index class that enforces the common algorithm structure and model the differences in the derived DocIndex and ContainerIndex classes. This could not handle the behavior that alerts need to be shown in a step when DocIndex is created via UI, but not when it's created via UI as part of ContainerIndex.
  2. Strategy: Model the differences with composition. However, I think my requirements aren't in line with the intent of Strategy design pattern as I don't want different algorithms but want to model differences only in certain steps. The algorithm structure is generally the same for both DocIndex and ContainerIndex creation.
  3. Decorator: Again IMHO its intent didn't match my requirements as I don't want runtime change in behavior. Also, this might require a lot of changes as the existing code has many other callers as well.
  4. State: To me this looks most promising. What I'll do is maintain different states of the index like UIContainerIndex (when container index is created via UI), UIDocIndex (when doc index is created via UI), UIContainerDocIndex (when doc index is created as part of container index via UI), and similar three states for the API route. This does satisfy my requirements, but I feel this might get unwieldy as the number of states increases (it already looks "not good enough" to me).

It would be great if someone could suggest something better. Thanks.

Program design advise

I have to write a program which does some more or less complex operations on sets of lines and surfaces. At first I tried a purely object oriented approach but now this feels a bit like it somehow has become more of an anti-pattern. Since I never really studied computer science except 3 basic courses, my knowledge and experience is very limited. But I would like to find a more elegant way to solve the problem and need some help. I try to elaborate:

This data needs to be handled:

  • simple lines (as a list of vectors)
  • extended lines (as a list of position, normal vectors and maybe more)
  • lists of both line types
  • lists of lists of both line types
  • surfaces
  • all lines and surfaces are stored in a "project" object

Now these have all kinds of procedures that operate on themselves only, like translation and rotation. But they also interact. For example a procedure like "project a line onto a surface with a extended line as a result". This is where the object oriented approach works quite well. But since the data needs to be visually represented, there has to be quite some render logic which was also added to the according classes which made them really heavy.

This is what I actually did (c++ pseudo code):

class SimpleLine {
  protected:
    points
  public:
    access points
    translation
    rotation
    render
    save to file
    ...
};

class ExtendedLine: public SimpleLine {
  protected:
    (points are inherited)
    normal vectors
  public:
    access data
    special translate
    special rotate
    render
    save to file
    ...
};

class SimpleLines: public std::vector<SimpleLine> {
public:
  translate
  project onto surface
  render
  save to file
  ...
};

class ExtendedLines: public std::vector<ExtendedLine> ...

class Project {
  simple lines
  extended lines
  surfaces

  render
  load from file
  save to file
};

Now my question is: How do I do a better separation of the different kind of operations on data and the data itself? Should I follow a more functional approach? Or is this already a acceptable solution and I'm just overthinking it? And: How is a problem like this typically solved, for example in something more complex (like a game)?

Thanks!

Design a Bar pattern of given inputs

i have to code to show bar pattern like- if my input is 54362 then output should be like-

      * 
*     *
* *   *
* * * * 
* * * * *
* * * * *
5 4 3 6 2

Thanks in advance

vendredi 26 juin 2015

Laravel Command Bus Validation - Best Practice

I'm currently working on a project which involves leveraging a 3rd party Soap API by issuing long requests.

Since we where initially unsure as to how/when some of these requests would be executed (either in a queue or via some artisan command) we decided that the Command Bus pattern would likely be a good fit.

However, I have a some concerns as to how these commands are being issued and where validation is occurring. To start the commands are not immutable.

Being new to the Laravel framework I was impressed by the Service Container and contextual bindings support however I wasn't sure how this might be leveraged properly if I'm only referencing concrete classes everywhere. ie: $command = new CrudOperation(n.* arguments));

All of our data validation is taking place inside separate FormRequest validation objects which may not be the best approach.

I'm also wondering whether each of these command handlers should be responsible for building out the necessary objects for our Soap call since they're already sitting behind the command bus.

Any advice is appreciated. Thanks.

Testing if object is not deleted

My object creates an thread and that thread modifies object-creator during his life cycle. The problem is, that thread should not invoke objects methods when it is destroyed. I have found some sollution for that problem and I would like to know if it is best one.

class A
{
    shared_ptr<int> guard = make_shared<int>(0);
public:
    weak_ptr<int> getGuard() { return guard; }
    void method() {}
    A()
    {
        thread([this]
        {
            const auto &guard = getGuard();
            while(!guard.expired()) 
                method();
        });
    }
};

Is there any way to 'limit' the methods that can be called on a class depending on the current state of a program?

Say I am developing a very simple card game. The card game has two phases.

1st Phase: Everone draws a card in turn order. 2nd Phase: Everyone plays a card, in turn order.

So, I model the game with an api that looks like this:

public class Game {
    public void draw(PlayerId playerId) {
        Player player = players.get(playerId);
        player.drawFrom(drawDeck);
    }

    public void play(PlayerId playerId, CardId cardId) {
        Player player = players.get(playerId);
        player.playCard(cardId);
    }
}

Here is my problem: the Game class has two methods to call, but only one method is valid at any one particular time. If the game is in the first phase, then the method play shouldn't be called. Likewise, if the game is in the second phase, the method draw should not be called.

What options do I have in this situation? I can only think of throwing exceptions if methods are called when they shouldn't be.

Ideally, I would like the client code to only be able to call the methods that are valid at that particular time. Any ideas on how I can do this? Or should the onus be on the client to call the methods correctly?

Need to display pattern as mentioned below using loops(if and for) in C#

I need to display pattern like below using loops(if and for) in C#

000
001
010
011
100
101
110
111

How to architect 'State Controller' objects being delegates of shared services

I have a UIViewController that currently conforms to the 'Massive View Controller' anti-pattern. I am trying to break functionality out into 'State Controller' objects that act as Controllers for each state that the ViewController might be in. My question is regarding services that multiple states might need to listen to. For example one state might be 'VideoRecordingState' and it has a reference to a 'FileSystem' object that is owned by the UIViewController. When the recording stops the 'VideoRecordingState' is replaced by a 'VideoReviewState'. Both states are interested in listening to the 'fileWriteCompleted' event from the 'FileSystem', and a file write that was started by one state might complete after it has been replaced by another state. So, does each state become the delegate of the 'service' object and just swaps itself out when the state changes, or does it make more sense for the UIViewController to be the delegate of the service and pass the notification on to the current state? Or is this whole design just plain wrong to begin with?

Massive Parent-Child and delegate pattern

I'm facing with a complex design problem. Due to a hard designed graphic I can't use Apple navigation pattern as UINavigationController or other ones. This is the app diagram App diagram

Black arrow: protocols direction Blue arrow: parent-child pattern direction

I created this flow because I want to maintain the code inside the single ViewController clear and isolated: I thought about them as modules that they can be used somewhere in other apps. The RootViewController is the MainVCs position manager. It decides which is the current view-controller that it must be showed and it configures it based on its status (modified by delegate methods). The single MainVC doesn't know that RootVC exists and it call Root using protocols. The single ChildViewController doesn't know that its MainVC exists and it call the Main using protocols and so on.

Code is clear and much easy to understand, my purpose, but when I have to apply a modify to the skeleton (RootVC) from the ChildViewControllerN, child of the umpteenth ChildViewController, child of the umpteenth MainViewController, I have to propagate the protocol until the RootViewController.

My first question is: is this pattern correct? What do you think about it?

My second question is: is there a limit point where I haven't to use delegate pattern but something like KVO?

Is breaking circular dependency necessary in this case?

for example , consider a system , which has a global main controller that has a sub controller , and the sub controller may call main controller to update:

MainController.h

class SubController;
class MainController{
public:
    static void setGlobalMainController(MainController* mainController);
    static MainController* getGlobalMainController();
    void init();
    void updateSystem();
protected:
    SubController* subController;
};

MainController.cpp

#include "MainController.h"
#include "SubController.h"
MainController* globalMainController;
void MainController::setGlobalMainController(MainController* mainController){
    globalMainController=mainController;
}

MainController* MainController::getGlobalMainController(){
    return globalMainController;
}

void MainController::init(){
    this->subController=new SubController();
    //wait sub controller to press button...
}

void MainController::updateSystem(){
    //do something
}

SubController.h

class SubController{
protected:
    void onButtonPressed();
}

SubController.cpp

#include "SubController.h"
#include "MainController"
void SubController::onButtonPressed(){
    //do something...
    MainController::getGlobalMainController()->updateSystem();
}

the SubController may accept button event and then need to update the main controller.

It has circular dependency,then I tried to break circular dependency using inheritance: create a new class MainControllerImp and move all concrete method in MainController to MainControllerImp:

MainController.h

class SubController;
class MainController{
public:
    static void setGlobalMainController(MainController* mainController);
    static MainController* getGlobalMainController();
    virtual void init()=0;
    virtual void updateSystem()=0;
protected:
    SubController* subController;
};

MainController.cpp

#include "MainController.h"
#include "SubController.h"
MainController* globalMainController;
void MainController::setGlobalMainController(MainController* mainController){
    globalMainController=mainController;
}

MainController* MainController::getGlobalMainController(){
    return globalMainController;
}

MainControllerImp.h

#include "MainController.h"
class MainControllerImp : public MainController{
    virtual void init();
    virtual void updateSystem();
}

MainControllerImp.cpp

#include "MainControllerImp.h"
void MainControllerImp::init(){
    this->subController=new SubController();
    //wait sub controller to press button...
}

void MainControllerImp::updateSystem(){
    //do something
}

SubController.h

class SubController{
protected:
    void onButtonPressed();
}

SubController.cpp

#include "SubController.h"
#include "MainController"
void SubController::onButtonPressed(){
    //do something...
    MainController::getGlobalMainController()->updateSystem();
}

the circular dependency seems disappeared. But after some time, I start thinking if I need breaking dependency at this case: it only moves all methods from parent class to child class, besides that it seems no any benefits. Also, it has one more class, which is less readable and the code is less straight forward.

Should I leave circular dependency at this case? or there are other better design pattern to break circular dependency?

jeudi 25 juin 2015

Good Approach to Learning Algorithms and Design Patterns?

From what I've gathered reading similar questions here, Algorithms by Sedgewick, and CLRS seem to be the preferred books on the subject. Unfortunately, they're rather long, and entail a lot of memorization. The same goes for many of the design patterns books. While I typically read textbooks from cover-to-cover without major breaks, I'm wondering whether books of this subject would be better utilized by reading only their introductory/core chapters, scanning through the rest, and then simply keeping them as reference afterwards.

I like this approach because it doesn't put so much strain on the student in trying to comprehend a multitude of algorithms, one after another, many of which may not even be used in practice. However, I am skeptical of how effective it could be. Has anyone read the aforementioned books, or studied algorithms or design patterns with this approach, and could share their experience?

Thanks.

Replacing Substring in Java

I have situation in Java where i am reading contents of file in String. It is something like this - String s =

  String S = "<name>source</name> <value>NB_System</value> </nameValue> <nameValue> <name>timestamp</name> <value>2015-6-25 22:39:41:455</value> </nameValue> <nameValue> <name>TTL</name> <value>0</value> </nameValue>"

I want to delete the timestamp from the string - timestamp</name> <value>2015-6-25 22:39:41:455</value>

Timestamp is creating issues in comparing results with master copy. Any suggestions how to get rid of timestamp here?

Thanks in advance

Any good practise design pattern fror Exception handling

I have exception handling code in every method for the below code for the bottom level methods

throw new Exception("The error that happens");

Is there any way I can avoid writing this code again and again in each method?

I am trying to write my own code and not using any log frameworks

private void TopLevelMethod()
{
    try
    {
        SomeMethod();
    }
    catch (Exception ex)
    {
        // Log/report exception/display to user etc.
    }
}

private void SomeMethod()
{
    TestPartA();
    TestPartB();
    TestPartC();
    TestPartD();
}

private void TestPartA()
{
    // Do some testing...
    try
    {
        if (somethingBadHappens)
        {
            throw new Exception("The error that happens");
        }
    }
    catch (Exception)
    {
        // Cleanup here. If no cleanup is possible, 
        // do not catch the exception here, i.e., 
        // try...catch would not be necessary in this method.

        // Re-throw the original exception.
        throw;
    }
}

private void TestPartB()
{
    // No need for try...catch because we can't do any cleanup for this method.
    if (somethingshappens)
    {
        throw new Exception("The error that happens");
    }
}

pattern matching in scala / recursion

I'd like to implement a function that counts the number of same characters directly following. This function always and only starts at the head.

function((Char, Int), List[char]) => ((Char, Int), List[Char])

e.g. (('b',0), List('b','b','x','x')) => (('b', 2), List('x', 'x'))

  def function: ((Char, Int), List[Char]) => ((Char, Int), List[Char])={
    case(('a', b), Nil) => (('a',b), Nil)
    case(('a', b), t::xs)  => (('a', b), t::xs)
    case (('a', b), a::xs) => function(('a', b+1),xs)
  }

I can't find the mistake in my pattern matching.

Are the two characters in the line

case (('**a**', b), **a**::xs) => function(('a', b+1),xs)

the same (like 'a' == 'a'), when I give them the same character?

thanks!

Metro Smart Card Application

I had a coding exercise today as part of an interview, where in I had to design a metro smart card application. Requirements -

  1. There is a metro line having 10 stations linearly from A1 to A10.
  2. Price per station is Rs. 5.5 (for weekends) and 7.0 (for weekdays)
  3. The metro line is 2-way.

I did it but I am not sure if that is correct. Of course I am getting the correct output but design is something which does not have one answer. I have created some class diagrams based on what i did today. This is maximum I could do. Can you guys please help me make it better? Image1 Image2

Dynamic Pattern Matching SQL with counts

In my case I am trying to see if there has been anyone who has devised a way to obtain an output that would traverse through all records for a given column and find all the patterns (whether it returns REGEX or the VALUES), then count how many times that exists. I know a lot of 1 counts would come back, so I more than likely would include a HAVING > 5 for instance.

Table =
dbo.PEOPLE

Columns =
LogID [int] IDENTITY(1,1) NOT NULL
,SourceData [varchar] (50) NOT NULL --which could include values that have numeric, alpha, and characters
,Account [nvarchar] (50) NULL

EXAMPLE DATA SET of table output (pipe delimited)
1|123X-456|56789
2|456/123|A345
3|ABC 345|X567
4|456 HELP-123|YCHB
5|456/987|2345
6|CDE 345|XX987
7|345X-456|YY6767

So what I would like my output to look like is two columns - PATTERN|COUNT
%X-456|2 --pulling in LogID rows 1 and 7, finding the like pattern and omitting everything else replacing with wildcard
456/%|2 --pulling in LogID rows 2 and 5
% 345|2 --pulling in LogID rows 3 and 6

Now, if someone has something that returns REGEX pattern vs. actual pattern values, then I would work with that.

Essentially I figured I would need to traverse through each character of a field, after reading the LEN of the field, and starting with position/char 1 reading each character until the end and writing each character to a TEMP with a cursor/CTE. Then coming back through and seeing how many times I can match that pattern where it is, for instance > 5 as stated at first. I know the execution plan will be robust and consume a lot of my SQL server resources, but it has to be easier than hiring people to find patterns.

Thanks in advance.

Design Pattern for a Courier Service Program

We have an Admin program for Courier Service. There are two branches with one admin each. We need a design pattern applicable for the requirements the following requirements:

  • Two Admins. (One for each branch)
  • Login Username and Password for the Admins

Admin Form has:

  • Locate Tracking numbers
  • Send Package
  • Send Cash
  • Pickup
  • Show Package Roster

It's like the customer needs to fill-up a form on paper and give it to the admin; and the admin will be the one to fill-up the forms in the program.

We do have a database. A two tables for each branch.

We need to implement a design pattern for this program. I can't think of anything that can be implemented here. (Sorry still new at this)

finding lines that contain n occurences of a certain pattern

I have a file containing lines that look like

A,B,1,2,3,$long,6,"A","",$long,,,,"ABC",,$long,,,,
E,F,2,3,4,$long,$long,$long,$long,,,"A","STRING";123456,,,1,2

My goal is to find lines containing n occurences of the pattern "$long".

Anyone knowing the grep regex for this match?

DAO persistence: only one method to store a complex data object?

Here we have:

public final class Product {

 Integer productId;
 String description;
 ...

 public Product(final Integer productId, final String descripcion, ...) {
    this.product_id = productId;
    this.description = description;
    ...
 }

 public Integer getProductId() { ... }
 public String getDescription() {...}

 ...

}

An then:

public final ProductDetails {

 Integer productId;
 String serialNumber;
 ...
 public ProductDatails(final Integer productId, final serialNumber, ...){ ... }
 public Intger getProductId() { ... }
 public String getSerialNumber { ... }
 ...

}

So, in order to build a DAO which persists the data the two classes contain, the question is that if it is a good practice to do as follows:

    public Interface IProductDAO {

      public void saveProduct(final Product product);
      public void saveProductDetails(final ProductDetails productDetails);

    }

or:

public Interface IProductDAO {
 public void saveProduct(final Product product, final ProductDetails productDetails);

I have been taking in consideration to refactor the two classes into one as follows:

public final class Product {

 Integer productId;
 String description;
 ProductDetails productDetails;
 ...

 public Product(final productId productId, final String description, final ProductDetails productDetails,...) {

   if(productId!=productDetails.getProductId())
      throw new IllegalArgumentException("ProductID is not the same");

   ...

 }

}

So:

 public Interface IProductDAO {            
      public void saveProduct(final Product product);                               
 }

I would like to know which one is the most 'natural' approach according best software development practices. If there are other approaches, they will be welcomed as well.

why doesn't this simple html code work? (pattern)

could somebody tell me why this simple code doesn't work? I type a random email address with .com at the end and I receive an error that this address doesn't have the right format.

<!DOCTYPE html>
<html>
<body>


<form action="demo_form.asp">
  E-mail: <input type="email" name="email" pattern="\.com$">
  <input type="submit">
</form>

</body>
</html>

Code desing for many different inputs but similar execution (output)

I have converter that converts CSV and writes it to database (always the same tables). There are many possible inputs and each input needs another configuration for CSV, as column name mappings, or restrictions on data. Of course some code parts are identical: as loop over all data rows or writing in database.

What is a good code pattern or design pattern(s) for such situation with many different possible inputs?

Do constructors always have to be public? [duplicate]

This question already has an answer here:

My first question is -

   class Explain() {
        public Explain() {
      }
   }

Should Constructor always declared as public?

What if I create a private constructor.

I always seen constructors are implicitly public. So why private constructor is useful? Or is it not useful at all. Because nobody could ever call it, or never make an object ! And that is my second question.

Thanks.

mercredi 24 juin 2015

What software architechture pattern does Java and C# use? [on hold]

I mean, for web applications there are several patterns like MVP(SC),MVP(PV),PM,MVVM and MVC, i've developed some desktop applications using Java and also using C#, and the sequence that i use mostly is the Waterfall model, and the 3 tier architecture, but, are there other design patterns?

Simpler, what are the design patterns for Desktop Applications?

Can the MVC be applied to Desktop Apps?

What problems can my DAO pattern have, when compared to DataMapper?

Suppose I have a Product class that loads a Motor.

class Product
{
   function productLoadMotor()
   {
       $this->motor = new Motor();
       $this->motor->loadMotorData();
       print $this->motor->loadedProperty; //print something
   }
}

class Motor
{   
    public function loadMotorData()
    {
        $this->motorDao = new MotorDao();
        $this->motorData = $this->motorDao->loadMotor();
        return $this->motorData;
    }
}

class MotorDao
{
    public function loadMotor()
    {
        $data = mysql_db_query($database, "SELECT...", $conn);
        return $data;
    }
}

It was mentioned that the above pattern is using dependency that closely ties my DAO to the business object. And that a DataMapper pattern will serve me better, because DataMapper will allow my business object develop independently over time.

Question:

Is there any particular problem or issue (with the way my code above is linked and structured) that will cause me problems? Anything related to dependencies linked incorrectly? If yes, where exactly and what are those problems (can you give me a hypothetical/concrete example)? Namely what problems can show up that will not show up in a properly-implemented DataMapper pattern?

I am seeking an answer that will most help me understand the relationship between my code and a DataMapper pattern. I see to understand pros/cons/ benefits/deficiencies betwen DataMapper and what I have above.

To contrast, DataMapper is something like this:

$product->motor = (new MotorMapper())->loadMotor();

class ProductMapper 
{
    function loadMotor()
    {
        $motor = db_query("SELECT ...");
        return $motor;
    }
}

Design Pattern for exposing Webservice

I want to expose an external API to my project(make an SDK in C# for the API).

What design pattern should I use so that:

  1. The code for making the request and getting the response is at one place.
  2. The code will make request, process the request and expose the data in Schematized from.
  3. What should I do so that the code using the API can control the number of threads that will be making and processing the requests(Configuration Driven)

Please suggest some guidelines.

Thanks.

What are the steps should we follow at development time to make our application modularized?

I am working on a product, We have many different modules in our application.

What I want is to design my application such that I can give any of the package to my clients as per their requirement.

Eg: I have seven modules 1-7, there is a possibility that for one client only one module is good enough and for some other 3-4 module is good. Then I just need to install only those modules on their server.

How should I take modularize approach?

I will be using WEBApi and REST service.

Java pattern first letter should not be hyphens (-), apostrophes (‘), and spaces ( ) [duplicate]

This question already has an answer here:

I am using this pattern to check

public static final Pattern VALID_FIRST_CHARACTERS = Pattern.compile("^[\\ \\'\\-]");

public boolean isValidFirstChar(String name) {
    if (VALID_FIRST_CHARACTERS.matcher(name).matches()) {
        return true;
    }
    return false;
}

no luck, can somebody help me please ?

Are those if statement "bad smell" regarding factory method design pattern?

Reading the factory design pattern in the "Gang of the Four" book pp 111, I found it use the parameterised factory method

if (id == MINE) return new MyProduct();
if (id == YOURS) return new YourProduct();

I read some articles which said those "if statement" are actually bad smell. We need to use reflection or non-reflection registration to avoid that.

Anyone can shed some light here? I don't find any statement in the book. If any new design pattern book said this is a bad smell, please also let me know.

Where to store business data?

I have a Rails app using MongoDB. I'll expose one single case although there are many others that would fit.

I've got a User model. Some User fields:

:first_name
:last_name
:email
:password_hash
:avatar
:roles

Sometimes it is interesting for us to know some data about how users interact with our app. For example, we want to know how many visits each user gets. What I thought about is to make a POST from client. Every time a user visits someone's profile a field inside that profile's owner (User) would be incremented.

Therefore, we can run reports based on that "stats".

One of my team-mates argues that that isn't a good practice as we'd end up with lots of requests all over the app. How people usually do this? Is it a good practice to make POST requests via AJAX and store it in database?

Thanks.

Take specific action depending on "foreign" subtype, without switch, casts and so on. Can we use polymorphism somehow?

I faced similar problem many times, and yet haven't found good solution. What follows is a concrete example with which I'm struggling now, but the problem is actually general.

Let's say we have some application that listens for binary data from serial port, decodes it, and sends some data back if needed. This is the core functionality, and it is done by a kind of "core" module.

This core module emits events. There is an abstract type Event, which contains some common data such as event time, and there are some subclasses of Event: for example, there is an event EventRawData that is emitted when any raw data is received, and EventMessage, that is emitted when message is decoded or sent.

There is GUI which listens for these events, and takes some actions when event happens. Of course, exact action depends on exact event type. The problem is how to take special action depending on event type. Event itself is completely unaware of any kind of GUI (and it shouldn't be aware), so, I can't add some virtual method to Event that displays this event somehow.

The naive approach is to use some kind of switch: in C++ we would use dynamic_cast, in Java it would be instanceof, etc. This is what I've done before, and I don't like it:

if (my_event instanceof EventRawData){
   // ...
} else if (my_event instanceof EventMessage){
   // ...
}

What I can think of instead, is:

Maybe we can invent some interface for GUI, and each particular GUI should implement this interface. Then, each event could have show() method:

abstract class Event {
   // ...
   abstract void show(GuiAbstract gui);
   // ...
}

and when this method is invoked by some particular GUI, the GUI should pass this there. This is probably what is called a "dependency injection" these days.

Well, I don't like this either: I want Event to be completely unaware of GUI.

Or, maybe it's better to get rid of base class Event, make each event completely separate class, and listen for them separately. I don't like it as well: I really want all events to have some common data (such as time of the event).

Maybe there is some design pattern that I'm unaware of? Any help is appreciated.

Implementing similar UseCases looks like code duplication

I've such case. User can export several object types (transaction, invoice, etc) to external accounting system. Export algorithm has steps:

  • fetch objects by some filter
  • export objects one by one to the accounting system (webservice method per object type)
  • register the fact that given document was exported, so it wont be exported again
  • prepare summary for user (num of exported documents, error messages etc)

The algorithm is the same for all object types but there are some important differences which must be handled:

  • different types
  • different target webservice method, different object to DTO mappings
  • different filters per object type

I've considered few solutions:

  • don't treat the export algorithm as code duplication and implement an algorithm per object type. Export of any data to any external system may be described by such algorithm - does it mean that we should always have one general class to export anything to anywhere?:)
  • move the differences to strategies (one strategy interface to create abstraction for all differencies) - I even implemented it.
  • use generics - unfortunately i'm coding in PHP and it's not possible

The question:

Is creating a separate export algorithm per object type a code duplication?

Maybe all of them should be treated as seperate UseCases?

If it's a duplication then what techniques to avoid it should I consider?

Avoiding redundancy in Composition pattern java

I have two classes A and B. Now, I have B "has a" A relationship. So, the most trivial thing to follow here is the Composition pattern. Now, one of the field of B is an object of A. The problem is some of the fields of A and B are common. So, in this case, those fields will be redundant. I can't create an abstract class out of the common fields and make A and B inherit it because they are already extending some abstract class. What would be the best practice in this case?

Implement singleton with static acces modifier

Example class with singleton design pattern.

  class Singleton {
        private static Singleton instance;
        private int x;

        private Singleton() {
             x = 5;
        }

        public static synchronized Singleton getInstance() {
            if(instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
            public void doSomething() {
                System.out.println("Hello");
        }
  }

I'm just wondering can I create this class with same variables and methods declared as static. Is it same as the singleton?

mardi 23 juin 2015

Open closed vs Single responsibility

I was looking into the Single Responsibility Principle(SRP) and Open Closed Principle(OCP).

SRP states that a class must have only one reason to change. OCP states that the class must be closed for modification but open to extension.

I find that to be contradicting. One principle states that the class must be simple enough, that you change for a single reason but the other principle states that a class must not be changed but only extended.

Does anyone have a better explanation?

what do i need to learn to get ready for next revolution "Internet of things" aka "Internet of everything"

what do i need to learn to get ready for next revolution "Internet of things" aka "Internet of everything".

or what do you guys think about internet of things.

Please give an example of factory method pattern

I read the difference between factory pattern and factory method pattern.Factory method pattern defers instantiation of an object to subclasses. Also it is a Factory Method because the children of “Creator” are responsible for implementing the “Create” method. Where as a simple factory is called directly by the class which wants to create an object. But for factory pattern also we can decouple the factory class by adding class registration through reflection and using a layer of subclasses for the objects to be created and keeping the object instantiation logic inside this subclasses. I am not getting an example of the factory method pattern that conforms to the above definition of factory method pattern.Can you please provide me a factory method example?

best way to implement an abstract factory that can create a huge amount of different products

The question title describes the problem but to be more specific suppose we have a 1000+ different products that have a similar nature (no, I'm not kidding.) but creating a class with 1000+ virtual functions and in turn 1000+ factory methods doesn't sound very attractive because it makes the code ugly and difficult to maintain and in long run as more objects are added, it might cause redundancy because keeping track of that many things in a list is humanly impossible. I would appreciate if the solutions are provided in C++ language because this is the target language for implementation. Also I don't think this question is subjective or opinion based because I'm sure someone out in the wild has already encountered this and possibly have suggested a design pattern for the same of which my (lack of) Internet search skills and impatience combined did not help in finding it.

How to design classes with different combinations of common functionality

I'm looking for some design suggestions. For example, let's say I want to create an abstract class for CRUD operations. I have my concrete implementations that inherit that base class. Some of my implementations are read-only. Some don't allow deletes. Some allow all CRUD operations. But at their core, all of these methods are the same between each implementation. And I want other classes that call these classes to be able to know what each implementation is capable of. My options that I can think of are:

  1. Put all code and public methods into the abstract class. Each implementation stores a list of what it can do {create, read, update} and expose a public method like AvailableMethods() which will simply return that list. In the implementation of these methods, it checks if that method is available and throws and exception if it is not. For instance, when create() is called, it checks to see if "create" is in the list of available methods. It doesn't seem right to do this for many reasons. The first of which, for me, is that I don't think any object should expose a method that will consistently throw an exception (assuming it's not an allowed method).

  2. Put all implementation into protected handler methods (handleCreate(), handleRead(), etc.) in the abstract class. Create interfaces for each method like ICanCreate has a single create() method, ICanRead has a single read() method. Concrete classes implement the needed interfaces and declare the public method that calls the handler. Calling classes can simply ask if the class implements the needed interface. This seems like a better solution but I feel like with hundreds of objects, and many different combinations, I'm going to be copy/pasting a thousand of the public methods. There will be a point where I'd want to consolidate into more base classes like ReadOnly, NoDelete, FullAccess or something like that. Which seems ok but even with only four choices, there are a lot of combinations. And this is just an example. I may have other functionality in which there are 6 or 8 methods.

Are there any other design options that I'm overlooking? I'm asking in a language agnostic way, but if there are any language specific ways of handling this better, I'm using PHP.

Should I have bothered using NavDrawer UI in my Android application?

I am near to completing my first production-scale Android application. It has been quite a learning process. I used to work in the Dev Tools group at Apple a while back and some of this really makes me pine for the old days. Setting up SQLite databases for Android. OMG does Android ever need a CoreData/EOF solution. Laying out interfaces? Well, InterfaceBuilder was annoying at times, but writing XML is not something humans should have to do a lot of.....

So, my app is using a NavDrawer for the main activity. I have to ask, was this even a good idea? Now I know how to set up views that have lists and scroll and such as that and I bet I can figure out the view transition animations if I wanted to. So what does NavDrawer give me, other than glitchiness?

At this point, everything mostly works. Well, moving back up from Preferences gives me the Preferences and main activity view both displaying on top of each other. But by a definition of working, it works. But I am not sure it was worth it.

Q: How does one set up a NavDrawer with 5 items?
A: It is easy! Just create these 4 classes, paste in these
300 lines of code, fix all the variable names, and do not
make any mistakes and it will work.
Q: What if it does not work?
A: Well, it worked for me. Please paste your entire project
into this page so that we can see which of the 27 things you
did not do.
Q, A, Q, A: Lather, rinse, repeat....

And this is the NavDrawer being helpful? Really? :-)

My main activity has a few master-detail lists in it. This is not a radical UI choice. I have lists of things, some with sub-things. So, in order to have the sub-thing's up button work, I have to put callback code for them into the main activity? The parent of the parent of the view I want to have the up button? Again, this is NavDrawer being helpful?

So, is the answer "Of course, you are using NavDrawer wrong", or is it "Of course, nobody actually expects NavDrawer to work unless you spend 6 months on it"? It seems that neither response would be a surprise.

Singleton Design Pattern in a web environment

I'm using in my asp.net web site, a singleton class to the users information.

I would like to know, if I put this web site online, when the users start to login, this this class will store the data to only one user.

nuget package - switching between test/live settings

A question about structure really. I have a class library which, amongst other functionality, also runs some database bits.

If I turn this into a nuget package so others in the company that need it can pull it down into their solutions, how do they go about changing the settings from test to live settings? (e.g. connection strings).

Is there a way to do this or is this bad design in general? For instance, should I actually be loading in the repository separately as opposed to having it as art of the pack?

At current workflow goes like this

Instantiate classes > 
Call method - method takes a record id >
Method calls repository and gets record from the id >
....does stuff to record... >
Method saves amendments back to database.

Should it instead be doing something like

Instantiate classes >
**Load repository into class** >
Call method - method takes a record id >
Method calls repository and gets record from the id >
....does stuff to record... >
Method saves amendments back to database.

Or should I not be handling any database access at all in the package, in which case how best to handle this whilst keeping my code reusable?

Thanks