问:
And at what point of modification to the original does source code with no license become owned by me?
I've recently come across a publicly viewable project on Github that has no license associated with it.  In this repo, there is a file with the logic and most of the code needed to work as a piece of a project I am working on.  Not verbatim, but about 60% of it I'd like to use with various modifications.  Once my code base is a little bit more stable, I plan to release what I've done under the WTFPL License.  I've emailed the repo owner, and so far have not gotten a reply.  I know I have the rights to fork the repo, but if I release a stripped down and modified version of the other project's file with mine, under the WTFPL, am I infringing on copyrights?

Per Github's Terms of Service, by submitted a project on Github and making it viewable to the public, you are allowing other users to see and fork your project.  Doesn't say anything about modifying, distributing, or using the fork.  And at what point of modification to the original does it become owned by me?

答:
Copyright gives the author (or the copyright holder, depending on jurisdiction) pretty much exclusive rights. Nobody else is allowed to do anything.

There are some restrictions, for example around fair use. You are allowed to make a parody of the project for satirical purposes (freedom of speech), for example, and you are allowed to quote tiny sections of it in a scientific article (freedom of education). If you are in the EU, you allowed to study it for interoperability purposes, iff you need it and iff the author refuses to give you the necessary information to build an interoperable product. (Note that "charging a fee" is not refusal!) But other than that, you aren't allowed to do anything. What you are allowed to do is spelled out in the license, and if there isn't one, then you can't do anything.

The GitHub TOS may or may not be construed as an implicit license, but even if this holds up in court as an actual copyright license, it still only gives you the rights that are listed in it: to read and fork the repo. Nothing more.

And at what point of modification to the original does it become owned by me?

That's a question for the courts. Your safest bet is: as long as your lawyers don't get paid significantly more than the other guy's, probably never. (If you are in the US, the history of BSD may be of interest to you.)


问:
Cross browser client side storage
I am developing an angularjs app. The app has to run in current FF, IE, Chrome and on iOS/Android via Phonegap.

I am looking for a solution to store data in the client.

Phonegap offers a web sql api, that is also supported by Chrome. FF however does not support it, since it is abbandoned by w3c.

Cookies and localStorage do not work reliable in iOS.

How can i store data in all those browsers?

答:
Take a look at http://caniuse.com/#feat=namevalue-storage - it seems that name/value storage is supported by most of the browsers. But it also states "In iOS 5 & 6 localStorage data is stored in a location that may occasionally be cleared out by the OS."

So I guess you have to create a local-storage-wrapper for you application and find workaround for each required browser. Those workarounds are called polyfill and you might find some which already fit your needs. For example, take a look at this page: https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills

ContentLicense: CC BY-SA 3.0

Title: Cross browser client side storage


问:
Is MVC now the only way to write PHP?
Hey... its XMAS Eve and something is bugging me... yes, I have work on my mind even when I am on holiday. The vast amount of frameworks available for PHP now use MVC. Even ASP.net has its own MVC module.

I can see the attraction of MVC, I really can and I use it frequently. The only downside that I can see is that you have to fire up the whole system to execute a page request. Depending on your task this can be a little wasteful.

So the question. In a professional environment is this the only way to use PHP nowadays or are their other design methods which have alternative benefits?

答:
Everything depends on the task at hand. There are no exceptions for this proposition for any topic. Be it MVC, Web Design, API programming, or even cooking. That's logic.

In regard to programming, for a particular task MVC may be overkill, or unsuitable. A 100 line script may be faster or more maintainable. Totally depends on task. You dont need to load up a beautifully structured, templated MVC app for an API that is only going to get a piece of data from a db table and serve it to a particular request.

MVC is better in cases that you may reuse the code, or would need to expand it in future, or need to maintain it for any particular reason.

And a note in regard to sequential vs oop - everything happens sequentially in a program. There cannot be two states of the same variable under same conditions. A shopping cart object itself cannot have two values for the same customer with same products with same options with same shipping locations and tax details. Or, you cannot create a shopping cart object and write the products in it before customer actually adds any products to the cart. It would be surreal. Something that requires particular conditions to happen cannot happen without those particular conditions being met, in programming. (And no - just initializing a potential predictive object class for a potential data object is not relevant).

So therefore think practical - do whatever the task in hand and its potential near, mid, and long term requirements necessitate.

ContentLicense: CC BY-SA 2.5

Title: Is MVC now the only way to write PHP?


问:
What would you call the concept of CofeeScript or Sass to be?
There is this rising trend with web development of making new pseudo languages to extend the functionality of JavaScript, CSS and HTML given that those are static and their metamorphosis or evolution is painfully slow due to the variety of browser providers.

So I am currently having a concept dilema on how to categorize them for a book I was made to write by my employer as no one seems to have a name for these pseudo languages.

A tiny list of them :

JavaScript: LiveScript, Metalua, Uberscript, EmberScript.

HTML: Razor, Java Scriptlets.

CSS : LESS, Sass.

I believe the concept of these pseudo languages and a language or an extension of a language is quite different.

First these languages do not extend any functionality currently existing on HTML or CSS or JavaScript, they simply work around it.

And also they do not "compile" to an intermediate language, they are merely 1-1 translated to something that only then can be compiled.

What would you call them?

答:
They are languages. Period.

There is no such thing as a compiled language, interpreted language, or transpiled language. Languages aren't compiled, interpreted or transpiled. They just are. Compilation (transpilation is just compilation) and interpretation are traits of the compiler or interpreter (duh!), not the language. Every language can be implemented by a compiler, and every language can be implemented by an interpreter. Most languages have both compiled and interpreted implementations. For example, there are interpreters for C and C++, and there are compilers for Ruby, Python, PHP, ECMAScript, Perl and Lua. Many modern language implementations actually use both interpretation and compilation in the same implementation.

There are, for example, projects for implementing CoffeeScript on the Rubinius VM and the Parrot VM. And why not? CoffeeScript is a nice language on its own, why tie it to ECMAScript?

TypeScript is semantically and syntactically a superset of ECMAScript, but that doesn't mean that the only way to implement it is as a compiler to ECMAScript. You could just as easily write an interpreter, or a compiler to native code, or a compiler to CIL bytecode, or a compiler to JVM bytecode.

Dart has a compiler to ECMAScript, but it also has a very nice and very fast native VM.


问:
Strategy to use two different measurement systems in software
I have an application that needs to accept and output values in both US Custom Units and Metric system.

Right now the conversion and input and output is a mess.  You can only enter in US system, but you can choose the output to be US or Metric, and the code to do the conversions is everywhere.

So I want to organize this and put together some simple rules.  So I came up with this:

Rules

user can enter values in either US or Metric, and User Interface will take care of marking this properly

All units internally will be stored as US, since the majority of the system already has most of the data stored like that and depends on this.  It shouldn't matter I suppose as long as you don't mix unit.

All output will be in US or Metric, depending on user selection/choice/preference.

In theory this sounds great and seems like a solution.  However, one little problem I came across is this:

There is some data stored in code or in the database that already returns data like this:  4 x 13/16" screws, which means "four times  screws".  I need the  to be in either US or Metric.  Where exactly do I put the conversion code for doing the conversion for this unit?

The above already mixing presentation and data, but the data for the field I need to populate is that whole string.  I can certainly split it up into the number 4, the 13/16", and the " x " and the " screws", but the question remains... where do I put the conversion code?

Different Locations for Conversion Routines

1)  Right now the string is in a class where it's produced.  I can put conversion code right into that class and it may be a good solution.  Except then, I want to be consistent so I will be putting conversion procedures everywhere in the code at-data-source, or right after reading it from the database.  The problem though is I think that my code will have to deal with two systems, all throughout the codebase after this, should I do this.

2)  According to the rules, my idea was to put it in the view script, aka last change to modify it before it is shown to the user.  And it may be the right thing to do, but then it strikes me it may not always be the best solution.  (First, it complicates the view script a tad, second, I need to do more work on the data side to split things up more, or do extra parsing, such as in my case above).

3) Another solution is to do this somewhere in the data prep step before the view, aka somewhere in the middle, before the view, but after the data-source.  This strikes me as messy and that could be the reason why my codebase is in such a mess right now.

It seems that there is no best solution.  What do I do?

Question

My goal is to figure out how to structure and where to place my unit conversion code within the system.  Software system in question is MVC-like (Zend Framework 2 - like) LAMP system.

Specific Example

Right now I have some class that given an id at creation time, has a method getValue(), which returns 4 x 13/16" screws.  Depending on id, different numbers can be produced, but they are still in inches.  I should note that some numbers are written with the dividing bar (13/16") and some use decimal notation (0.8125").  How could I set up my framework so that I can display such values in millimeters as well?

答:
Never store strings like  4 x 13/16" screws in your code or your database. Make it a placeholder string like 4 x {0} screws, pass it around with the actual value in internal units (in your case US inches), and only when your program finally presents this to the user, it will replace the placeholder by a value either in inches or mm (according to what is actually configured). If your program needs to present US values sometimes as fractions, you could use placeholders with some "hint" symbol (for example, use an f like {0f} to make sure inches will be displayed as fractions.

Of course, you should try to have only a small number of conversion routines (ideally just one) in your whole program, and a single place where the switch for US units vs. metric units is placed. Having the same information redundantly, or different conversion routines for the same purpose is extremely error-prone. So the central conversion routine should be reused wherever possible. So when I got your alternatives 1, 2, and 3 right, this leads right to option 3. If this becomes messy is up to you, but I think it is possible to handle this without making your code unneccessarily complicated.


问:
Reverse horizontal and vertical for a HTML table
There is a two-dimensional array describing a HTML table. Each element of the array consists of:

the cell content

rowspan

colspan

Every row of this two dimensional array corresponds to  cells of a
 of the table which my software should generate.

I need to "reverse" the array (interchange vertical and horizontal direction).

Insofar I considered algorithm based on this idea: make a rectangular matrix of the size of the table and store in every element of this matrix the corresponding index of the element of the above mentioned array. (Note that two elements of the matrix may be identical due rowspan/colspan.) Then I could use this matrix to calculate rowspan/colspan for the inverted table.

But this idea seems bad for me. Any other algorithms?

Note that I program in PHP.

答:
The only difficulty is to find on which column a cell starts.  Once you figure how to do that you can collect the cells for each column and output them as a row, exchanging colspan and rowspan.  To find the starting colum you have to track what part of the table positions is used by previous cells.  Each cell starts at the next available position.

I don’t know php, so I will use pseudocode.

The input is an array that gives for each row the list of variable-sized cells.  The output is in the same format.

I will  assume the table fills a rectangular area.  If not, some padding with empty cells will be neessary in the output.

```<code>function reverse( table:array of array of cell )
{
  used = new array of array of boolean.
  output = new array of array of cell

  for r = 0 to table.size()-1 {
    // process row r
    c = 0;
    for each cell in table[r] {
      // skip to next position
      while used[r][c] { c++; }
      // cell starts at column c.  add it to the output
      cell2 = cell with rowspan and colspan values switched
      output[c].append(cell2)
      // mark used table positions (use 1 for missing rowspan/colspan)
      for i = 0 to cell.rowspan-1 {
        for j = 0 to cell.colspan-1 {
          used[r+i][c+j] = true;
        }
      }
    }
  }

  return output;
}
</code>```

I hope you can translate it to php.

Body:
The only difficulty is to find on which column a cell starts.  Once you figure how to do that you can collect the cells for each column and output them as a row, exchanging colspan and rowspan.  To find the starting colum you have to track what part of the table positions is used by previous cells.  Each cell starts at the next available position.

I don’t know php, so I will use pseudocode.

The input is an array that gives for each row the list of variable-sized cells.  The output is in the same format.

I will  assume the table fills a rectangular area.  If not, some padding with empty cells will be neessary in the output.

function reverse( table:array of array of cell )
{
  used = new array of array of boolean.
  output = new array of array of cell

  for r = 0 to table.size()-1 {
    // process row r
    c = 0;
    for each cell in table[r] {
      // skip to next position
      while used[r][c] { c++; }
      // cell starts at column c.  add it to the output
      cell2 = cell with rowspan and colspan values switched
      output[c].append(cell2)
      // mark used table positions (use 1 for missing rowspan/colspan)
      for i = 0 to cell.rowspan-1 {
        for j = 0 to cell.colspan-1 {
          used[r+i][c+j] = true;
        }
      }
    }
  }

  return output;
}

I hope you can translate it to php.


问:
clone() only partially doable; how to react?
Suppose we have a class-hierarchy whose base class B requires a clone() method to be defined in its derivations. Whilst this works perfectly for most of them there is this one derivation X that holds an optional reference to a resource/object that can only be referenced from one instance of X. Whilst the rest of X can be cloned without problems this reference would have to be set to null/nil/nullptr.

What is the correct way to handle this situation?

X::clone() could throw an UncloneableException. Though this would be correct, it is not satisfying.

Set the reference to null/nil/nullptr and leave no notice of it. The user of X has to know about Xs "particularities".

Require derivations of B to define B::nearestClone(): the user of B has to be aware that the return value might not be a 1:1 clone.

Something else?

答:
Sounds like one particular instance of X is the "alpha" X and is, in effect, a singleton.  Breaks some design principles but might still be reasonable.

The strict purist approach is that alphaX is not clonable, nor persistable, etc. so nobody can break the singleton contract.  This is actually tricky and has generated many articles and books. Your options are to make all Xs non-cloneable, or for just alphaX to throw an exception.  Can the user know if their particular X is the alpha?

However, if this is more like nodes in a tree where there is one special root node, but clone still makes some sense (whether you clone the parent and children is a good question) you could clone but set that reference to null.

So, "it depends".  Sorry that this isn't definitive.  :-)


问:
How to avoid being forked into oblivion by a more powerful contributor?
As recently reported here:

Xamarin has forked Cocos2D-XNA, a 2D/3D game development framework,
  creating a cross-platform library that can be included in PCL
  projects.

However the founder of the project that was forked says:

The purpose of the MIT license is to unencumber your fair use. Not to
  encourage you to take software, rebrand it as your own, and then "take
  it in a new direction" as you say.

While not illegal, it is unethical.

It seems that the GitHub page of the new project doesn't even indicate that it's a fork in a typical GitHub manner, opting for an easily-removable History section instead (see bottom).

So my questions are:

Was Xamarin's action and the way the action was done ethical or not?

Is it possible to avoid such a situation if you are a single
developer or a small unfunded group of developers?

I am hoping this could be either a wiki question or there will be some objective answers grounded on modern OSS ethics/philosophy.

答:
Was Xamarin's action and the way the action was done ethical or not?

A lot of people are conflating the legal and ethical situation. The X11 license allows anyone to "use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so", so this is definitely legal.

Ethically though, it's more complicated. In open source communities, it's generally considered preferable to improve the original software rather than create a fork. In the link you gave, Miguel de Icaza says:

As you know, we contributed extensively to Cocos2D-XNA and we just could not continue to work together.

Once we reached a point where we could not collaborate together, I decided to take the project in the direction that I desired at the expense of backwards compatibility.

It's not clear why they "could not collaborate together", but it sounds like Xamarin made a reasonable effort to work on the original project before deciding to fork it.

Is it possible to avoid such a situation if you are a single developer or a small unfunded group of developers?

Legally, you could choose to use a license that doesn't allow forking by disallowing redistribution of the source code (at this point, it wouldn't be "free software"). Another option is to leave the code unencumbered but don't allow redistribution of static assets like images or non-code text (some games have licenses like this).

Socially, you can prevent forking by:

Making it easy for people to contribute changes to your project.

Reviewing patches quickly.

Allowing changes that don't directly benefit you.

Being polite. A surprising number of forks are due to contributors not being willing to work with each other anymore.

Forking software is a lot of work, and most sane people won't do that if they have an easier option. If they have no other choice, then preventing them from forking your code will just force them to either fork someone else's code or rewrite your software from scratch. It might slow them down, but it won't really help you much.

Also, using a more restrictive license will make some people less likely to contribute. Xamarin apparently "contributed extensively to Cocos2D-XNA", and I doubt they would have done that if the license didn't allow them to redistribute it.


答:
Under the constraints of the question, I would have an interface such as this (pseudocode):

```<code>public interface Cloneable<T> {
  boolean isCloneable();
  T clone();
}
</code>```

The isCloneable() method would return true if the current object can be cloned, while the clone() method would perform the actual clone. This is a kludgy hack for the fact that a subclass might not be cloneable despite implementing the Cloneable interface. If your programming language already provides a Cloneable interface you may need to add your own to make this work.

In fact this entire exercise serves to prove that a Cloneable interface is a bad idea. It places a constraint on any class that directly or indirectly implements the interface, and potentially any class contained in Cloneable objects.

Your question makes the assumption that cloning must be supported. However, the ideal way of copying an object is not to have a Cloneable interface, but to bake the idea of "copying" directly into a class without using the type system to define what is and is not cloneable. That is out of the scope of your question, but it might be worth exploring as a separate exercise (and perhaps follow-on question).

Title: clone() only partially doable; how to react?

Body:
Suppose we have a class-hierarchy whose base class B requires a clone() method to be defined in its derivations. Whilst this works perfectly for most of them there is this one derivation X that holds an optional reference to a resource/object that can only be referenced from one instance of X. Whilst the rest of X can be cloned without problems this reference would have to be set to null/nil/nullptr.

What is the correct way to handle this situation?

X::clone() could throw an UncloneableException. Though this would be correct, it is not satisfying.

Set the reference to null/nil/nullptr and leave no notice of it. The user of X has to know about Xs "particularities".

Require derivations of B to define B::nearestClone(): the user of B has to be aware that the return value might not be a 1:1 clone.

Something else?

Body:
Under the constraints of the question, I would have an interface such as this (pseudocode):

public interface Cloneable<T> {
  boolean isCloneable();
  T clone();
}

The isCloneable() method would return true if the current object can be cloned, while the clone() method would perform the actual clone. This is a kludgy hack for the fact that a subclass might not be cloneable despite implementing the Cloneable interface. If your programming language already provides a Cloneable interface you may need to add your own to make this work.

In fact this entire exercise serves to prove that a Cloneable interface is a bad idea. It places a constraint on any class that directly or indirectly implements the interface, and potentially any class contained in Cloneable objects.

Your question makes the assumption that cloning must be supported. However, the ideal way of copying an object is not to have a Cloneable interface, but to bake the idea of "copying" directly into a class without using the type system to define what is and is not cloneable. That is out of the scope of your question, but it might be worth exploring as a separate exercise (and perhaps follow-on question).


问:
Need to organize words based on their components, any other way aside from brute force?
I'm not sure if this process has a name.

I have some words (about 9,000). They are in Japanese, but I'll try to explain this using English words. I want to categorize the words by the components (in English, letters).

A

B

C

act bar play

This should create:

A: play

B: bar

C: act

Now, 'a' appears in all 3 words, but I want to make sure that each category (letter) has at least word. Now, it would make sense to delete a word after it's used, but there are a few cases where 2 letters make up one word and that's each letter's only word--so I'd like to account for that somehow.

Is there an approach for solving this aside from brute force? Dynamic programming perhaps? Even a name for this process (if it exists) would be great.

答:
You can express this as a maximum flow problem.  A maximum flow problem optimizes a flow in a network.  It can be used to solve assignment problems.  You want to assign words to categories.

You need to build a graph as follows:

Each category and each word is a node, to which you have to add a start node and an end node.

From the start node, add an edge going to each category.
From each category add an edge going to each word that is compatible with the category.
From each word, add an edge going to the end node.
All edges have capacity 1.

In this graph you want to maximuze the flow going from the start node to the end node.  The Ford-Fulkerson is especially interesting because it works with integer weights and returns a solution in integers.

The solution assigns one word to each category just follow for each category which edge has a positive flow.  If it is impossible to assign a word to all categories, it will return the assignment that maximizes the number of categories matched with a word.

If you have more words than categories, or any words left over, you can assign the remaining words to the first matching category.

This will guarantee that a maximum of categories have at least one word matched.


问:
How to change the state of a singleton in runtime
Consider I am going to write a simple file based logger AppLogger to be used in my apps, ideally it should be a singleton so I can call it via

```<code>public class AppLogger {
    public static String file = "..";

    public void logToFile() {
        // Write to file
    }

    public static log(String s) {
        AppLogger.getInstance().logToFile(s);
    }
}
</code>```

And to use it

```<code>AppLogger::log("This is a log statement");
</code>```

The problem is, what is the best time I should provide the value of file since it is a just a singleton?

Or how to refactor the above code (or skip using singleton) so I can customize the log file path? (Assume I don't need to write to multiple at the same time)

p.s. I know I can use library e.g. log4j, but consider it is just a design question, how to refactor the code above?

答:
It depends whether the file name is dynamic and can change any time or whether the fil e name is set at initialization time.

If you want a one-time initialization, you would set the filename in your app's initialization code.  Just ignore any call to logToFIle before the filename has been set.

Or you could set the file name in the constructor or in getInstance().  The singleton should then be able to initialize itself by retrieving the file name from a configuration file.

On the other side, if the file name can change while the app runs, you have to handle it like any other mutable state.  Access the singleton by getInstance() and call the setFilename() method.

In any case, if multiple thread access is a possibility, all operations must be synchronized.  If you are logging, the writing of the log file would probably take much more time than the synchronization.


问:
One codebase - lots of hosted services (similar to a basecamp style service) - planning structure
We have built a service (PHP Based) for a client, and are now looking to offer it to other clients as a hosted service. For this example, think of it like a hosted forum service, where a client signs up on our site, and is given a subdomain or can use their own domain, and the code picks up the domain, checks it against a 'master' users table, and then loads the content as needed.

I'm trying to work out the best way of handling multiple clients.

At the moment I can only think of two options that would work:

Option 1 - Have 1 set of database tables, but on each table have a column called 'siteid' - this would mean every query has to check the siteid. This would effectively work with just 1 codebase, and 1 database.

Option 2 - Have 1 'master' database with all the core stuff such as the client details and their domain. Then when the systen checks the domain, it pulls the clients database details (username/password/dbname) from a table, and loads a second database. The issue here is security of the mysql server details, however it does have the benefit that they are running their own database instead of sharing one.

Which option would I be better taking here, and why? Ideally I want it to be fairly easy to convert the 'standalone' script to the 'multi-domain' script as we're on a tight deadline.

答:
Before you decide how to organize your database tables for multiple clients ("the great multi-tenant vs. multi-instance debate"), you should consider how you intend to:

scale your service as your number of clients/branded sites grows,

scale your service as the number of users grows (either for individual clients/sites, or in aggregate),

keep your site(s) available should some of your hardware fail.

These decisions about how you're going to scale performance and maintain availability will make a big difference in how your data should be structured. Key variables include:

How much data you will have,

How rapidly your service might grow (in total number of clients, total number of users, or other metrics),

How much service availability you or your clients may demand,

How much isolation and security your clients may desire,

What type of platforms you wish to run these services on (in-house, virtualized, cloud, or a combination), and

What skills you have on-hand or could readily retain to help you through the development

I have successfully scaled services "up" by simply buying larger server, storage, and network instances. While this will not last you forever, scaling up is a legitimate entry strategy requiring fewer skills and simpler data structures. Eventually you would not be able to economically purchase larger instances, and would need to tackle the more difficult scale "out" direction, hosting your service across multiple cooperating nodes. This can provide much better scalability and availability, but also more complexity and oversight. A combination of clustering, sharding, and replication is usually required.

One intermediate step that can help bridge the gap between the straightforward vertical scaling and "full" horizontal/distributed scaling is scale-out multi-instance. This hybrid approach spreads your workload over multiple nodes, but with a largely vertical ("up") scaling strategy per node. It requires more facility with load balancers, DNS mapping, and provisioning/orchestration than typical scale-up deployments, but not the full "be the master of distributed algorithms and paradigms" that a Twitter, Facebook, or Google-style service design would. It also would map nicely to your "private brand" business style.

That you're on a tight deadline and that you (based on your question) do not have a lot of scale-out/sharding experience both argue for the simpler Option #1 or grandmasterb's Option #3, along with a plan to scale vertically first, then to a multi-instance model.


问:
Reflective discovery of an inner class in an API
Let me ask you, as this bothers me for quite a while but appears to be subjectively the best solution for my problem, if reflective discovery of an inner class for API purposes is that bad idea?

First, let me explain what I mean by saying "reflective discovery" and all that stuff.

I am sketching an API for a Java database system, that'll be centered around block-based entities (don't ask me what that means - that's a long story), and those entities can be read and returned to the Java code as objects subclassed from the Entity class.

I have an Entity.Factory class, that, by means of fluent interfaces, takes a Class<? extends Entity> argument and then, uses an instance of Section.Builder, Property.Builder, or whatever builder the entity has, to put it into the back-end storage.

The idea about registering all entity types and their builders just doesn't appeal to me, so I thought that the closest solution to the problem that'd suffice my design needs would be to discover, using reflection, all inner classes of Entity classes and find one that's called Builder.

Looking for some expert insight :) And if I missed some important design details (which could happen as I tried to make this question as concise as possible), just tell me and I'll add them.

答:
Maybe you are looking at the problem the wrong way.

You shouldn't start from a subclass of Entity and find the associated Builder by reflection.  Instead, you should start from an instance of a Builder and let it build the Entity you want.

I don't know how you use your factory.  But for example, instead of calling factory.create(Section.class) you could call factory.create(new Section.Builder()).  Would that make sense?


问:
Advice on approaching a significant rearrangement/refactoring?
I'm working on an application (hobby project, solo programmer, small-medium size), and I have recently redesigned a significant part of it. The program already works in it's current state, but I decided to reimplement things to improve the OO design.

I'm about to implement this new design by refactoring a big part of the application. Thing is I'm not sure where to start. Obviously, by the nature of a rearrangement, the moment you change one part of the program several other parts (at least temporarily) break. So it's a little 'scary' to rearrange something in a piece of software that already works.

I'm asking for advice or some general guidelines: how should I approach a significant refactoring? When you approach rearranging large parts of your application, where do you start?

Note that I'm interested only in re-arranging the high-level structure of the app. I have no intention of rewriting local algorithms.

答:
Spend most of your time up front writing comprehensive and detailed unit and integration tests.  They are the piece that will tell you if changes are breaking other pieces.

Then change pieces in a small a step as possible and run all the above tests, plus manual testing, between each step.

For the changes being made, use a distributed version control system like git so you can apply and rollback changes.


答:
Rewriting a complete application just because you don't like the code is usually not a good idea. Refactoring just for the sake of refactoring usually doesn't fix any problems, but introduces several new ones.

When you've learned something new which would totally improve the design of your previous application, resist the urge to rewrite it. There will always be a next project where you can apply your knowledge.

The only situation where large-scale refactoring makes sense is when you try to add a new feature, and you realize that the current architecture doesn't allow to do it in an elegant way. Then you might consider to do the necessary rewrites while developing that feature. Just don't forget about your goal: Getting that feature to work.

Title: Advice on approaching a significant rearrangement/refactoring?

Body:
I'm working on an application (hobby project, solo programmer, small-medium size), and I have recently redesigned a significant part of it. The program already works in it's current state, but I decided to reimplement things to improve the OO design.

I'm about to implement this new design by refactoring a big part of the application. Thing is I'm not sure where to start. Obviously, by the nature of a rearrangement, the moment you change one part of the program several other parts (at least temporarily) break. So it's a little 'scary' to rearrange something in a piece of software that already works.

I'm asking for advice or some general guidelines: how should I approach a significant refactoring? When you approach rearranging large parts of your application, where do you start?

Note that I'm interested only in re-arranging the high-level structure of the app. I have no intention of rewriting local algorithms.


问:
Can regexp be used to check for palindromes?
Can regexp pattern matching be used to check for palindromes within a given text in Java?

My intuition is that in order to check for palindromes, we may need to remember the character that was parsed, which cannot be done using regexp. Is that correct?

答:
No.

As others have mentioned, regular expressions cannot match palindromes of arbitrary length.

However, many programming languages have extended regular expressions in a way that puts them theoretically between regular and context-free languages, allowing them to match certain patterns that a strict regular expression by the textbook would not be able to match. Perl is one of these languages.

Java accepts several Perl extensions, but not the recursion tag required to implement this. What Perl can do is see that the first and last characters of the string match, then recursively use the same regex to attempt to match whatever is in the middle. Java does not support this nonstandard regex extension.

Here is another question that affirms it is not possible, and one more that offers a mathy CS proof of why it is not possible.


答:
First off, when you start poking around with questions like this, you will mix the aspects of Computer Science and what is actually out there.  Computer Science considers a regular expression different than what perl m// or java.util.regex can do.

This is the Apocalypse on Pattern Matching, generally having to do with what we call "regular expressions", which are only marginally related to real regular expressions. Nevertheless, the term has grown with the capabilities of our pattern matching engines, so I'm not going to try to fight linguistic necessity here. I will, however, generally call them "regexes" (or "regexen", when I'm in an Anglo-Saxon mood).

Larry wall from Apocalypse 5, June 4th, 2002

What exists in regex as we programmers know them is a significant superset of what traditional finite automata can do (that's a fun paper to read if you like the science part of CS).

The thing that this question boils down to is the pumping lemma on regular languages.  This can be said that if you have a regular language, you can put things into the middle without changing if the language is accepted.

Consider a language of binary palindromes.  It matches 101.  It also matches 1001 and 10001 and so forth.  You can put as many things in the middle there without changing if it should be accepted.  If its regular, it will handle 10101010101010101 and so on.

However, a regular expression is just short hand for writing a finite automata.  The word finite is key.  It has a finite number of states.  This means that if I put enough things in that word to be tested, it will repeat the same state twice if there are more elements to it than there are states (this is the pigeonhole principle).  Once that happens, the state of the automata will get confused and either generate a false positive or a false negative... and thus, using the pumping lemma, it can be shown that a language containing palindromes of arbitrary length is not regular.

Lets look more into the pumping lemma for regular languages.  The informal wording from wikipedia is:

Informally, it says that all sufficiently long words in a regular language may be pumped — that is, have a middle section of the word repeated an arbitrary number of times — to produce a new word that also lies within the same language.

So, lets take the language "a followed by some number of b followed by an a" which can be written as ab*a.  Within this regular language you have aa and aba and abba and abbba.  Applying the pumping lemma to this I can take the bbb part and stick in it in there again and if it still matches, it is a regular language.  So, putting bbb in the middle of abba I get abbbbba which is still part of the language (refiddle).  You can do this for any thing that is a regular language.

On the other hand, if you can put this in there and have something that isn't part of the language be matched, or should be part of the language but isn't matched you have a proof by contradiction that the original language isn't regular.

So, lets say "I have a language of binary palindromes of arbitrary length"  The regular expression to match it is ([01]?)([01]?)([01]?)([01]?)([01]?)[01]?\5\4\3\2\1 (note, I'm being a bit free with the language here being an extended one with back reference shorthand, but noting that would take a bit more text to properly represent it otherwise).

The above regular expression will match 010 and reject 011.  It will match 10101 but not 10111.  Great.  But the pumping lemma says that I should be able to put an arbitrarily large amount of the middle into the middle.  Now, the reader should go back and look at that regular expression... it has 5 back references.  It can't "store" more than 5 in there.  Thus, if I was to put

```<code>12345.....54321
101001111100101
</code>```

in there, it wouldn't match this string (refiddle), but that is a palindrome.  You can stick any palindrome of 12 or more characters in there and it will not match.

Thus, using the pumping lemma, I can say "palindromes of arbitrary length is not regular".  If it was, I could stick a thousand or million 1s in the middle there and pump it up... but I can't, so it isn't.

(Those who have dealt with regular languages before will likely recognize the palindrome of [01] is the parentheses matching language with a slight twist... which also isn't regular - see also Can regular expressions be used to match nested patterns? or To make sure: Pumping lemma for infinite regular languages only?)

A key part of the regular language is that it represented by a finite number of states.  What the contradiction with 101001111100101 did was to try to make it longer than the longest possible word that the language could recognize - which broke it.

Why not add more states?  Well, you can only put a finite number of states in there.  ([01]?)...([01]?)[01]?\100000...\1 ... and I'll make a palindrome that is 200,002 characters long, and it won't recognize it.  If you need an infinite number of states to present the language, it isn't a regular language (it might be context free (and palindromes are), but that's something else).

Title: Can regexp be used to check for palindromes?

Body:
Can regexp pattern matching be used to check for palindromes within a given text in Java?

My intuition is that in order to check for palindromes, we may need to remember the character that was parsed, which cannot be done using regexp. Is that correct?

Body:
First off, when you start poking around with questions like this, you will mix the aspects of Computer Science and what is actually out there.  Computer Science considers a regular expression different than what perl m// or java.util.regex can do.

This is the Apocalypse on Pattern Matching, generally having to do with what we call "regular expressions", which are only marginally related to real regular expressions. Nevertheless, the term has grown with the capabilities of our pattern matching engines, so I'm not going to try to fight linguistic necessity here. I will, however, generally call them "regexes" (or "regexen", when I'm in an Anglo-Saxon mood).

Larry wall from Apocalypse 5, June 4th, 2002

What exists in regex as we programmers know them is a significant superset of what traditional finite automata can do (that's a fun paper to read if you like the science part of CS).

The thing that this question boils down to is the pumping lemma on regular languages.  This can be said that if you have a regular language, you can put things into the middle without changing if the language is accepted.

Consider a language of binary palindromes.  It matches 101.  It also matches 1001 and 10001 and so forth.  You can put as many things in the middle there without changing if it should be accepted.  If its regular, it will handle 10101010101010101 and so on.

However, a regular expression is just short hand for writing a finite automata.  The word finite is key.  It has a finite number of states.  This means that if I put enough things in that word to be tested, it will repeat the same state twice if there are more elements to it than there are states (this is the pigeonhole principle).  Once that happens, the state of the automata will get confused and either generate a false positive or a false negative... and thus, using the pumping lemma, it can be shown that a language containing palindromes of arbitrary length is not regular.

Lets look more into the pumping lemma for regular languages.  The informal wording from wikipedia is:

Informally, it says that all sufficiently long words in a regular language may be pumped — that is, have a middle section of the word repeated an arbitrary number of times — to produce a new word that also lies within the same language.

So, lets take the language "a followed by some number of b followed by an a" which can be written as ab*a.  Within this regular language you have aa and aba and abba and abbba.  Applying the pumping lemma to this I can take the bbb part and stick in it in there again and if it still matches, it is a regular language.  So, putting bbb in the middle of abba I get abbbbba which is still part of the language (refiddle).  You can do this for any thing that is a regular language.

On the other hand, if you can put this in there and have something that isn't part of the language be matched, or should be part of the language but isn't matched you have a proof by contradiction that the original language isn't regular.

So, lets say "I have a language of binary palindromes of arbitrary length"  The regular expression to match it is ([01]?)([01]?)([01]?)([01]?)([01]?)[01]?\5\4\3\2\1 (note, I'm being a bit free with the language here being an extended one with back reference shorthand, but noting that would take a bit more text to properly represent it otherwise).

The above regular expression will match 010 and reject 011.  It will match 10101 but not 10111.  Great.  But the pumping lemma says that I should be able to put an arbitrarily large amount of the middle into the middle.  Now, the reader should go back and look at that regular expression... it has 5 back references.  It can't "store" more than 5 in there.  Thus, if I was to put

12345.....54321
101001111100101

in there, it wouldn't match this string (refiddle), but that is a palindrome.  You can stick any palindrome of 12 or more characters in there and it will not match.

Thus, using the pumping lemma, I can say "palindromes of arbitrary length is not regular".  If it was, I could stick a thousand or million 1s in the middle there and pump it up... but I can't, so it isn't.

(Those who have dealt with regular languages before will likely recognize the palindrome of [01] is the parentheses matching language with a slight twist... which also isn't regular - see also Can regular expressions be used to match nested patterns? or To make sure: Pumping lemma for infinite regular languages only?)

A key part of the regular language is that it represented by a finite number of states.  What the contradiction with 101001111100101 did was to try to make it longer than the longest possible word that the language could recognize - which broke it.

Why not add more states?  Well, you can only put a finite number of states in there.  ([01]?)...([01]?)[01]?\100000...\1 ... and I'll make a palindrome that is 200,002 characters long, and it won't recognize it.  If you need an infinite number of states to present the language, it isn't a regular language (it might be context free (and palindromes are), but that's something else).


问:
Using json as database with EF, how can I link EF and the json file during DbContext initialization?
For a personal testing-project I am considering to create a SPA with the following technologies:

ASP.NET MVC + EF + WebAPI + AngularJS.

The project will make use of small amount of data, so I was thinking I could use just a .json file as storage.

But I am not sure about how to proceed with the link between EF and the json file in the initialization of the DbContext.

I found a stackoverflow related question: https://stackoverflow.com/questions/13899342/can-we-use-json-as-a-database

I know the basics of edit files and store data inside. What I tried is to get the data from the json file in the initilizer method and create the objects one by one.

This is more a doubt about how this works if I save/update an object in the dbcontext, do I need to go through all the elements and add/update it manually? Is it better to rewrite the complete file?

According to this https://stackoverflow.com/questions/7895335/append-data-to-a-json-file-with-php it is not a good practice to use json/XML for data wich will be manipulated.

Anyone has experience with anything similar? Is this a really bad idea and I should use another kind of data-storage?

答: Don't do it!  There are so many options these days for actual databases in every context that one should almost never use something else as if it were a database.  For small and simple projects, you can at least use SQLite - it's probably used by several apps on your phone!


问:
Is it safe to convert Windows file paths to Unix file paths with a simple replace?
So for example say I had it so that all of my files will be transferred from a windows machine to a unix machine as such: C:\test\myFile.txt to {somewhere}/test/myFile.txt (drive letter is irrelevant at this point).

Currently, our utility library that we wrote ourselves provides a method that does a simple replace of all back slashes with forward slashes:

```<code>public String normalizePath(String path) {
   return path.replaceAll("\\", "/");
}
</code>```

Slashes are reserved and cannot be part of a file name, so the directory structure should be preserved. However, I'm not sure if there are other complications between windows and unix paths that I may need to worry about (eg: non-ascii names, etc)

答:
No.  There are far more things to think about than just the path separator (the "\ vs /" thing).  As Rob Y mentions, there is how spaces are handled, and their high frequency in Windows usage.  There are different illegal characters in the two environments.  There is Unix's willingness to allow almost anything when escaped by a leading "\".  There is Windows use of '"' to deal with embedded spaces.  There is Windows' use of UCS-16 and Unix's use of ASCII or UTF-8.

etc.,   etc.,   etc.

But, for lots of applications that can put constraints on the pathnames they need to manipulate, you actually can do it just the way you suggest.  And it will work in at least a large number of the cases, just not all of them.


答:
Yes, but this whole thing is a moot point. Java seamlessly converts forward slashes to back slashes on Windows. You can simply use forward slashes for all paths that are hard-coded or stored in configuration and it will work for both platforms.

Personally, I always use the forward slash even on Windows because it is not the escape character. Whether the raw path is in code or externalized in a properties file, I encode it the same way.

Try it! This will work in Windows. Obviously, change the actual path to something that exists and your user has permission to read.

```<code>File f = new File("c:/some/path/file.txt");
if (!f.canRead()) {
  System.out.println("Uh oh, Snowman was wrong!");
}
</code>```

Bonus: you can even mix slashes in the same path!

```<code>File f = new File("c:/some\\path/file.txt");
if (!f.canRead()) {
  System.out.println("Uh oh, Snowman was wrong again!");
}
</code>```

Title: Is it safe to convert Windows file paths to Unix file paths with a simple replace?

Body:
So for example say I had it so that all of my files will be transferred from a windows machine to a unix machine as such: C:\test\myFile.txt to {somewhere}/test/myFile.txt (drive letter is irrelevant at this point).

Currently, our utility library that we wrote ourselves provides a method that does a simple replace of all back slashes with forward slashes:

```<code>public String normalizePath(String path) {
   return path.replaceAll("\\", "/");
}
</code>```

Slashes are reserved and cannot be part of a file name, so the directory structure should be preserved. However, I'm not sure if there are other complications between windows and unix paths that I may need to worry about (eg: non-ascii names, etc)

Body:
Yes, but this whole thing is a moot point. Java seamlessly converts forward slashes to back slashes on Windows. You can simply use forward slashes for all paths that are hard-coded or stored in configuration and it will work for both platforms.

Personally, I always use the forward slash even on Windows because it is not the escape character. Whether the raw path is in code or externalized in a properties file, I encode it the same way.

Try it! This will work in Windows. Obviously, change the actual path to something that exists and your user has permission to read.

File f = new File("c:/some/path/file.txt");
if (!f.canRead()) {
  System.out.println("Uh oh, Snowman was wrong!");
}

Bonus: you can even mix slashes in the same path!

File f = new File("c:/some\\path/file.txt");
if (!f.canRead()) {
  System.out.println("Uh oh, Snowman was wrong again!");
}


问:
How exactly is an Abstract Syntax Tree created?
I think I understand the goal of an AST, and I've built a couple of tree structures before, but never an AST. I'm mostly confused because the nodes are text and not number, so I can't think of a nice way to input a token/string as I'm parsing some code.

For example, when I looked at diagrams of AST's, the variable and its value were leaf nodes to an equal sign. This makes perfect sense to me, but how would I go about implementing this? I guess I can do it case by case, so that when I stumble upon an "=" I use that as a node, and add the value parsed before the "=" as the leaf. It just seems wrong, because I'd probably have to make cases for tons and tons of things, depending on the syntax.

And then I came upon another problem, how is the tree traversed? Do I go all the way down the height, and go back up a node when I hit the bottom, and do the same for it's neighbor?

I've seen tons of diagrams on ASTs, but I couldn't find a fairly simple example of one in code, which would probably help.

答:
The short answer is that you use stacks. This is a good example, but I'll apply it to an AST.

FYI, this is Edsger Dijkstra's Shunting-Yard Algorithm.

In this case, I will use an operator stack and an expression stack. Since numbers are considered expressions in most languages, I'll use the expression stack to store them.

class ExprNode:
    char c
    ExprNode operand1
    ExprNode operand2

    ExprNode(char num):
        c = num
        operand1 = operand2 = nil

    Expr(char op, ExprNode e1, ExprNode e2):
        c = op
        operand1 = e1
        operand2 = e2

# Parser
ExprNode parse(string input):
    char c
    while (c = input.getNextChar()):
        if (c == '('):
            operatorStack.push(c)

        else if (c.isDigit()):
            exprStack.push(ExprNode(c))

        else if (c.isOperator()):
            while(operatorStack.top().precedence >= c.precedence):
                operator = operatorStack.pop()
                # Careful! The second operand was pushed last.
                e2 = exprStack.pop()
                e1 = exprStack.pop()
                exprStack.push(ExprNode(operator, e1, e2))

            operatorStack.push(c)

        else if (c == ')'):
            while (operatorStack.top() != '('):
                operator = operatorStack.pop()
                # Careful! The second operand was pushed last.
                e2 = exprStack.pop()
                e1 = exprStack.pop()
                exprStack.push(ExprNode(operator, e1, e2))

            # Pop the '(' off the operator stack.
            operatorStack.pop()

        else:
            error()
            return nil

    # There should only be one item on exprStack.
    # It's the root node, so we return it.
    return exprStack.pop()
```

<p>(Please be nice about my code. I know it's not robust; it's just supposed to be pseudocode.)</p>

<p>Anyway, as you can see from the code, arbitrary expressions can be operands to other expressions. If you have the following input:</p>

```5 * 3 + (4 + 2 % 2 * 8)
```

<p>the code I wrote would produce this AST:</p>

```     +
    / \
   /   \
  *     +
 / \   / \
5   3 4   *
         / \
        %   8
       / \
      2   2
```

And then when you want to produce the code for that AST, you do a Post Order Tree Traversal. When you visit a leaf node (with a number), you generate a constant because the compiler needs to know the operand values. When you visit a node with an operator, you generate the appropriate instruction from the operator. For example, the '+' operator gives you an "add" instruction.

Body:
The short answer is that you use stacks. This is a good example, but I'll apply it to an AST.

FYI, this is Edsger Dijkstra's Shunting-Yard Algorithm.

In this case, I will use an operator stack and an expression stack. Since numbers are considered expressions in most languages, I'll use the expression stack to store them.

class ExprNode:
    char c
    ExprNode operand1
    ExprNode operand2

    ExprNode(char num):
        c = num
        operand1 = operand2 = nil

    Expr(char op, ExprNode e1, ExprNode e2):
        c = op
        operand1 = e1
        operand2 = e2

# Parser
ExprNode parse(string input):
    char c
    while (c = input.getNextChar()):
        if (c == '('):
            operatorStack.push(c)

        else if (c.isDigit()):
            exprStack.push(ExprNode(c))

        else if (c.isOperator()):
            while(operatorStack.top().precedence >= c.precedence):
                operator = operatorStack.pop()
                # Careful! The second operand was pushed last.
                e2 = exprStack.pop()
                e1 = exprStack.pop()
                exprStack.push(ExprNode(operator, e1, e2))

            operatorStack.push(c)

        else if (c == ')'):
            while (operatorStack.top() != '('):
                operator = operatorStack.pop()
                # Careful! The second operand was pushed last.
                e2 = exprStack.pop()
                e1 = exprStack.pop()
                exprStack.push(ExprNode(operator, e1, e2))

            # Pop the '(' off the operator stack.
            operatorStack.pop()

        else:
            error()
            return nil

    # There should only be one item on exprStack.
    # It's the root node, so we return it.
    return exprStack.pop()

(Please be nice about my code. I know it's not robust; it's just supposed to be pseudocode.)

Anyway, as you can see from the code, arbitrary expressions can be operands to other expressions. If you have the following input:

5 * 3 + (4 + 2 % 2 * 8)

the code I wrote would produce this AST:

     +
    / \
   /   \
  *     +
 / \   / \
5   3 4   *
         / \
        %   8
       / \
      2   2

And then when you want to produce the code for that AST, you do a Post Order Tree Traversal. When you visit a leaf node (with a number), you generate a constant because the compiler needs to know the operand values. When you visit a node with an operator, you generate the appropriate instruction from the operator. For example, the '+' operator gives you an "add" instruction.


问:
What are steps in making an operating system in C ?
I am trying to make an my own OS. This is for educational purpose only, so that I get to understand the internals as well as get a good idea of low level programming. I have some prior application development experience  in C#/python/C++/C. I am a noob in assembly language(very less experience and knowledge). I understand that in writing an operating system,we can't go without assembly language.

Currently, I have just printed a string in assembly language in the boot sector using qemu and BIOS interrupts.

What I want is that, can someone specifically point out the steps that I need to follow to make my operating systems run C programs. So that, I can start writing my OS in C.

Any other piece of advice to help a newbie, regarding the same is also welcome.

Although, I have looked into many os development related tutorials/websites, I can't seem to find this information anywhere.

答:
First, you cannot write entirely an operating system kernel in C, because by definition an OS is managing physical hardware resources, and some of them (at least on common hardware like x86) are not accessible in C (e.g. MMU, I/O ports, ...). So you'll need a little assembly. (perhaps most of them can be asm instructions inside C functions).

Then, look at OsDev, it gives you a lot of information about how to start.

You'll also learn a lot by extending existing free software OS: in particular, understanding how to write your own Linux kernel modules and drivers will teach you a lot. See http://kernelnewbies.org/


答:
Building the AST from the source text is "simply" parsing. How exactly it is done depends upon the parsed formal language and the implementation. You could use parser generators like menhir (for Ocaml), GNU bison with flex, or  ANTLR etc etc. It is often done "manually" by coding some recursive descent parser (see this answer explaining why). The contextual aspect of parsing is often done elsewhere (symbol tables, attributes, ....).

However, in practice AST are much more complex than what you believe. For instance, in a compiler like GCC the AST keeps source location information and some typing information. Read about Generic Trees and GIMPLE in GCC and look inside its gcc/tree.def. Consider, if you want to process C or C++ or Fortran or Ada, writing your own GCC plugin. BTW, look also inside the obsolete GCC MELT (which I have designed & implemented), it is relevant to your question. Read the Dragon book. See also this draft report for references, and the RefPerSys project and the source code of many other open source projects (including Ocaml or Guile or SBCL or Jq) on github or gitlab as examples.

Title: How exactly is an Abstract Syntax Tree created?

Body:
I think I understand the goal of an AST, and I've built a couple of tree structures before, but never an AST. I'm mostly confused because the nodes are text and not number, so I can't think of a nice way to input a token/string as I'm parsing some code.

For example, when I looked at diagrams of AST's, the variable and its value were leaf nodes to an equal sign. This makes perfect sense to me, but how would I go about implementing this? I guess I can do it case by case, so that when I stumble upon an "=" I use that as a node, and add the value parsed before the "=" as the leaf. It just seems wrong, because I'd probably have to make cases for tons and tons of things, depending on the syntax.

And then I came upon another problem, how is the tree traversed? Do I go all the way down the height, and go back up a node when I hit the bottom, and do the same for it's neighbor?

I've seen tons of diagrams on ASTs, but I couldn't find a fairly simple example of one in code, which would probably help.

ContentLicense: CC BY-SA 4.0


问:
How to make the members of my Data Access Layer object aware of their siblings
My team currently has a project with a data access object composed like so:

```<code>public abstract class DataProvider
{
     public CustomerRepository CustomerRepo { get; private set; }
     public InvoiceRepository InvoiceRepo { get; private set; }
     public InventoryRepository InventoryRepo { get; private set; }
     // couple more like the above
}
</code>```

We have non-abstract classes that inherit from DataProvider, and the type of "CustomerRepo" that gets instantiated is controlled by that child class.

```<code>public class FloridaDataProvider
{
     public FloridaDataProvider()
     {
          CustomerRepo  = new FloridaCustomerRepo(); // derived from base CustomerRepository
          InvoiceRepo = new InvoiceRespository();
          InventoryRepo = new InventoryRepository();
     }
}
</code>```

Our problem is that some of the methods inside a given repo really would benefit from having access to the other repo's. Like, a method inside InventoryRepository needs to get to Customer data to do some determinations, so I need to pass in a reference to a CustomerRepository object.

Whats the best way for these "sibling" repos to be aware of each other and have the ability to call each other's methods as-needed? Virtually all the other repos would benefit from having the CustomerRepo, for example, because it is where names/phones/etc are selected from, and these data elements need to be added to the various objects that are returned out of the other repos.

I can't just new-up a plain "CustomerRepository" object inside a method within a different repo, because it might not be the base CustomerRepository that actually needs to run.

答:
First, lets ignore fact, that repositories are stupid idea in the first place.

Like, a method inside InventoryRepository needs to get to Customer data to do some determinations

Your repositories are quire obviously breaking single responsibility principle. The fact that your repository is pulling data from the DB and adding some behavior on top of it is clear indication of this. The way to solve this is simple. Leave the data loading logic in repository and create separate class for doing the additional logic.


答:
There is a significant difference between how an AST is typically depicted in test (a tree with numbers/variables at the leaf nodes and symbols at interior nodes) and how it is actually implemented.

The typical implementation of an AST (in an OO language) makes heavy use of polymorphism. The nodes in the AST are typically implemented with a variety of classes, all deriving from a common ASTNode class. For each syntactical construct in the language you are processing, there will be a class for representing that construct in the AST, such as ConstantNode (for constants, such as 0x10 or 42), VariableNode (for variable names), AssignmentNode (for assignment operations), ExpressionNode (for generic expressions), etc.

Each specific node type specifies if that node has children, how many and possibly of what type. A ConstantNode will typically have no children, an AssignmentNode will have two and a ExpressionBlockNode can have any number of children.

The AST gets built by the parser, who knows what construct it has just parsed, so it can construct the right kind of AST Node.

When traversing the AST, the polymorphism of the nodes comes really into play. The base ASTNode defines the operations that can be performed on the nodes, and each specific node type implements those operations in the specific way for that particular language construct.


问:
How can I convince management to deal with technical debt?
This is a question that I often ask myself when working with developers. I've worked at four companies so far and I've become aware of a lack of attention to keeping code clean and dealing with technical debt that hinders future progress in a software app. For example, the first company I worked for had written a database from scratch rather than use something like MySQL and that created hell for the team when refactoring or extending the application. I've always tried to be honest and clear with my manager when he discusses projections, but management doesn't seem interested in fixing what's already there and it's horrible to see the impact it has on team morale.

What are your thoughts on the best way to tackle this problem?
What I've seen is people packing up and leaving. The company then becomes a revolving door with developers coming in and out and making the code worse. How do you communicate this to management to get them interested in sorting out technical debt?

答:
I take it you have never been involved in a project to re-write/replace or even upgrade and existing system.

These are some of the hardest projects to complete successfully. Some of the problems you will come accross are:

Business rules are lost in time.

Documentation and implementation are totally out of sync.

What you see as a bug the users see as a feature.

Conversely many "features" will be viewed as defects by the users.

You will not get user buy in -- they will regards your "fact finding" as "nerds asking stupid questions", they will regard the testing effort as a waste of time, they will insist on adding new features thus lengthening a project will will already be behind schedule.

Chances are the source code does not match 100% with the running executable.

While your department is messing around refactoring development the business actually wants is not being done.

Chances are that your re-factoring will involve "cleaner improved interfaces" thus dragging other projects into your quagmire of late delivery and failed tests.

After the project is canned (well over 50% of these efforts fail completely) you will have lost all creditability -- you will need to move to another company in another town to find someone prepared to listen too you.

If the project "succeeds"  everyone will remember what a nightmare it was -- you will .......

I urge you to avoid any re-writes/refactoring projects like the plague, they can be some of the most dispiriting experiences in any professionals career.

There is much wisdom in the phrase "If it ain't broke don't fix it".


问:
Do you think asking to sign contributor license agreement for a open source project creates a resistance for contributors?
I am working on a open-source project which is backed by an organization. Organization pays a team to make this open-source project. This project will be licensed with GPLv3.

We are debating on having a CLA for contributors. Do you think mandating a CLA will reduce the number of contributors? I have observed that people have no issues in signing a CLA when the project is really popular.

So do you think CLA will create a resistance to contribute?

答:
A CLA does create a huge resistance for contributing. It requires the potential contributor -often a software developer- to lobby the lawyers and managers of his organization (which may means months of painful, boring, unpleasant, internal lobbying) and to get a legal document signed by official representatives of his organization (in a large corporation, it is difficult). That contributor won't make the effort for an unknown free software (he/she might make that painful effort for a very popular software).

CLA are probably easier to accept in very small organizations like small start-ups or SMEs -because the developer can just go directly ask his boss = the SME owner or manager-, but people working in them are less likely to contribute to an external free software project.

It also remove the possibility of small contributions (someone sending you a few dozen lines of patches won't bother to get the CLA signed, and if the CLA is necessary to submit the patch, he won't even start working on that small patch), and this is how you get initial contributors.

So as a software developer and free software friend, I would tell you to avoid CLAs.

Of course, the lawyers of your organization will tell you the opposite (because lawyers also need to prove themselves useful, and because they can find horror stories, or because they think of relicensing the free software....).

BTW, lack of a formal CLA procedure is perhaps one of the reasons making github so successful.

I believe you first should make your free software popular and successful and attract small contributors; for that you need to avoid CLA.

In case it is not clear, I am advising not have any CLA at all, not adding some CLA later.


问:
If there's no problem treating a statement as an expression, why was there a distinction in the first place in some programming languages?
Why do we have the distinction between statements and expressions in most programming languages?

For example, in Java, assuming f and g return ints, this still won't compile because it's a statement and statements don't return values.

```<code>// won't compile
int i = if (pred) {
    f(x);
} else {
    g(x);
}
</code>```

but in Scala, it's very happy with treating if as an expression.

```<code>// compiles fine
val i: Int = if (pred) f(x) else g(x)
</code>```

So if there's no problem treating an if statement as an expression, why was there a distinction in the first place?

答:
The if could return a value here because both of the functions also return values. But there are void functions as well, and f and g might have different return types, which would make it unclear what the type of this if would be. In effect, if you ban statements from a programming language, you also ban void methods, strict typing and some more common constructs that a lot of people don't want to see go.

(And yes, I am aware that other people would be very glad to see them go and will tell me and you and everyone at great length and high volume how glad they would be - this is a Holy war, please don't fuel it.)


答:
Yes, a CLA will create resistance. It's meant to do that.

The CLA will give your organization more posibilities with the source like, license the source commercially or make their own non-opensource products.

But it's always a tradeoff: you lose potential contributors that would have contributed without a CLA.

If that's worth it, is up to you and your organization. But either way you better choose from the start. Because if you want to add a CLA later you have to go back to all previous contributors and have them also sign it.

Title: Do you think asking to sign contributor license agreement for a open source project creates a resistance for contributors?

Body:
I am working on a open-source project which is backed by an organization. Organization pays a team to make this open-source project. This project will be licensed with GPLv3.

We are debating on having a CLA for contributors. Do you think mandating a CLA will reduce the number of contributors? I have observed that people have no issues in signing a CLA when the project is really popular.

So do you think CLA will create a resistance to contribute?


问:
MVC helper functions business logic
I am creating some helper functions (mvc.net) for creating common controls that I need in almost every project such as alert boxes, dialogs etc.

If these do not contain any business logic and it's just client side code (html, js) then it's ok. My problem arises when I need some business logic behind this helper.

I want to create a 'rate my (web) application' control that will be visible every 3 days and the user may hide it for now, navigate to rate link or hide it for ever.

To do this I need some sort of database access and a code that acts as business logic. Normally I would use a controller for this, with my DI and everything, but I don't know where to put this code now.

This should be placed in the helper function or in a controller that responds objects instead of ActionResults?

答:
As the business logic for these helper components will likely differ from project to project, I would split those helpers into two parts:

One part that must be implemented by each project separately and that provides answers to business-logic questions like: "should I show this control".

A second, reusable, part that does not contain any actual business logic, but depends on the first part to provide the answers.

The part providing the business logic for the helper component should probably live in the project's Model part, and the project's Controller would be responsible for hooking up the helper with its business logic.

Title: MVC helper functions business logic


答:
Because it is confusing, therefore it is easier to introduce bugs.

One of the most famous in C is: if (a = b) instead of if (a == b). With a distinction between expressions and statements, the compiler would have complained.

Going on with C, there is a specific form of if whenever it should return a value:

```<code>pred ? f(x) : g(x)
</code>```

Title: If there's no problem treating a statement as an expression, why was there a distinction in the first place in some programming languages?

Body:
Why do we have the distinction between statements and expressions in most programming languages?

For example, in Java, assuming f and g return ints, this still won't compile because it's a statement and statements don't return values.

```<code>// won't compile
int i = if (pred) {
    f(x);
} else {
    g(x);
}
</code>```

but in Scala, it's very happy with treating if as an expression.

```<code>// compiles fine
val i: Int = if (pred) f(x) else g(x)
</code>```

So if there's no problem treating an if statement as an expression, why was there a distinction in the first place?

Body:
Because it is confusing, therefore it is easier to introduce bugs.

One of the most famous in C is: if (a = b) instead of if (a == b). With a distinction between expressions and statements, the compiler would have complained.

Going on with C, there is a specific form of if whenever it should return a value:

pred ? f(x) : g(x)


问:
Interface (contract), Generics (universality), and extension methods (ease of use). Is it a right design?
I'm trying to design a simple conversion framework based on these requirements:

All developers should follow a predefined set of rules to convert from the source entity to the target entity

Some overall policies should be able to be applied in a central place, without interference with developers' code

Both the creation of converters and usage of converter classes should be easy

To solve these problems in C# language, A thought came to my mind. I'm writing it here, though it doesn't compile at all. But let's assume that C# compiles this code:

I'll create a generic interface called IConverter

```<code>public interface IConverter<TSource, TTarget>
    where TSource : class, new()
    where TTarget : class, new()
{
    TTarget Convert(TSource source);

    List<TTarget> Convert(List<TSource> sourceItems);
}
</code>```

Developers would implement this interface to create converters. For example:

```<code>public class PhoneToCommunicationChannelConverter : IConverter<Phone, CommunicationChannle>
{
    public CommunicationChannel Convert(Phone phone)
    {
        // conversion logic
    }

    public List<CommunicationChannel> Convert(List<Phone> phones)
    {
        // conversion logic
    }
}
</code>```

And to make the usage of this conversion class easier, imagine that we add static and this keywords to methods to turn them into Extension Methods, and use them this way:

```<code>List<Phone> phones = GetPhones();
List<CommunicationChannel> channels = phones.Convert();
</code>```

However, this doesn't even compile. With those requirements, I can think of some other designs, but they each lack an aspect. Either the implementation would become more difficult or chaotic and out of control, or the usage would become truly hard. Is this design right at all? What alternatives I might have to achieve those requirements?

答:
I had to specify a lot of custom type conversions in my project and had a lot of success just using a piece of code from the EmitMapper project

Emitmapper : StaticConvertersManager.cs

You can just create classes with static functions which have a param with one type and return another type and you can register these then with this manager

Saved me a lot of time


答:
As a hobbyist open source contributor I would never contribute for free to a project which makes me sign a CLA. When I contribute open source code in my free-time, I do so because I want to help the greater good. I don't want my voluntary contribution to get relicensed under a proprietary license later. Lack of a CLA guarantees to me that my work will stay open source.

I would, however, willingly sign a CLA when I get paid for my work.


问:
What is the value of a let expression
From what I understand, every code in f# is an expression, including let binding.
Say we got the following code:

```<code>let a = 5
printfn "%d" a
</code>```

I've read that this would be seen by the compiler as

```<code>let a = 5 in
(
     printfn "%d" a
)
</code>```

And so the value of all this would be value of inner expression, which is value of printf. On the other hand, in f# interactive:

```<code>> let a = 5;;
val a : int = 5
</code>```

Which clearly indicates that the value of let expression is the value bound to the identifier.

Q: Can anyone explain what is the value of a let expression? Can it be different in compiled code than in F# interactive?

答:
There are several contexts in F# where a let may appear, including:

The context of module definitions, where value definitions use the let keyword.  Definitions do not return or have a value in the same sense as expressions.

The context of expressions, where value definition expressions use the let keyword.  To simplify, value definition expressions are basically of the form let p = i in b, where p is a pattern and i and b are expressions, and the value of such an expressions is the value of the b expression.

The context in F# interactive is like the context of module definitions.  In the case of value definitions, the F# interactive helpfully prints out some information on the defined value.

Note that the above contexts are not the only contexts where let appears.  For example, class type definitions may contain value definitions using the let keyword.  See The F# Language Specification for more details.

Title: What is the value of a let expression


问:
Interface design where functions need to be called in a specific sequence
The task is to configure a piece of hardware within the device, according to some input specification. This should be achieved as follows:

1) Collect the configuration information. This can happen at different times and places. For example, module A and module B can both request (at different times) some resources from my module. Those 'resources' are actually what the configuration is.

2) After it is clear that no more requests are going to be realized, a startup command, giving a summary of the requested resources, needs to be sent to the hardware.

3) Only after that, can (and must) detailed configuration of said resources be done.

4) Also, only after 2), can (and must) routing of selected resources to the declared callers be done.

A common cause for bugs, even for me, who wrote the thing, is mistaking this order. What naming conventions, designs or mechanisms can I employ to make the interface usable by someone who sees the code for the first time?

答:
You just need to document correctly how the interface is used, and give a tutorial example.

You may also have a debugging library variant which does some runtime checks.

Perhaps defining and documenting correctly some naming conventions (e.g. preconfigure*, startup*, postconfigure*, run*....)

BTW, a lot of existing interfaces follow a similar pattern (e.g. X11 toolkits).


答:
It's a redesign but you can prevent misuse of many APIs but not having available any method that shouldn't be called.

For example, instead of first you init, then you start, then you stop

Your constructor inits an object that can be started and start creates a session that can be stopped.

Of course if you have a restriction to one session at a time you need to handle the case where someone tries to create one with one already active.

Now apply that technique to your own case.

Title: Interface design where functions need to be called in a specific sequence

Body:
The task is to configure a piece of hardware within the device, according to some input specification. This should be achieved as follows:

1) Collect the configuration information. This can happen at different times and places. For example, module A and module B can both request (at different times) some resources from my module. Those 'resources' are actually what the configuration is.

2) After it is clear that no more requests are going to be realized, a startup command, giving a summary of the requested resources, needs to be sent to the hardware.

3) Only after that, can (and must) detailed configuration of said resources be done.

4) Also, only after 2), can (and must) routing of selected resources to the declared callers be done.

A common cause for bugs, even for me, who wrote the thing, is mistaking this order. What naming conventions, designs or mechanisms can I employ to make the interface usable by someone who sees the code for the first time?


答:
This is indeed a common and insidious kind of error, because compilers can only enforce syntax conditions, while you need your client programs to be "grammatically" correct.

Unfortunately,   naming conventions are almost entirely ineffective against this kind of error. If you really want to encourage people not to do ungrammatical things, you should pass out a command object of some kind that must be initialized with values for the preconditions, so that they can't perform the steps out of order.


答:
Another complication on Windows is that it also supports UNC notation as well as the traditional drive letters.

A file on a remote file server can be accessed as \\server\sharename\path\filename.


问:
Dependency Injection: where to store dependencies used by only one method?
I am developing a project integrated with Dependency Injection (just for reference, I'm using Unity).

The problem is that I have some Manager classes with several methods and in many cases I have dependencies used only in one method.

```<code>public class UserReportManager : IUserManager
{
    private UserRepository  UserRepository  {get;set;}
    private TeamRepository   TeamRepository   {get;set;}
    private CacheRepository   CacheRepository   {get;set;}
    private WorkgroupRepository   WorkgroupRepository   {get;set;}

    public UserManager(UserRepository userRepository,
                       TeamRepository teamRepository,
                       CacheRepository cacheRepository ,
                       WorkgroupRepository workgroupRepository,
                       ... // Many other dependencies
                      )
    {
        UserRepository  = userRepository;
        TeamRepository = teamRepository;
        CacheRepository = cacheRepository ;
        WorkgroupRepository = workgroupRepository;
        ... // Setting the remaining dependencies
    }

    public void CreateReportAboutMostActivesUsers(){
        // Uses only UserRepository
    }

    public void CreateReportAboutUserInsideTeams(int teamID){
        // Uses UserRepository and TeamRepository
    }

    public void CreateReportAboutUserHistory(){
        // Uses UserRepository and CacheRepository
    }

    public void CreateReportAboutUsersInsideWorkgroup(int workgroupID){
        // Uses UserRepository and WorkgroupRepository
    }
}
</code>```

The UserManager is instantiated in this way:

```<code>DependencyFactory.Resolve<IUserManager>();
</code>```

Note: DependencyFactory is just a wrapper to simplify the access to the UnityContainer

Is it OK to have classes like that in the example? Is there a better way to implement avoiding to instantiate all the unnecessary dependencies?

答:
You don't need a user manager, what you need is to create an interface for each repository.

So you will have IUserRepository, ITeamRepository and go on.

After that you have to separate the logic from the factory using two different projects, I use to call the logic project DAL and the factory Resolver.
You have to do this because if for example you are actually using Sql Server to access your repositories and for some reason you will decide to use EF you have to rewrite the Factory code that it is wrong. Factory must be generic so if you will decide to use EF you have just to create a new DAL, using the same interfaces and just use EF logic, after that you will reference the new DAL instead of the old one in the Factory project and everything will work again.

So create a DAL project, create a class for each repository inheriting from the correct interface (interfaces must be in a third project that I use to call dependencies and must be referenced from both DAL and Resolver) add to the interface the methods sign for the methods that you need like:

```<code>public interface IUserRepository
{
    void GetLatestUser(); // get with void makes no sense
}
</code>```

than in your factory all that you need is just to register the interface with the implementation:

```<code>container.RegisterType<IUserRepository, UserRepository>();
</code>```

PS: you don't need this:

```<code>public class DependencyFactory<T> //but just

public static class DependencyFactory
</code>```

And at the end to obtain your repository you just need to add this function to your factory:

```<code>public static T Resolve<T>()
{
    var result = default(T);

    if (Container.IsRegistered(typeof(T)))
    {
        result = Container.Resolve<T>();
    }

    return result;
}
</code>```

Body:
You don't need a user manager, what you need is to create an interface for each repository.

So you will have IUserRepository, ITeamRepository and go on.

After that you have to separate the logic from the factory using two different projects, I use to call the logic project DAL and the factory Resolver.
You have to do this because if for example you are actually using Sql Server to access your repositories and for some reason you will decide to use EF you have to rewrite the Factory code that it is wrong. Factory must be generic so if you will decide to use EF you have just to create a new DAL, using the same interfaces and just use EF logic, after that you will reference the new DAL instead of the old one in the Factory project and everything will work again.

So create a DAL project, create a class for each repository inheriting from the correct interface (interfaces must be in a third project that I use to call dependencies and must be referenced from both DAL and Resolver) add to the interface the methods sign for the methods that you need like:

public interface IUserRepository
{
    void GetLatestUser(); // get with void makes no sense
}

than in your factory all that you need is just to register the interface with the implementation:

container.RegisterType<IUserRepository, UserRepository>();

PS: you don't need this:

public class DependencyFactory<T> //but just

public static class DependencyFactory

And at the end to obtain your repository you just need to add this function to your factory:

public static T Resolve<T>()
{
    var result = default(T);

    if (Container.IsRegistered(typeof(T)))
    {
        result = Container.Resolve<T>();
    }

    return result;
}


问:
Finding a way to simplify complex queries on legacy application
I am working with an existing application built on Rails 3.1/MySql with much of the work taking place in a JavaScript interface, although the actual platforms are not tremendously relevant here, except in that they give context.

The application is powerful, handles a reasonable amount of data and works well. As the number of customers using it and the complexity of the projects they create increases, however, we are starting to run into a few performance problems. As far as I can tell, the source of these problems is that the data represents a tree and it is very hard for ActiveRecord to deterministically know what data it should be retrieving.

My model has many relationships like this:

```<code>Project
   has_many Nodes
   has_many GlobalConditions

Node
   has_one Parent
   has_many Nodes
   has_many WeightingFactors through NodeFactors
   has_many Tags through NodeTags

GlobalCondition
   has_many Nodes ( referenced by Id, rather than replicating tree )

WeightingFactor
   has_many Nodes through NodeFactors

Tag
   has_many Nodes through NodeTags
</code>```

The whole system has something in the region of thirty types which optionally hang off one or many nodes in the tree.

My question is: What can I do to retrieve and construct this data faster?

Having worked a lot with .Net, if I was in a similar situation there, I would look at building up a Stored Procedure to pull everything out of the database in one go but I would prefer to keep my logic in the application and from what I can tell it would be hard to take the queried data and build ActiveRecord objects from it without losing their integrity, which would cause more problems than it solves.

It has also occurred to me that I could bunch the data up and send some of it across asynchronously, which would not improve performance but would improve the user perception of performance. However if sections of the data appeared after page load that could also be quite confusing.

I am wondering whether it would be a useful strategy to make everything aware of it's parent project, so that one could pull all the records for that project and then build up the relationships later, but given the ubiquity of complex trees in day to day programming life I wouldn't be surprised if there were some better design patterns or standard approaches to this type of situation that I am not well versed in.

答:
whether it would be a useful strategy to make everything aware of it's parent project

That is a standard strategy. It is called "denormalization". Assumed

your "project elements" never change the project they belong to

your project's primary ID key will never change

the additional memory needed for the IDs is no problem

it actually solves your performance problems

you should apply it.

Another approach is trying to add some views to your database, encapsulating some complex JOIN operations (I assume your database is properly indexed so the JOIN itself won't slow down things more than necessary). I never used Rails by mayself, but AFAIK ActiveRecord will work on views. So for example by joining 2 tables of a parent-child relationship together, instead of having a first SELECT SQL to determine a set of parent objects, and a list of SELECT SQLs, each one for the set of child objects of a specific parent ID, you pull all your data from the joined view with just one select SQL. Of course, this will work best when you need the data in joined form and don't want to write changes back to your DB system.


答:
Why is the purpose of this UserManager class?, you can use your repos directly when you need them. The name "Manager" its normally and advise of a class with a lot of or unclear responsibilities, who knows what a "manager" does?.

Other thing looks a little strange in your design its that looks like if you are creating one repository per table or storage (this cache repo) more than one repository per entity/aggregate like the original proposal in Domain Driven Design.

For example, you have a teamRepository instead of having a method findByTeam in the user repository. I expect a teamRepository return me "teams" not users. Think in a repository as an abstraction to access the user entity whatever this users really are. Inside this repo implementation you can off course access different tables or storage systems to get those users.

About the original question, in general if you have N dependencies in a class and each dependency is only used in one method you have a cohesion problem in your class, this is a bad symptom, is an "alarm" to revise your design.

Title: Dependency Injection: where to store dependencies used by only one method?

Body:
I am developing a project integrated with Dependency Injection (just for reference, I'm using Unity).

The problem is that I have some Manager classes with several methods and in many cases I have dependencies used only in one method.

```<code>public class UserReportManager : IUserManager
{
    private UserRepository  UserRepository  {get;set;}
    private TeamRepository   TeamRepository   {get;set;}
    private CacheRepository   CacheRepository   {get;set;}
    private WorkgroupRepository   WorkgroupRepository   {get;set;}

    public UserManager(UserRepository userRepository,
                       TeamRepository teamRepository,
                       CacheRepository cacheRepository ,
                       WorkgroupRepository workgroupRepository,
                       ... // Many other dependencies
                      )
    {
        UserRepository  = userRepository;
        TeamRepository = teamRepository;
        CacheRepository = cacheRepository ;
        WorkgroupRepository = workgroupRepository;
        ... // Setting the remaining dependencies
    }

    public void CreateReportAboutMostActivesUsers(){
        // Uses only UserRepository
    }

    public void CreateReportAboutUserInsideTeams(int teamID){
        // Uses UserRepository and TeamRepository
    }

    public void CreateReportAboutUserHistory(){
        // Uses UserRepository and CacheRepository
    }

    public void CreateReportAboutUsersInsideWorkgroup(int workgroupID){
        // Uses UserRepository and WorkgroupRepository
    }
}
</code>```

The UserManager is instantiated in this way:

```<code>DependencyFactory.Resolve<IUserManager>();
</code>```

Note: DependencyFactory is just a wrapper to simplify the access to the UnityContainer

Is it OK to have classes like that in the example? Is there a better way to implement avoiding to instantiate all the unnecessary dependencies?