答:
Asking for help is really the best answer, but here's a little more that may be useful.

So for those who have been in industry
  for any longer length of time, what
  would happen if you were told to solve
  a problem that you couldn't? Has it
  happened, and if so, what did happen?
  Did they just drop it and said "Oh
  well, guess we can make do with
  something else"? Were there
  consequences? Were you reprimanded, or
  even fired?

Yes, it's happened to me, and no, I never got reprimanded or fired for it, because...

In industry, it's all about whether you solve problems on time and within budget, and decent managers understand that's not always possible.

What really happens is your manager says, "I'd like you to do X, what do you think it will take?" And you can give lots of answers. Good ones include:

I've done something really similar to this, so I think it will take three weeks and $3,000 worth of testing hardware.

I've something generally similar to this. So let me think about it and get back to you this afternoon.

I've never done anything like this. So let me research it and get back to you tomorrow.

Nobody on the planet has ever done this. If you want to look into it, it will take me two weeks to do enough experimentation to make an estimate.

It's the manager's job to decide whether and how to proceed. If they do choose to proceed, it's your job to meet your estimates, or let the manager know if there's an impediment. As long as you do that, in a reasonable company there won't be negative consequences.

Of course, there are also unreasonable companies that don't give you the time or resources to get your job done. I've worked at some of those, and everybody was handed problems that couldn't be solved within the company's constraints. One of them laid off about 98% of the programming staff within eight months, and that certainly was a consequence, but it wasn't personally directed at me, and I still consider my boss and his boss from there to be good friends.

Title: What happens if you're unable to solve a problem?

Body:
I'm a year away from graduating from university, and I'm really looking forward to solving practical problems. Especially non-trivial ones which require a bit of research and a lot of thinking.

But at the same time, that is also my greatest fear - being faced with a problem that I'm unable to solve, no matter how hard I try. And with pressure to deliver code on impending deadlines just around the corner, it does look a bit scary when viewing it from the safe playgrounds on uni (where the worst thing that can happen is that you have to redo a course or exam).

So for those who have been in industry for any longer length of time, what would happen if you were told to solve a problem that you couldn't? Has it happened, and if so, what did happen? Did they just drop it and said "Oh well, guess we can make do with something else"? Were there consequences? Were you reprimanded, or even fired?


问:
Need to provide an interface (for plugins) for taking input Type A, and returning output Type B
```<code>public interface IMyInputProviderPlugin
{
    IMyOutput Provide(IMyInput data);
}
</code>```

This is an interface I need to provide so that I can dynamically load the dlls and not have them bound to my implementation.

However, upon reading this, it seems like this is an anti-pattern?

http://blog.ploeh.dk/2011/04/27/Providerisnotapattern/

I'm confused, how does one do this if not this way?

答:
Every pattern attempts to solve one or more challenges in software design, and has a set of disadvantages. You will need to study the patterns that you can utilize in your situation and determine what suits your needs the best.

The link you shared in your question is by Mark Seeman whose book that he references in the article is primarily focused on Dependency Injection (DI). DI forces many design principles and has many advantages, and thus there are many DI containers developed in various languages that can be utilized for DI. DI container lets one apply DI more easily and a typical DI container will do lifecycle management of the various types including instantiating those. If you used DI containers, it is likely that you would not need to use the provider model.

However, in my personal experience, there are situations where one does not use a DI container and the code needs to locate a service and use it (pretty much like what you are planning to do). This pattern is called service locator pattern, and provider model can be argued to be a specialization of that design pattern. Thus, you will see that there are developers who will disagree with Mark Seeman. (FYI, read the comments if possible of both articles for disagreements).

Eventually, it comes down to you determining what suits your needs the best. I have used dependency injection as well as something similar to the provider model, and they both serve certain needs and in some cases, one is preferable over the other. For example, if I had to provide the ability of my running application to be able to load another externally provided module and manage its lifecycle without shutting the main application down, I am quite likely to go with the provider model, and will typically end up writing custom code to exert complete control over the interfaces.

IMO, you should weight the pros and cons of each approach (perhaps even prototype if needed), and go with what is most likely to work with you instead of delving too much into the question of whether it is a "pattern" or "anti-pattern".

ContentLicense: CC BY-SA 3.0


问:
How about using a DTO class as a property in the corresponding BO class?
I was reading this blog post and liked the idea of using the DTO class for an entity and using it as a property in the corresponding business object class like so:

```<code>public class Person : BALBase
{
        public PersonDTO Data { get; set; }
</code>```

This also can eliminate the need for a mapping tool like AutoMapper (mapping between POCO and DTO). I am thinking of using this concept in my app. My app is layered using straight assemblies with no web services/REST/WCF calls.

What can be the disadvantages of using this concept?

答:
The main disadvantage of this method is that you're losing any business logic and validation that your business object might enforce over the data.

What does the Person class do that the PersonDTO doesn't? Perhaps it performs validations on fields, so that setting Person.Name to an empty string is caught and an error returned. Exposing PersonDTO directly would miss that.

Perhaps the business object ensures that proper workflows are maintained. Moving a person from one department to another might require approval of a manager in the target department. Person might expose a MoveDepartment method that encapsulates this workflow logic, while exposing PersonDTO might allow a caller to change PersonDTO.Department directly.


答:
One major problem I see is that dependency is the wrong way. DTO should depend on your business layer, not other way around. It is much more possible to change DTO than it is to change business rules.

What if you want to have different type of DTO for different services? What if you want to use the business layer directly in webservice? Constraining your business layer to use one specific DTO will make all of those cases harder to implement.

Title: How about using a DTO class as a property in the corresponding BO class?

Body:
I was reading this blog post and liked the idea of using the DTO class for an entity and using it as a property in the corresponding business object class like so:

```<code>public class Person : BALBase
{
        public PersonDTO Data { get; set; }
</code>```

This also can eliminate the need for a mapping tool like AutoMapper (mapping between POCO and DTO). I am thinking of using this concept in my app. My app is layered using straight assemblies with no web services/REST/WCF calls.

What can be the disadvantages of using this concept?


问:
If I use LGPL-licensed images in my open-source software project, do I have to use the LGPL for the whole project?
...or, can I license things separately within the project (i.e. images=LGPL, code=GPL).  I've been confused about this for a little while now and I can't seem to find a clear answer.</p>

答:
It is very common, and with GPL-style software licenses almost a requirement, to use different licenses for the source code and the artwork/images.

Just like that Creative Commons licenses are a bad fit for software, software copyright licenses are also a bad fit for non-software works, like images.

Especially the LGPL is a bad fit for images, because the clauses about linking, that separate it from the GPL, don't seem to have a meaning for images but they might have unexpected legal consequences.

The best option for a project that consists of both software and images is to use separate licenses for the two parts, with a Creative Commons license for the images and a software license (like GPL) for the code.

As far as copyright is concerned, the code and images can be regarded as separate works and that is the reason you can use separate licenses.


问:
observer class as instance
Sometimes I read in observer-pattern descriptions, to make the constructor of a observer base class protected so the class will be abstract. but by making the constructor public (if even one is neccessary), I could use the observer as an instance and not only as base-class.

Is there any disadvantage of doing so i'm not mentioned yet?

答:
The idea of the Observer pattern is to allow an object to register for updates from another object, without the other object having to know about the actual type of the observer.

In statically typed languages such as Java or C++, this is done by having the class of the object that needs to register for updates, inherit from the Observer class or implement the Observer interface. This is so it could be regarded as an Observer and register as an observer to any class that allows this, without that class knowing about the actual type of the registering observer.

The class allowing objects to register for notifications (called 'the subject') provides a public method registerObserver(Observer o), and thanks to Polymorphism any class that inherits from the Observer class or implements the Observer interface can register.

The Observer class or interface will have a method notifyObserver(), which the subject can call on all the observers registered to it - again, without caring about their concrete type.

This shows you that it makes no sense to instantiate an Observer on it's own. And this is why you define the Observer class as abstract, or in single-inheritance languages as an Interface.

Also, keep in mind that in single-inherited languages such as C# or Java, it's much better to define an Observer interface, and not an Observer class, because if a class inherits from Observer it can't inherit from anything else which is very limiting. However some single-inherited languages support Interfaces, so your classes can implement an Observer interface while still being able to inherit from another class.

Another thing to remember is that conceptually, a class defines an object's type while an Interface defines what an object can do. All your subject cares about is that objects can observe it, it doesn't care what they are. So conceptually an Observer Interface is a better option than a class (unless you use a language like C++ which doesn't have Interfaces but has multiple-inheritance).

Title: observer class as instance


问:
What happens if you're unable to solve a problem?
I'm a year away from graduating from university, and I'm really looking forward to solving practical problems. Especially non-trivial ones which require a bit of research and a lot of thinking.

But at the same time, that is also my greatest fear - being faced with a problem that I'm unable to solve, no matter how hard I try. And with pressure to deliver code on impending deadlines just around the corner, it does look a bit scary when viewing it from the safe playgrounds on uni (where the worst thing that can happen is that you have to redo a course or exam).

So for those who have been in industry for any longer length of time, what would happen if you were told to solve a problem that you couldn't? Has it happened, and if so, what did happen? Did they just drop it and said "Oh well, guess we can make do with something else"? Were there consequences? Were you reprimanded, or even fired?

答:
It depends on what the specific problem is, obviously.  But the response can be any of :

Find a workaround/substitution

Buy a commercial solution that approximates what you want

Dont give up and keep working at it as long as you need to until you succeed.

Number 3 may require time off from the problem and revisiting it weeks or months later.  That often helps.

ContentLicense: CC BY-SA 2.5


问:
I don't know how to understand the Wildcard type in Java
I am reading the Core Java (9th edition) by Cay S. Horstmann and Gary Cornell. After making an effort, I cannot still understand the ? super Manager. Here are some materials relating to this question.

```<code>public class Pair<T> {
    private T first;
    private T second;

    public Pair(T first, T second) {
        this.first = first;
        this.second = second;
    }

    public void setFirst(T first) {
        this.first = first;
    }

    public void setSecond(T second) {
        this.second = second;
    }

    public T getFrist() {
        return this.first;
    }

    public T getSecond() {
        return this.second;
    }
}
</code>```

The Manager inherits from Employee, and Executive inherites from Manager. Pair has methods as follows:

```<code>void setFirst(? super Manager)
? super Manager getFirst()
</code>```

Since ? super Manager denotes any supertype of Manager, why I cannot call setFirst method with Employee (it is obvious that Employee is the supertype of Manager), but only with type Manager or a subtype such as Executive(but Executive is the subtype of Manager, not a supertype of Manager)?

答:
One can read and re-iterate it over and over again - as it has been many times already. In a comment to your question, Philipp already linked to a question on Stackoverflow which tries to answer it. For me, the explanation of Uncle Bob did the trick.

He writes (next to a lot of other good stuff):

A List<? super Shape> is a list into which you may add Shapes. Another way to think of this is that the type <? super T> is an unknown type that T can substitute for. You may have to read that several times before you understand it. I certainly did. So here's yet another way to think about it. The type <? super T> is a type that T is derived from. It is a base class of T. Clearly if D is derived from B then you can put D instances into a List. Likewise, since T derives from <? super T>, you can put T instances into a List<? super T>. Follow? No? Neither did I for awhile. It takes a bit of getting used to.

What this means in the end is that your assumption you'd be able to put super-types of Manager into your List<? super Manager> is wrong. That's not what is meant here. The super keyword solves the problem of not being able to insert stuff into generic places while you were able to get some out (with extends).

Imagine two pairs, one that extends Manager, one that "supers" it:

```<code>Pair<? extends Manager> subPair = new Pair<Manager>();
Pair<? super Manager> superPair = new Pair<Manager>();
</code>```

What you can never do, is insert an Employee in any of these:

```<code>subPair.setFirst(new Employee());
superPair.setFirst(new Employee());
</code>```

If you want managers, employees will never be enough. And it's worse: you can't even insert an Executive into your subPair, even though Executive extends Manager. It won't compile either:

```<code>subPair.setFirst(new Executive());
</code>```

Edit:
Why is that? Well, your generic subPair always refers to some "explicit" Pair, Pair<Manager> in this case. It just as well might have referred to a Pair<CoManager> (with CoManager extends Manager). Java won't know the explicit type that's actually used and thus can't allow you insertions.

But super comes to the rescue. With super you can insert Managers and their sub-types into your Pair. And that is what super is for: Inserting.

```<code>superPair.setFirst(new Executive());
</code>```

Edit: Any why does that work? While extends guarantees you some type that implements (or derives from) Manager, super guarantees you any such type. So, while with extends you get a specific type with (at least) the Manager interface, with super you can insert any type with the Manager interface.

And for the bigger picture, I really suggest reading the article of Uncle Bob.

Body:
One can read and re-iterate it over and over again - as it has been many times already. In a comment to your question, Philipp already linked to a question on Stackoverflow which tries to answer it. For me, the explanation of Uncle Bob did the trick.

He writes (next to a lot of other good stuff):

A List<? super Shape> is a list into which you may add Shapes. Another way to think of this is that the type <? super T> is an unknown type that T can substitute for. You may have to read that several times before you understand it. I certainly did. So here's yet another way to think about it. The type <? super T> is a type that T is derived from. It is a base class of T. Clearly if D is derived from B then you can put D instances into a List<B>. Likewise, since T derives from <? super T>, you can put T instances into a List<? super T>. Follow? No? Neither did I for awhile. It takes a bit of getting used to.

What this means in the end is that your assumption you'd be able to put super-types of Manager into your List<? super Manager> is wrong. That's not what is meant here. The super keyword solves the problem of not being able to insert stuff into generic places while you were able to get some out (with extends).

Imagine two pairs, one that extends Manager, one that "supers" it:

Pair<? extends Manager> subPair = new Pair<Manager>();
Pair<? super Manager> superPair = new Pair<Manager>();

What you can never do, is insert an Employee in any of these:

subPair.setFirst(new Employee());
superPair.setFirst(new Employee());

If you want managers, employees will never be enough. And it's worse: you can't even insert an Executive into your subPair, even though Executive extends Manager. It won't compile either:

subPair.setFirst(new Executive());

Edit:
Why is that? Well, your generic subPair always refers to some "explicit" Pair, Pair<Manager> in this case. It just as well might have referred to a Pair<CoManager> (with CoManager extends Manager). Java won't know the explicit type that's actually used and thus can't allow you insertions.

But super comes to the rescue. With super you can insert Managers and their sub-types into your Pair. And that is what super is for: Inserting.

superPair.setFirst(new Executive());

Edit: Any why does that work? While extends guarantees you some type that implements (or derives from) Manager, super guarantees you any such type. So, while with extends you get a specific type with (at least) the Manager interface, with super you can insert any type with the Manager interface.

And for the bigger picture, I really suggest reading the article of Uncle Bob.


问:
Should I released my plugins AGPL
I am using ownCloud - which is AGPL license - and only create few custom modules, and a theme, the core is not touched at all so:

should I allow download source for the whole app ( owncloud and my modules/theme ) ? ( as it is agpl based )

or should I only provide link to download owncloud code ( the original code ) ?

Or don't have to allow download at all ( optional )?

Considering that, I am building a commercial app, where users will pay for the service?
Please advice,

答:
The AGPL license is a variant of the GPL license with a broader view on distribution of the software. The main difference between GPL and AGPL is that the latter also considers accessing an application remotely as distributing it.

The core precepts of the GPL (and AGPL) are

If you distribute an application, you must also distribute the source code

Even if only part of the application is copyrighted under (A)GPL, the first point applies to every part of the application.

This means that, if your modules interact with ownCloud or otherwise form a single 'application' with it, then you must release your modules under the AGPL license as well (or a license that gives them at least as much rights on the source code) and you must provide access to the sources of your modules.

It might be possible to create a successful commercial app based on it, but you won't be able to compete on features. So, you will need other attractors for subscriptions, such as superior content, customer service, etc. Whether that is achievable can only you decide.

Title: Should I released my plugins AGPL


问:
Why are most functional programming languages also interpreted languages?
Functional/non-functional and interpreted/compiled are two different categorizations, yet it seems that there are a lot of overlaps in the programming languages that fall under those categories. Is this a coincidence?</p>

答:
There is no such thing as an "interpreted language". A language is a set of abstract mathematical rules. A language isn't interpreted or compiled, it just is. Interpretation and compilation are traits of, well, the interpreter or compiler (duh!), not the language.

A language is an abstract entity, an interpreter or compiler is a concrete implementation of that abstraction. The two live on completely different levels of abstraction. The term "interpreted language" is not just wrong, it doesn't even make sense. If English were a typed language, "interpreted language" would be a type error!

You can't ask whether a language is an interpreted language, the answer isn't "yes" or "no", because the question itself is non-sensical. It's like asking whether orange is a prime number.

Every language can be implemented with an interpreter, and every language can be implemented with a compiler. You can automatically derive a compiler from an interpreter and an interpreter from a compiler.

The vast majority of languages have both compiled and interpreted implementations. The vast majority of modern high-performance language implementations are mixed-mode implementations which combine interpretation and compilation.

Now, let's look at some popular functional languages and some of their popular implementations:

Haskell

GHC, the Glorious Glasgow Haskell Compiler: obviously a compiler

UHC, the Utrecht Haskell Compiler: again, a compiler

JHC, also a compiler

HUGS (no longer maintained): an interpreter

Standard ML

SML/NJ (Standard ML of New Jersey): a compiler

MLton: a compiler

ML Kit: a compiler

Moscow ML: a compiler

TILT: a compiler

SML.NET: a compiler

Alice: an interpreter

OCaml: there is only one implementation of OCaml, a compiler

F♯: there is only one implementation of F♯ (Microsoft Visual F♯), a compiler

Scala: there is only one implementation of Scala, a compiler

Clojure

Clojure: a compiler for the Java platform

ClojureCLR: a compiler for the CLI platform

ClojureScript: a compiler for the ECMAScript platform

Scheme

Racket: compiles Scheme to bytecode, then either interprets or compiles that byte code

Stalin: a compiler

Gambit: a compiler

CHICKEN: a compiler

Ikarus: a compiler

Larceny: a compiler

IronScheme: a compiler

Bigloo: a compiler

Kawa: an interpreter

Gauche: an interpreter


问:
Is is OK to use a non-primary key as the id in a rails resource?
I am getting ready to set up a resource for some new api calls to my rails application.

I am planning on calling the resource devices ie

```<code>resources :devices
</code>```

This is going to represent android mobile devices

I know this will get me routes such as

GET devices/:id

In most cases :id would be an integer representing the primary key, and in the controller we would use :id as such:

```<code>GET devices/1
@device = Device.find(params[:id])
</code>```

In this case I would like to use :id as the google_cloud_messaging_reg_id

So I would like to have requests like this:

```<code>GET devices/some_long_gcm_id
</code>```

and then in the controller , just us params[:id] to look up the device by the gcm registration id.  This seem more natural, since the device will know it's gcm id rather than it's rails integer id.  Are there any reasons I should avoid doing this?

---------------------------------------------------------------------

UPDATE:

My initial concern was that seeing a route (via rake routes) of /devices/:id or looking at the controller and seeing params[:id] would be confusing since most would assume :id was the integer primary key.

After  thinking about it some more, and reading Idan Arye's answer below, my current thinking is to create routes like shown below.  This will get me routes (via rake routes) that look like this:

```<code>GET    /api/v1/android_devices/:gcm_reg_key(.:format)
</code>```

which I think makes it somewhat clear that :gcm_reg_key may not be a primary key integer.
And in the controller the parameter would be

```<code>params[:gcm_reg_key]
</code>```

Again, I think this makes it somewhat clear that the param may not be an integer primary key (convention would be params[:id])

Any other thoughts or suggestions are welcome.

```<code>match '/android_devices/:gcm_reg_key', to: 'android_devices#show' , via: :get, as: 'android_device'
match '/android_devices/:gcm_reg_key', to: 'android_devices#update', via: :post, as: 'android_device_create'
match '/android_devices/:gcm_reg_key', to: 'android_devices#update', via: :patch, as: 'android_device_modify'
match '/android_devices/:gcm_reg_key', to: 'android_devices#destroy', via: :delete, as: 'android_device_destroy'
resources :android_devices , only: [:create, :index]
</code>```

答:
You have to make a distinction between your database and the url, which is actually a kind of API or front to your data. There is no obligation whatsoever that what is the ID in the url, corresponds to the ID in the database.

Actually, I can give two good reasons for this ID to differ:

A hacker could guess url's of existing other devices, by just incrementing/decrementing the id. Depending on the kind of site you have, this might or might not be relevant.

A url could be more easily remembered if it is on the whole readable/meaningful. Like something like /blogs/:blog_title. And your case applies just perfectly imho.

So personally I have done almost exactly what you said, without changing the routes.

To make sure all link-helpers keep working, you just have to overrule the to_param function for a model (docs).

So in your case

```<code>class Device < ActiveRecord::Base

  def to_param
    gcm_reg_key
  end

end
</code>```

and then you can still write device_path(@device) and it will correctly form the url.

In your controller you just write

```<code>def show
  @device = Device.find_by(gcm_reg_key: params[:id])
end
</code>```

and then keep your routes as

```<code>resources :devices
</code>```

OwnerDisplayName: nPn

Body:
You have to make a distinction between your database and the url, which is actually a kind of API or front to your data. There is no obligation whatsoever that what is the ID in the url, corresponds to the ID in the database.

Actually, I can give two good reasons for this ID to differ:

A hacker could guess url's of existing other devices, by just incrementing/decrementing the id. Depending on the kind of site you have, this might or might not be relevant.

A url could be more easily remembered if it is on the whole readable/meaningful. Like something like /blogs/:blog_title. And your case applies just perfectly imho.

So personally I have done almost exactly what you said, without changing the routes.

To make sure all link-helpers keep working, you just have to overrule the to_param function for a model (docs).

So in your case

class Device < ActiveRecord::Base

  def to_param
    gcm_reg_key
  end

end

and then you can still write device_path(@device) and it will correctly form the url.

In your controller you just write

def show
  @device = Device.find_by(gcm_reg_key: params[:id])
end

and then keep your routes as

resources :devices


问:
what to do when UX asks for an ugly, convoluted event driven design and you don't know how to implement it in a clean manner?
I have been tasked with creating a desktop client application that fetches data from web apis and presents it to the user.

During the last month or so, I've spent most of my time and energy bringing to life the functionality that UX described with two pictures.

Looking at the pictures, it seems like a simple design. There are only 4 controls:

One drop down list that fires a selection event. Another drop down list that is populated based on selected data from the first drop down list and also fires a selection event. Two radio controls that enable or disable the second drop down list. A third drop down list that, depending on which radio button was last selected, is populated with data based on either the first drop down list or the second drop down list.

Doesn't seem hard.

But then when I actually start implementing this design I find that I don't know, for example, what to do with if the user selects radio button B (which is supposed to enable the second drop down list) but the drop down list has no elements; in that case, do I force the first radio button A to be reselected? Do I display an error message? Do I prompt the user for action?

It's these little 'corner' cases that don't necessarily jump at the people who request these designs that make me wonder if I'm in the wrong line of business or if I'm stuck working with people who don't have a clear picture of what they want or don't really know what they want but expect me to fill in the dots without actually doing the UX design myself.

UX is about enhancing the user's experience, not the programmer's experience, I get it, but is this the kind of input that programmers are typically expected to receive from UX? Are programmers always expected to fill in the dots, even when the proper behavior hasn't been explicitly stated?

答:
In case of doubt, ask for clarification. Maybe the UX do not know that these "corner cases" are possible.

As for the example that you write, I do not think it so complicated as you paint it. Just from common sense, you have two options:

If there are no items for the dropbox, disable option B. Add a tip (when hovering, or with an icon), stating that option B is disabled because of that.

If there is something that forbids it (for example, finding out the list of items is expensive and you only want to retrieve them once "option B" is selected, so you don't know before of that if the list is empty), when "option B" is selected change the dropbown to a label that explains that to the user.

Of course, it will depend of how much freedom do you have to do your work. If you have no freedom at all, just do your work as stated and report back possible issues. If no answers come, just do exatly what was asked (of course, at the same time document everything to CYA).


答:
You are experiencing a gap in the requirements (what to do when X goes wrong). This is not uncommon, because it is very hard to think of all possibilities up front.

What to do about it is quite simple: you ask the person responsible for the requirements/user stories/etc, to give you guidance on what the desired result should be from user perspective. Then you implement that.

If waiting for the response on your query would dangerously delay the project, then you should implement whatever is easiest to do for now and open an issue to create a proper implementation when the formal answer is known.

Title: what to do when UX asks for an ugly, convoluted event driven design and you don't know how to implement it in a clean manner?

Body:
I have been tasked with creating a desktop client application that fetches data from web apis and presents it to the user.

During the last month or so, I've spent most of my time and energy bringing to life the functionality that UX described with two pictures.

Looking at the pictures, it seems like a simple design. There are only 4 controls:

One drop down list that fires a selection event. Another drop down list that is populated based on selected data from the first drop down list and also fires a selection event. Two radio controls that enable or disable the second drop down list. A third drop down list that, depending on which radio button was last selected, is populated with data based on either the first drop down list or the second drop down list.

Doesn't seem hard.

But then when I actually start implementing this design I find that I don't know, for example, what to do with if the user selects radio button B (which is supposed to enable the second drop down list) but the drop down list has no elements; in that case, do I force the first radio button A to be reselected? Do I display an error message? Do I prompt the user for action?

It's these little 'corner' cases that don't necessarily jump at the people who request these designs that make me wonder if I'm in the wrong line of business or if I'm stuck working with people who don't have a clear picture of what they want or don't really know what they want but expect me to fill in the dots without actually doing the UX design myself.

UX is about enhancing the user's experience, not the programmer's experience, I get it, but is this the kind of input that programmers are typically expected to receive from UX? Are programmers always expected to fill in the dots, even when the proper behavior hasn't been explicitly stated?


问:
Unit testing - one test is partly a "superset" of another, is this wrong?
Wasn't sure how to phrase that title, sorry!

I've just come across this in our code base, and was wondering what the consensus was about how to unit test it:

C# (-ish, sorry, this is paraphrased from memory)

```<code>class DateCalculator
{
   public static DateTime CalculateLeadTime(DateTime deliveryDate)
   {
      //return the result of some determinate calculation involving deliveryDate
   }
}

//New example
class OrderController
{
    public ActionResult GetLeadTime(WidgetOrder order)
    {
        var leadTime = DateCalculator.CalculateLeadTime(order.GetDeliveryDate() );
        return Json(leadTime.Value.Date.ToString("dd/MM/yyyy") );
    }
}

//Old, incorrect example
class OrderService
{
   public DateTime GetLeadTime(WidgetOrder order)
   {
      return DateCalculator.CalculateLeadTime(order.GetDeliveryDate() );
   }
}
</code>```

We've then got two unit tests, one to verify that CalculateLeadTime works (this is very easy, you can put in several test values and predict what comes out), and one that GetLeadtime works (still easy, but...). My question is: what would you test here, and where?

It makes sense to me to test CalculateLeadTime in isolation, because it could be a complicated calculation, and it's already a nice small predictable unit.  But would you then go on to test some of the same stuff (maybe a single representative input and output?) in your GetLeadTime method?  Or would you simply test that any DateTime value is returned, and assume that the calculation is correct because you're testing that somewhere else?  Or would you not test the Calculate method on its own, because you know that you're going to test it when you use it, and you don't like the duplication?

EDIT: to muddy the waters a bit, I can see the code now, and rather than a Service, the calling class is an MVC Controller, and the Action under scrutiny is an AJAX method so returns the result of the calculation wrapped in JSON.  The current test verifies that JSON is returned, but not the contents of it.  Does this change anything?

答:
Ideally you should change your design a little bit and decouple OrderService from DateCalculator.CalculateLeadTime by using dependency injection:

```<code>class OrderService
{
   Func<DateTime,WidgetOrder> _calculateLeadTime;

   public OrderService(Func<DateTime,WidgetOrder> calculateLeadTime)
   {
       _calculateLeadTime=calculateLeadTime;
   }

   public DateTime GetLeadTime(WidgetOrder order)
   {
      return _calculateLeadTime(order.GetDeliveryDate() );
   }
}
</code>```

Now its easy to unit test OrderService in isolation: instead of DateCalculator.CalculateLeadTime,  pass a mock function through the constructor for your test and check if it is correctly called from the GetLeadTime. This changes the situation so the meaningful tests for OrderService are not a superset of the tests for DateCalculator any more.

Of course, you may add an integration test to your test suite, which checks if OrderService.GetLeadTime returns the expected value when it is constructed with the intended DateCalculator.CalculateLeadTime function.  But typically for those integration tests you need only a smaller range of test cases as for your unit tests. Since you have tests for the individual behaviour of both units, you already trust their core functionality and you need only make sure they both work together as intended.

In the current simplistic example, it is debatable if the situation does really need all three kinds of tests, but in general (assumed some more complex functions in your real world scenario), this typically pays off.

Body:
Ideally you should change your design a little bit and decouple OrderService from DateCalculator.CalculateLeadTime by using dependency injection:

class OrderService
{
   Func<DateTime,WidgetOrder> _calculateLeadTime;

   public OrderService(Func<DateTime,WidgetOrder> calculateLeadTime)
   {
       _calculateLeadTime=calculateLeadTime;
   }

   public DateTime GetLeadTime(WidgetOrder order)
   {
      return _calculateLeadTime(order.GetDeliveryDate() );
   }
}

Now its easy to unit test OrderService in isolation: instead of DateCalculator.CalculateLeadTime,  pass a mock function through the constructor for your test and check if it is correctly called from the GetLeadTime. This changes the situation so the meaningful tests for OrderService are not a superset of the tests for DateCalculator any more.

Of course, you may add an integration test to your test suite, which checks if OrderService.GetLeadTime returns the expected value when it is constructed with the intended DateCalculator.CalculateLeadTime function.  But typically for those integration tests you need only a smaller range of test cases as for your unit tests. Since you have tests for the individual behaviour of both units, you already trust their core functionality and you need only make sure they both work together as intended.

In the current simplistic example, it is debatable if the situation does really need all three kinds of tests, but in general (assumed some more complex functions in your real world scenario), this typically pays off.


问:
Algorithm to Copy data faster than windows default copy provider
I need an algorithm which can copy data(files/folder) from one place to another, faster than windows default copy/paste option. I'm working in vc++. Is there any algorithm by which I can do copy/paste faster.

Or Is there is any other suggestion to perform this task?

Thanks

答:
The Windows copy/paste function has several components.

A cute GUI interface

Pre-analysis of the work to be done, to help the GUI provide nice feedback and detect conflicts

Essentially single tasking

A very fast internal API for copying files.

In my opinion you are unlikely to be able to write code that can beat the Windows CopyFile() API function. You can however use multi-threading to saturate the IO channel and if you also omit the cute GUI stuff and the pre-analysis then that's probably as fast as you can go.

You can test this quite easily by running several XCOPY tasks at the same time and watching the resource monitor to see when you reach the maximum IO throughput.

One final thought: if you're copying a lot of small files there may be advantages in copying files that are located close together to minimise disk head movement. You would need to test to find out whether that is a factor.


答:
You're making a big mistake when you put assumptions into your unit tests about how the unit is implemented.

Consider what would happen were the implementation of OrderService to change so that it no longer used DateCalculator (or, more generally, if you wanted to test a different implementation with the same unit tests).  Your unit tests for OrderService would no longer be able to catch most of the potential errors.

While it is true that you can use white-box information to tailor unit tests to code, the unit tests should not be designed to make assumptions about how the code works.  So, yes: I would absolutely write tests that may end up running the same code, because code isn't written in stone and I don't want my tests to be concretely coupled to the code it's supposed to be checking.

Title: Unit testing - one test is partly a "superset" of another, is this wrong?

Body:
Wasn't sure how to phrase that title, sorry!

I've just come across this in our code base, and was wondering what the consensus was about how to unit test it:

C# (-ish, sorry, this is paraphrased from memory)

```<code>class DateCalculator
{
   public static DateTime CalculateLeadTime(DateTime deliveryDate)
   {
      //return the result of some determinate calculation involving deliveryDate
   }
}

//New example
class OrderController
{
    public ActionResult GetLeadTime(WidgetOrder order)
    {
        var leadTime = DateCalculator.CalculateLeadTime(order.GetDeliveryDate() );
        return Json(leadTime.Value.Date.ToString("dd/MM/yyyy") );
    }
}

//Old, incorrect example
class OrderService
{
   public DateTime GetLeadTime(WidgetOrder order)
   {
      return DateCalculator.CalculateLeadTime(order.GetDeliveryDate() );
   }
}
</code>```

We've then got two unit tests, one to verify that CalculateLeadTime works (this is very easy, you can put in several test values and predict what comes out), and one that GetLeadtime works (still easy, but...). My question is: what would you test here, and where?

It makes sense to me to test CalculateLeadTime in isolation, because it could be a complicated calculation, and it's already a nice small predictable unit.  But would you then go on to test some of the same stuff (maybe a single representative input and output?) in your GetLeadTime method?  Or would you simply test that any DateTime value is returned, and assume that the calculation is correct because you're testing that somewhere else?  Or would you not test the Calculate method on its own, because you know that you're going to test it when you use it, and you don't like the duplication?

EDIT: to muddy the waters a bit, I can see the code now, and rather than a Service, the calling class is an MVC Controller, and the Action under scrutiny is an AJAX method so returns the result of the calculation wrapped in JSON.  The current test verifies that JSON is returned, but not the contents of it.  Does this change anything?


问:
Why do people use markdown wysiwyg editors in web applications?
I understand the advantages of using markdown in local text files, and then taking those files and generating HTML. This is great for documentation, readme's in git repositories and posts for static site generators. It is very simple to create markdown syntax in any text editor, it's human readable, and you can create HTML from markdown relatively easily.

What I don't understand, is the advantages of using a wysiwyg editor for markdown in web applications, especially those that use a database server. (non-flat-file). I thought the whole point of using markdown was to remove the need for a wysiwyg editor. What is the advantage of using a markdown wysiwyg editor over an editor that just outputs HTML (avoiding the overhead of converting markdown to HTML in the process)?

clarification: basically I'm looking for technical advantages to having a WYSIWYG editor output markdown instead of HTML. To the end user the text form will look the same, so it's only dealing with markdown/html in the backend of an application. Anchor CMS sorta does this, and I'm wondering if there is an advantage over just plain HTML output.

答: Programmers like markup languages (Wikipedia markup, Markdown, HTML, SGML, etc.).  Non-technical users like WYSIWYG editors.  It has been this way since the first attempts at computerized typesetting (e.g., RUNOFF, 50 years old this year).


问:
How to avoid duplication of code related to shared entities in the repository pattern?
I'm building a repository for a large CRM schema that has a high number of relations between entities.

Some of the entities are referenced by almost all entities, e.g. Person and Company.

Where I have an aggregate root such as Order, that addresses Order Header, Order Lines etc. In the case where the Order is from a new Customer, I need to insert a Company and a Person record at the same time... so far so good.

The difficulty is that this is the situation with very many other aggregate roots.

I don't want to have a private method insertPerson(IPerson) in every single repository implementation.

I have a Customer repository that already has public InsertCustomer(ICustomer) method, which persists a Company and a person record. But my reading indicates that repositories shouldn't depend on each other.

If this is a case where it is okay for repositories to depend on each other, what is the best way to go about it? Should I inject the Customer Repository into the Order repository constuctor, pass it as a parameter to the methods that need it, or never commit this evil and duplicate the identical code in all repositories, in case those repositories need to specialise that code for their specific contexts?

答:
This sounds like an area that Service Layer might come in handy.  You could inject the repositories in the service layer and that way each repo won't depend on the others, and the service can coordinate all of the inserts for a given operation across aggregates.

Details of your implementation might also guide you depending on the extent to which you're relying on an ORM and need to take into account the atomicity of the repository operations. Without knowing more about that this advice may be less than useful.


问:
Do dependency injection frameworks pose a dependency risk?
I have been refactoring an existing system to use dependency injection, and that work has been going smoothly.

After a while I noticed that a large number of in-house libraries became dependent upon the DI framework I used. As a result the entire project now depends upon this third-party framework.

I saw an irony in decoupling all the dependencies by making them dependent upon a shared library.

My first reaction was to create a wrapper library around the dependency framework. Therefore, I could replace this framework if needed. After estimating the work involved I realized that the resulting API would be to similar to the existing framework, and therefore make replacing it more difficult. So I abandoned the idea.

My concern is that the DI framework I'm using becomes obsolete or needs replacing.

Does there exist a development pattern when working with DI that reduces the coupling between a project and the DI framework?

答:
Ordinary constructor injection doesn't require a framework at all.  The only thing you lose out on is the ability to centralize your dependencies in a configuration file.

DI containers are an "enterprise software" pattern, used when the object graph is very large and complex.  I suspect that 95% of applications do not require it.


问:
Are Data Warehouses bespoke products that are tailored towards the specific needs of one single organisation?
Are Data Warehouses bespoke projects that are developed to meet the needs of a specific organisation or can you buy off the shelf products that would meet the needs of many organisations?

I am talking about a product that will integrate information from many different systems e.g. finance system, sales system, production system etc for management reporting.

Different organisations have different systems that have different database designs.  For example,  organisation A may use finance system A, which has a completely different design to finance system B used by organisation B.

Therefore I believe that Data Warehouse products are bespoke products and it is not possible to develop a product that could be used by many organisations e.g. organisation A and organisation B; that have the same types of systems e.g. Finance, Sales etc.

Am I correct in this analysis?

答:
Your assumption that a data warehouse can be a "single, off the shelf product" doesn't seem to fit in the context of what a data warehouse can be or is.

From the info provided here:

http://en.wikipedia.org/wiki/Data_warehouse

The first thing you need to define is what "type" of data warehouse you want to build. The more generic the situation, the more likely you can use a product built by another company.

You also need to be aware of the fact that if such generic data-warehouse software exists, it will most likely incorporate the ability to pull in data from a variety of sources (as the article mentions: "Integrating data from one or more disparate sources creates a central repository of data, a data warehouse (DW)")

Lastly, it could also be that a data-warehouse piece of software is built similar to something like a Business Process Management(BPM) or Enterprise Resource Planning (ERP) software, where the end user is meant to build up the models using the software, thereby allowing the end-user to specify the customizations for integrating/pulling in the data from a variety of sources. This would mean that the end user would most likely need to know how to write programming scripts, or at the very minimum, know something like SQL.

If you feel my answer is lacking in any way, feel free to comment below and I will try to fix it.


答:
You are fully correct - using a DI framework will most probably make your code dependent from that thing. Actually, that is too surprising, since this is typically true for every other framework or foundation library, especially when that lib supports your project with some generic features used everwhere in your code. For example, when you decide to use a certain UI framework or Web framework, this decision is hard to change afterwards as soon as you have build a certain amount of code based on that library. When you decide to use a specific (maybe non-standard) String class, you cannot easily change that decision later. Such a decision is an architectural one, it is like choosing a certain programming language and try to change that decision after you have written >100K lines of code.

Having all of your code depend on a certain framework might not be a problem as long as it does what you expect from it, and as long as it is properly maintained. But it can become an issue if that's not the case. There are some strategies how to deal with that situation:

choose a framework from a vendor you have faith in that he can deliver you updates and new releases for several years from now

choose an open source framework which has few enough lines of code (and a proper license), so you can do any maintenance on your own, given the vendor vanishes from the market

write your own framework

live with the situation as long as the vendor is available, and when he really vanishes, choose a different framework and try to create an adapter which emulates the old framework using the new

The idea of creating a wrapper library beforehand is not new at all, but I have seldom seen that working, since you would have to make assumptions for a future situation for which you don't know if or when it will hit you, and what the "new" framework will look like. On the other hand, some years ago we successfully exchanged a complete UI framework in a C++ project with ~120K of lines of code by applying the adapter strategy I mentioned above.

Title: Do dependency injection frameworks pose a dependency risk?

Body:
I have been refactoring an existing system to use dependency injection, and that work has been going smoothly.

After a while I noticed that a large number of in-house libraries became dependent upon the DI framework I used. As a result the entire project now depends upon this third-party framework.

I saw an irony in decoupling all the dependencies by making them dependent upon a shared library.

My first reaction was to create a wrapper library around the dependency framework. Therefore, I could replace this framework if needed. After estimating the work involved I realized that the resulting API would be to similar to the existing framework, and therefore make replacing it more difficult. So I abandoned the idea.

My concern is that the DI framework I'm using becomes obsolete or needs replacing.

Does there exist a development pattern when working with DI that reduces the coupling between a project and the DI framework?


答:
I don't think DI frameworks can really become obsolete anytime soon. What should happen to make it obsolete?

An invention of a new and smarter pattern maybe? However it should look like, it would require much bigger changes in the code.

A change in the language maybe? Even worse.

I'd say that the current DI is mature enough and I'm not aware of much happening there. You haven't specify your language, so speaking of Guice, it's fairly non-obtrusive and works with standard Java annotations (also uses their own for things not standardized, but you rarely need it). It's open sourced, widely used, and Apache licensed. What could be the problem?

I'm pretty sure that changing the DI framework would be orders of magnitude easier than changing any other library (e.g., a UI change means much more work).


问:
Why do programmers still use mailing lists?
Why do many open source projects collaborate primarily through mailing lists rather than through, say, forums?  I may be ignorant in my assessment, but I, along with my communication teacher, think mailing lists are rather inefficient:

It's hard to reference old messages.  You have to wait until an archiving site picks up the message you want to link to, then look it up.

It's hard to reply to messages you haven't received from subscription, since you have to manually copy the sender and message contents.

It's impossible to moderate threads of discussion.  Posts cannot be deleted or modified without supernatural powers.

It's tricky to keep threads together (namely, to ensure all participants in the conversation are copied/replied to).

It's tricky for users to participate in multiple high-volume mailing lists, as they have to subscribe and set up filters (or just be really involved).

What real edge do mailing lists have that didn't occur to me?

答:
From https://github.com/pypa/packaging-problems/issues/21#issuecomment-46129044

My experience: GitHub (and Bitbucket) are great. Search engines find relevant discussions, or you can browse the repo to see everything. Everyone's comments are on one page, and it's obvious how to add your own (there's a giant green 'comment' button). It's dead easy to make an account--most community people already have one--but if not, it's a familiar process. Thus, GitHub is very welcoming, and levelling too.

Mailing lists, on the other hand, are dire, and I believe excluding to almost all of the community. From a search engine, you'll be taken to a single post from the middle of the discussion. You might see excerpts from earlier posts in reverse chronological order. It's disorientating. To read all the comments, you have to click around a tree structure (shown on a different page). That is ludicrously unfriendly. Most people surely give up. Perhaps the experience is better if you are a member of the mailing list, and receive the messages in your inbox. Understand though, that new people will always read mailing list posts on the web.

Worse, there are no instructions on the page how to comment. For example  https://mail.python.org/pipermail/distutils-sig/2013-August/022529.html , there's no big green comment button. If you click around, you can sign up to receive future posts in your inbox (not sure I want that) but that still doesn't explain how to reply to the post you're reading. I suspect older community are oblivious to this problem, because they grew up on mailing lists. Understand, most young people don't know how to use a mailing list--they've never seen one. By modern standards, the process to do so is laughably slow. (I'm reading a post on the web. I should be able to write a comment from the same page). It's prohibitive for many.

PEPs are thus problematic. For example http://legacy.python.org/dev/peps/pep-0453/ . There are no community comments on the page itself. There are links to five different mailing list pages where you can read what other people have said in the past, but there are no instructions how to have your own say. That's a shame. (Compare with Ruby feature requests which are discussed on an ordinary comment thread on the same page https://bugs.ruby-lang.org/issues/8992 )

bugs.python.org is also unwelcoming, in my experience. I reported a bug once, it was closed immediately, with a reply

You can't comment here, you're in the wrong place. This subject been discussed on the mailing list several times before [no link given]. If you want to comment, you should join the mailing list, go back in time, wait for the right post, and reply there.

The message was polite, but completely unhelpful. I felt unwelcome. I gave up trying to contribute to (what I assumed was) the community and started writing rants on Stack Overflow instead. They proved extremely popular, which encouraged me to try participating again. I'm happy I found your GitHub group--you have interesting things to say, and you've accepted my contributions. Thanks. I've even submitted pull requests--I love how levelling GitHub is.

To clarify, I don't believe the poster on bugs.python.org was trying to exclude me--they probably thought they were being helpful. But the perceived "we do things our way" attitude made me feel ignored and unwelcome. I'm sure other potential contributors have turned back at the same or earlier hurdles.  http://bugs.python.org/issue16675


答:
Why Markdown?

What is the advantage of using a markdown wysiwyg editor over an editor that just outputs HTML?

Because there are cases where you can't use a WYSIWYG editor, and should revert to text mode.

Example: diff of a question or an answer on Stack Exchange. Sometimes, you can simply compare the rendered layout. But there are cases where the rendered layout is not explicit enough, and watching Markdown helps in understanding what was changed.

Because Markdown is more compact. Storing HTML instead of Markdown would take more place in the database.

This is a lame argument, given the price per GB today. Besides, in most cases, HTML is stored side by side with Markdown in the database in order to generate the HTML once, and regenerate it only when Markdown is changed.

Because if the post was originally written in Markdown, you should keep it if you want to show it later to the author. If you convert everything to HTML and try to reconstitute Markdown from HTML later, there are chances the Markdown would not correspond to the original one.

A basic example: for titles in my answers on Stack Exchange, I put two dashes like this:

```<code>This is a title in Markdown
--
</code>```

Other persons would prefer:

```<code>This is a title in Markdown
---------------------------
</code>```

Others would rather write:

```<code>## This is a title in Markdown
</code>```

When I work in vim, I use the third format, because it feels more natural. But not on Stack Exchange.

Those three variants produce the same HTML. By recreating Markdown from HTML, you'll pick one of those three formats, and annoy people who are using two other variants.

Why a WYSIWYG editor for Markdown?

What I don't understand, is the advantages of using a wysiwyg editor for markdown in web applications

You work in IT. You understand Markdown and are willing to learn it. Right.

My grand-mother never worked in IT. She is willing to click on the bold "B" icon to make the text bold, or on the nice landscape in a frame to insert an image. But inserting dashes and stars? I don't think so. Probably, she doesn't even know there is "#" key on the keyboard.

I hate PHPBB. There are many reasons for that, but one minor reason is the fact that I need to type [b][/b] just to insert some bold text. That's just crazy. On a French keyboard, it requires some effort. Currently, I'm typing with a Belgian keyboard, and it took me 30 seconds just to find "[" and "]" keys.

Markdown is easier, but still, persons who are habituated to a different format and who don't care about Markdown either:

Won't use formatting at all, or:

Avoid using the website which uses Markdown.

Having a WYSIWYG editor helps those people to avoid thinking about the characters they need to type, and focus on the intention, i.e. how do they need to format the piece of text.

Title: Why do people use markdown wysiwyg editors in web applications?

Body:
I understand the advantages of using markdown in local text files, and then taking those files and generating HTML. This is great for documentation, readme's in git repositories and posts for static site generators. It is very simple to create markdown syntax in any text editor, it's human readable, and you can create HTML from markdown relatively easily.

What I don't understand, is the advantages of using a wysiwyg editor for markdown in web applications, especially those that use a database server. (non-flat-file). I thought the whole point of using markdown was to remove the need for a wysiwyg editor. What is the advantage of using a markdown wysiwyg editor over an editor that just outputs HTML (avoiding the overhead of converting markdown to HTML in the process)?

clarification: basically I'm looking for technical advantages to having a WYSIWYG editor output markdown instead of HTML. To the end user the text form will look the same, so it's only dealing with markdown/html in the backend of an application. Anchor CMS sorta does this, and I'm wondering if there is an advantage over just plain HTML output.

Body:
Why Markdown?

What is the advantage of using a markdown wysiwyg editor over an editor that just outputs HTML?

Because there are cases where you can't use a WYSIWYG editor, and should revert to text mode.

Example: diff of a question or an answer on Stack Exchange. Sometimes, you can simply compare the rendered layout. But there are cases where the rendered layout is not explicit enough, and watching Markdown helps in understanding what was changed.

Because Markdown is more compact. Storing HTML instead of Markdown would take more place in the database.

This is a lame argument, given the price per GB today. Besides, in most cases, HTML is stored side by side with Markdown in the database in order to generate the HTML once, and regenerate it only when Markdown is changed.

Because if the post was originally written in Markdown, you should keep it if you want to show it later to the author. If you convert everything to HTML and try to reconstitute Markdown from HTML later, there are chances the Markdown would not correspond to the original one.

A basic example: for titles in my answers on Stack Exchange, I put two dashes like this:

This is a title in Markdown
--

Other persons would prefer:

This is a title in Markdown
---------------------------

Others would rather write:

## This is a title in Markdown

When I work in vim, I use the third format, because it feels more natural. But not on Stack Exchange.

Those three variants produce the same HTML. By recreating Markdown from HTML, you'll pick one of those three formats, and annoy people who are using two other variants.

Why a WYSIWYG editor for Markdown?

What I don't understand, is the advantages of using a wysiwyg editor for markdown in web applications

You work in IT. You understand Markdown and are willing to learn it. Right.

My grand-mother never worked in IT. She is willing to click on the bold "B" icon to make the text bold, or on the nice landscape in a frame to insert an image. But inserting dashes and stars? I don't think so. Probably, she doesn't even know there is "#" key on the keyboard.

I hate PHPBB. There are many reasons for that, but one minor reason is the fact that I need to type [b][/b] just to insert some bold text. That's just crazy. On a French keyboard, it requires some effort. Currently, I'm typing with a Belgian keyboard, and it took me 30 seconds just to find "[" and "]" keys.

Markdown is easier, but still, persons who are habituated to a different format and who don't care about Markdown either:

Won't use formatting at all, or:

Avoid using the website which uses Markdown.

Having a WYSIWYG editor helps those people to avoid thinking about the characters they need to type, and focus on the intention, i.e. how do they need to format the piece of text.


答:
Note that volunteer projects tend to be more developer/contibutor-oriented then user-oriented to some extend. This make sense as the former tend to have a limited time while the latter get something 'for free'.

The projects I worked with (mainly GNOME-related) tend to have a real manpower shortage so anything which saves time or makes it easier for developers to participate is a plus. So from perspective of developer (in random order):

Mails allow highly customized filtering which people do use extensively. For example all the mails from ML for project I maintain goes to my inbox directly and are labelled as such. For less important ML they go to separate folder and skip the inform. For others I just use NNTP + Gmane.

Mails allow highly customizable MUA starting from web interfaces to very complicated programs allowing filtering, highlighting of important emails, creating tasks etc. They allow to script parts of reply and automate certain parts.

Accessing ML has 0 friction for (for example) me. I don't need to create any additional account - in most cases I just subscribe via NNTP in Gmane and, on many ML, just send an email. On the other hand I need to create an account on forum, create a password which is a) secure, b) unique [because who knows if the forum does not 'encrypt' password by rot13] and c) fulfil all the requirements [at least 8 characters including smaller and upper case letters and some special characters, but not too special like dot, unless today is Tuesday when we allow the dot...] and then start doubting I'm human while I'm trying to solve CAPATCHA ;)

Mails allow to add participants to thread when they are needed. For example for patch review you can add someone to To field and ask him if it won't interfere with his work etc. Most forums do not allow such things - at least not with few clicks as most MUA. Mails also allows to drop people from discussion (by curtsy first by dropping them to BCC) to avoid spamming.

I'd argue in some cases the threaded discussion can be have advantages. Yes - it's complicated etc. but patch review can split into several parts regarding different issues.

Most MUAs have integrated notification systems which allow to judge as important/spam/deal with it later. On the other hand the forums, if they have notification/subscription system, forces you to go to the website.

SMTP/NNTP are standards - they have RFCs and all. There are already tools which run against them - for example git can send patch to ML but it cannot send to forum. The closest I heard about it is ad-hoc support for bugzilla.

... and I don't think list is exhaustive. I can see why/how the workflow might not be welcoming to new users, not mentioning the less technical. Gnome has different channels for them to engage (G+, Fb, and yes - forums) but AFAIK rarely any developer time to take participation in community there, relearn the tools etc.

Title: Why do programmers still use mailing lists?

Body:
Why do many open source projects collaborate primarily through mailing lists rather than through, say, forums?  I may be ignorant in my assessment, but I, along with my communication teacher, think mailing lists are rather inefficient:

It's hard to reference old messages.  You have to wait until an archiving site picks up the message you want to link to, then look it up.

It's hard to reply to messages you haven't received from subscription, since you have to manually copy the sender and message contents.

It's impossible to moderate threads of discussion.  Posts cannot be deleted or modified without supernatural powers.

It's tricky to keep threads together (namely, to ensure all participants in the conversation are copied/replied to).

It's tricky for users to participate in multiple high-volume mailing lists, as they have to subscribe and set up filters (or just be really involved).

What real edge do mailing lists have that didn't occur to me?


问:
Flaws in my PHP development setup - sharing sources causing lags
I have following development setup for my PHP projects:

Working station running on Windows 7 with PhpStorm IDE.

GIT for version controlling.

CentOS on virtual machine (VirtualBox) with Apache and MySQL (copy of production server).

So far, I've been sharing project's source folders between host and guest systems and it was working quite well only really slow. The reason behind this is that Apache was reading files from remote folder (mounted locally). After doing some research, I found out that this set up can be improved by using disk mapping (Samba) instead of folder sharing. So I did that change. I configured my PhpStorm to automatically deploy files to mapped drive. Everything works like a charm now, except for one problem - when I change branches I need to synchronize project's local folder with the one on mapped drive and that takes time, a lot of time (like branching in SVN). Is there another way to handle this than just working on files directly on mapped drive?

答:
The most efficient setup for your configuration would be to git clone the repo via SSH directly into the virtual machine (in a location that's accessible to the SAMBA user), mount the "remote" folder from the VM as a network drive in Windows and use PHPStorm to open the project directly from that drive.

The point is this: edit the project directly from the mapped location, do not use PHPStorm's deployment options to deploy your changes to the mapped drive. It will still be slow, but it should be a bit faster than your current setup.


答:
It is true Data Warehouses typically pull data from many different sources/parts of the business. A Datamart typically pulls data from a lone source.

There are applications that cater to specific industries that offer the ability to integrate and pull data from different resources into a common data structure. I still wouldn't call this a data warehouse because much of the data is structured for transactions and other relational forms and not completely optimized for denormalized report pereformance or historical data capturing.

These types of systems are easier for the manufacturer to create a data warehouse. The core structure (Star Schema?) may be there along with some customizable data cubes. Many firms have inhouse expertise with something like Excel which has PowerPivot to do some customizable BI.

I've worked in the legal and financial industries and some of their popular enterprise apps offer this. Lengthy engagements, installations, customizations and testing are common, so I wouldn't exactly say this works "right out of the box". Then again, which enterprise apps do?

Title: Are Data Warehouses bespoke products that are tailored towards the specific needs of one single organisation?

Body:
Are Data Warehouses bespoke projects that are developed to meet the needs of a specific organisation or can you buy off the shelf products that would meet the needs of many organisations?

I am talking about a product that will integrate information from many different systems e.g. finance system, sales system, production system etc for management reporting.

Different organisations have different systems that have different database designs.  For example,  organisation A may use finance system A, which has a completely different design to finance system B used by organisation B.

Therefore I believe that Data Warehouse products are bespoke products and it is not possible to develop a product that could be used by many organisations e.g. organisation A and organisation B; that have the same types of systems e.g. Finance, Sales etc.

Am I correct in this analysis?


问:
Is my work on a developer test being taken advantage of?
I am looking for a job and have applied to a number of positions. One employer responded. I had a pretty lengthy phone interview (perhaps an hour +) and they then set me up with a developer test. I was told that the test was estimated to take between 6 and 8 hours and that, provided the results met with their approval, I would be paid for my work.

That gave me some pause, but I endeavored. The developer test took place on a VM accessed via RDP. The task was to implement a search page in a web project that requests data from the server, displays it on the screen in a table, has a pretty complicated search filtering scheme (there are about 15 statuses and when sending the search to the server you can search by these statuses) in addition to the string/field search. Additionally, they want SVG icons to change color on certain data values, and some data represented differently than how it's structured in the database.

Loooong story short, this took a heck of a lot longer than 6-8 hours. Much of it was due to the very poor VM that I was running on (Visual Studio 2013 took 10 minutes to load, and another 15 minutes to open the 3 GB ginormous solution).

I was told that after completing the test I should commit my changes to source control...  Hmm, OK. I followed directions. And after committing the changes, I was emailed a response. The SVGs weren't colored right, there was a bug in this edge-case, there was an occasional problem with this other thing that I never experienced, etc. So I am 13-14 hours into this thing now, and I have to do bug fixes. I do them, and the employer comes back with more bug fix requests.

All my work is apparently going into a production application. I noticed a few anomalies in the code where it looked like others had coded all of one functionality but hadn't touched anything else.

Am I just being used for cheap labor? Even if they pay me the promised 50 dollars an hour for 6 hours, I have committed about 18 hours to this thing now. If I bug fix all of the stuff they keep coming up with, I will have worked at least 16 hours for free.

I have taken a number of developer tests, but I have never taken one during which I worked on code destined for production. I have never taken a test where I implemented a feature that was in the pipeline for development, and I have never taken one that took 4 rounds and a total of 20+ hours. I get the impression they are using their developer test to field some of the functionality on the cheap.

Do I have the wrong impression? And is this testing protocol appropriate?

答:
While you are supposedly getting paid for (some of) your work, this does not sound like a trial project, it sounds like a scam to get cheap/free work out of you. It may be that it is was intended to be a trial project, just not structured or managed very well.

But managment that is so bad that it is sounds like a scam, is definitely something you should take into consideration when deciding whether to take the job or not.

A proper trial project should make it clear that

They have work that they desire to have done.

Based upon your interview they believe you should be able to do the work.

Sucessfull completion of the project does not guarantee a position.

Terms for the project (how much they will pay, who owns the code, whether it is time and materials or flat rate, estimated time to completion, etc).

The project will be reviewed and feedback provided -- not just a yes/no as to whether or not you get the position.

The terms should be acceptable to you regardless of whether you get hired -- if the terms are only acceptable if they come with a full time job, they aren't really acceptable.


问:
Reference wind directions to texture space?
I have a 2D array filled with a simple class:

```<code>class Tile
{
    boolean N,E,S,W;
}
</code>```

I also have a tilesheet representing all possible outcomes except all false (12 + crossroad). Now i need to reference all these possibilities to texture space on my sheet. Apart from having an if statement for each and every outcome is there a more efficient way i cannot currently think off?

答:
I'm not sure I understand what you are doing here, but your class looks to be equivalent to a 4-bit integer and so it might be helpful to return its state as such -- or even better, as a bit flag enum.  It might also be useful to introduce an indexer property to your class (I'm using c# here) to iterate easily through the values in the 4 cardinal directions:

```<code>public enum CardinalDirection
{
    /// <summary>
    /// The +Y Direction
    /// </summary>
    N = (1 << 0),
    /// <summary>
    /// The +X Direction
    /// </summary>
    E = (1 << 1),
    /// <summary>
    /// The -Y Direction
    /// </summary>
    S = (1 << 2),
    /// <summary>
    /// The -X Direction
    /// </summary>
    W = (1 << 3),
}

[Flags]
public enum Direction
{
    None = 0,
    /// <summary>
    /// The +Y Direction
    /// </summary>
    N = (1 << 0),
    /// <summary>
    /// The +X Direction
    /// </summary>
    E = (1 << 1),
    /// <summary>
    /// The -Y Direction
    /// </summary>
    S = (1 << 2),
    /// <summary>
    /// The -X Direction
    /// </summary>
    W = (1 << 3),

    NE = N + E,
    NS = N + S,
    NW = N + W,
    ES = E + S,
    EW = E + W,
    SW = S + W,

    NES = N + E + S,
    NEW = N + E + W,
    NSW = N + S + W,
    ESW = E + S + W,

    NESW = N + E + S + W
}

public class Tile
{
    bool N, E, S, W;

    public static Direction ToDirection(bool N, bool E, bool S, bool W)
    {
        Direction dir = Direction.None;
        if (N)
            dir |= Direction.N;
        if (E)
            dir |= Direction.E;
        if (S)
            dir |= Direction.S;
        if (W)
            dir |= Direction.W;
        return dir;
    }

    public static void FromDirection(Direction dir, out bool N, out bool E, out bool S, out bool W)
    {
        N = (dir & Direction.N) == Direction.N;
        E = (dir & Direction.E) == Direction.E;
        S = (dir & Direction.S) == Direction.S;
        W = (dir & Direction.W) == Direction.W;
    }

    public Direction Direction
    {
        get
        {
            return Tile.ToDirection(N, E, S, W);
        }

        set
        {
            Tile.FromDirection(value, out N, out E, out S, out W);
        }
    }

    /// <summary>
    /// Returns the the value in the specified direction
    /// </summary>
    /// <param name="dir"></param>
    /// <returns></returns>
    public bool this[CardinalDirection cardinalDirection]
    {
        get
        {
            switch (cardinalDirection)
            {
                case CardinalDirection.N:
                    return N;
                case CardinalDirection.E:
                    return E;
                case CardinalDirection.S:
                    return S;
                case CardinalDirection.W:
                    return W;
                default:
                    throw new ArgumentOutOfRangeException("dir", cardinalDirection.ToString());
            }
        }
        set
        {
            switch (cardinalDirection)
            {
                case CardinalDirection.N:
                    N = value;
                    return;
                case CardinalDirection.E:
                    E = value;
                    return;
                case CardinalDirection.S:
                    S = value;
                    return;
                case CardinalDirection.W:
                    W = value;
                    return;
                default:
                    throw new ArgumentOutOfRangeException("dir", cardinalDirection.ToString());
            }
        }
    }
}
</code>```

This should allow you to conveniently switch on selected combinations of directions.

As an example of using the indexer property to iterate through the cardinal direction flags, the following method, given a 2d array of tiles, counts the number of tiles adjacent to a specified tile with matching flag values:

```<code>public static class TileHelper
{
    public static int CountConsistent(Tile[][] tiles, int iX, int iY)
    {
        int count = 0;
        var tile = tiles[iX][iY];
        foreach (var pair in tiles.WalkAround(iX, iY))
        {
            var dir = pair.Key;
            if (tile[dir] == pair.Value[dir.Rotate180()])
                count++;
        }
        return count;
    }

    /// <summary>
    /// Enumerate through the 4 tiles N, E, S, and W of the given tile in the tile array.
    /// Tiles off the edges of the array will be skipped.
    /// </summary>
    /// <param name="tiles"></param>
    /// <param name="iX"></param>
    /// <param name="iY"></param>
    /// <returns></returns>
    public static IEnumerable<KeyValuePair<CardinalDirection, Tile>> WalkAround(this Tile[][] tiles, int iX, int iY)
    {
        if (iX < 0 || iY < 0 || iX >= tiles.Length || iY >= tiles[iX].Length)
            yield break;
        if (iY + 1 < tiles[iX].Length)
            yield return new KeyValuePair<CardinalDirection, Tile>(CardinalDirection.N, tiles[iX][iY + 1]);
        if (iX + 1 < tiles.Length)
            yield return new KeyValuePair<CardinalDirection, Tile>(CardinalDirection.E, tiles[iX + 1][iY]);
        if (iY > 1)
            yield return new KeyValuePair<CardinalDirection, Tile>(CardinalDirection.S, tiles[iX][iY - 1]);
        if (iX > 1)
            yield return new KeyValuePair<CardinalDirection, Tile>(CardinalDirection.W, tiles[iX - 1][iY]);
    }

    public static CardinalDirection Rotate180(this CardinalDirection cardinalDirection)
    {
        switch (cardinalDirection) {
            case CardinalDirection.N:
                return CardinalDirection.S;
            case CardinalDirection.E:
                return CardinalDirection.W;
            case CardinalDirection.S:
                return CardinalDirection.N;
            case CardinalDirection.W:
                return CardinalDirection.E;
            default:
                throw new ArgumentOutOfRangeException("dir", cardinalDirection.ToString());
        }
    }
}
</code>```

(Probably the first method could be done more beautifully with Linq).

Hope that helps.

Body:
I'm not sure I understand what you are doing here, but your class looks to be equivalent to a 4-bit integer and so it might be helpful to return its state as such -- or even better, as a bit flag enum.  It might also be useful to introduce an indexer property to your class (I'm using c# here) to iterate easily through the values in the 4 cardinal directions:

public enum CardinalDirection
{
    /// <summary>
    /// The +Y Direction
    /// </summary>
    N = (1 << 0),
    /// <summary>
    /// The +X Direction
    /// </summary>
    E = (1 << 1),
    /// <summary>
    /// The -Y Direction
    /// </summary>
    S = (1 << 2),
    /// <summary>
    /// The -X Direction
    /// </summary>
    W = (1 << 3),
}

[Flags]
public enum Direction
{
    None = 0,
    /// <summary>
    /// The +Y Direction
    /// </summary>
    N = (1 << 0),
    /// <summary>
    /// The +X Direction
    /// </summary>
    E = (1 << 1),
    /// <summary>
    /// The -Y Direction
    /// </summary>
    S = (1 << 2),
    /// <summary>
    /// The -X Direction
    /// </summary>
    W = (1 << 3),

    NE = N + E,
    NS = N + S,
    NW = N + W,
    ES = E + S,
    EW = E + W,
    SW = S + W,

    NES = N + E + S,
    NEW = N + E + W,
    NSW = N + S + W,
    ESW = E + S + W,

    NESW = N + E + S + W
}

public class Tile
{
    bool N, E, S, W;

    public static Direction ToDirection(bool N, bool E, bool S, bool W)
    {
        Direction dir = Direction.None;
        if (N)
            dir |= Direction.N;
        if (E)
            dir |= Direction.E;
        if (S)
            dir |= Direction.S;
        if (W)
            dir |= Direction.W;
        return dir;
    }

    public static void FromDirection(Direction dir, out bool N, out bool E, out bool S, out bool W)
    {
        N = (dir & Direction.N) == Direction.N;
        E = (dir & Direction.E) == Direction.E;
        S = (dir & Direction.S) == Direction.S;
        W = (dir & Direction.W) == Direction.W;
    }

    public Direction Direction
    {
        get
        {
            return Tile.ToDirection(N, E, S, W);
        }

        set
        {
            Tile.FromDirection(value, out N, out E, out S, out W);
        }
    }

    /// <summary>
    /// Returns the the value in the specified direction
    /// </summary>
    /// <param name="dir"></param>
    /// <returns></returns>
    public bool this[CardinalDirection cardinalDirection]
    {
        get
        {
            switch (cardinalDirection)
            {
                case CardinalDirection.N:
                    return N;
                case CardinalDirection.E:
                    return E;
                case CardinalDirection.S:
                    return S;
                case CardinalDirection.W:
                    return W;
                default:
                    throw new ArgumentOutOfRangeException("dir", cardinalDirection.ToString());
            }
        }
        set
        {
            switch (cardinalDirection)
            {
                case CardinalDirection.N:
                    N = value;
                    return;
                case CardinalDirection.E:
                    E = value;
                    return;
                case CardinalDirection.S:
                    S = value;
                    return;
                case CardinalDirection.W:
                    W = value;
                    return;
                default:
                    throw new ArgumentOutOfRangeException("dir", cardinalDirection.ToString());
            }
        }
    }
}

This should allow you to conveniently switch on selected combinations of directions.

As an example of using the indexer property to iterate through the cardinal direction flags, the following method, given a 2d array of tiles, counts the number of tiles adjacent to a specified tile with matching flag values:

public static class TileHelper
{
    public static int CountConsistent(Tile[][] tiles, int iX, int iY)
    {
        int count = 0;
        var tile = tiles[iX][iY];
        foreach (var pair in tiles.WalkAround(iX, iY))
        {
            var dir = pair.Key;
            if (tile[dir] == pair.Value[dir.Rotate180()])
                count++;
        }
        return count;
    }

    /// <summary>
    /// Enumerate through the 4 tiles N, E, S, and W of the given tile in the tile array.
    /// Tiles off the edges of the array will be skipped.
    /// </summary>
    /// <param name="tiles"></param>
    /// <param name="iX"></param>
    /// <param name="iY"></param>
    /// <returns></returns>
    public static IEnumerable<KeyValuePair<CardinalDirection, Tile>> WalkAround(this Tile[][] tiles, int iX, int iY)
    {
        if (iX < 0 || iY < 0 || iX >= tiles.Length || iY >= tiles[iX].Length)
            yield break;
        if (iY + 1 < tiles[iX].Length)
            yield return new KeyValuePair<CardinalDirection, Tile>(CardinalDirection.N, tiles[iX][iY + 1]);
        if (iX + 1 < tiles.Length)
            yield return new KeyValuePair<CardinalDirection, Tile>(CardinalDirection.E, tiles[iX + 1][iY]);
        if (iY > 1)
            yield return new KeyValuePair<CardinalDirection, Tile>(CardinalDirection.S, tiles[iX][iY - 1]);
        if (iX > 1)
            yield return new KeyValuePair<CardinalDirection, Tile>(CardinalDirection.W, tiles[iX - 1][iY]);
    }

    public static CardinalDirection Rotate180(this CardinalDirection cardinalDirection)
    {
        switch (cardinalDirection) {
            case CardinalDirection.N:
                return CardinalDirection.S;
            case CardinalDirection.E:
                return CardinalDirection.W;
            case CardinalDirection.S:
                return CardinalDirection.N;
            case CardinalDirection.W:
                return CardinalDirection.E;
            default:
                throw new ArgumentOutOfRangeException("dir", cardinalDirection.ToString());
        }
    }
}

(Probably the first method could be done more beautifully with Linq).

Hope that helps.


问:
Showing a View from another View in MVP
This question is regarding MVP triads. Lets say I have two triads and first one has View1, Mode1 and Presenter1. Second triad has View2, Model2 and Presenter2. Now what I trying to do is, I just want to display the View2 when I click a button in View1.

You'd show the View1 calling it's presenter's show method.

```<code>View1Presenter presenter1 = new View1Presenter (view1, Model1);
presenter1.show();
</code>```

Now When I click btnShowView2 button on the View1, it should display the View2.

So how to call presenter2.show() from View1?

答:
Displaying a second view on btnShowView2.Clicked is some kind of business logic, so the right place for implementing this is in the event handler of presenter1 which deals with that event (I assume that presenter1 is registered to all relevant button-click events of View1). Lets call it HandleBtnView2Click, so the initial code inside that handler might look like this:

```<code>  void HandleBtnView2Clicked(object sender, EventArgs e))
  {
       IView2 view2 = new View2();
       Model2 model2 = model1.GetRefToModel2(); // or whatever is needed to get model2
       View2Presenter presenter2 =new View2Presenter(view2,model2);
       presenter2.show();
  }
</code>```

But actually, this is not a good solution, since it would imply the presenter2 layer must be linked against the UI library (in your case WinForms), which in worst case prevents automatic testing.

The better solution is to delegate the creation of View2 to a third instance, which can be easily mocked out. In general, its possible to use an abstract factory for this. In the specific case, it is also possible to use View1 for the creation of View2. Add a method to your IView1 interface:

```<code> interface IView1
 {
    // ...
      IView2 CreateView2();
 }
</code>```

and use it in the code above:

```<code>  void HandleBtnView2Clicked(object sender, EventArgs e))
  {
       IView2 view2 = view1.CreateView2(); // view1 is of type IView1 and a member of presenter1
       Model2 model2 = model1.GetRefToModel2(); // or whatever is needed to get model2
       View2Presenter presenter2 =new View2Presenter(view2,model2);
       presenter2.show();
  }
</code>```

Now when you want to automatically test your presenter1, provide it with a mock implementation of view1 which implements the CreateView2 method in a manner returning a mock of view2. In the View1 class, you implement CreateView2() to return the new View2(), so the responsibility for creating views stays at the the view layer.

You can go a step further if you want and make presenter1 testable in isolation from presenter2. If you think that is necessary, create an interface IPresenter2 and put the whole creation code above into an abstract "presenter factory":

```<code>   void HandleBtnView2Clicked(object sender, EventArgs e))
   {
        IPresenter presenter2 = presenterFactory.CreatePresenter2(model1);
        presenter2.show();
   }
</code>```

The presenterFactory has to be injected into your presenter1 at construction time and can be replaced by a mock in your test suite. If that's necessary, you have to decide for yourself. It will add an additional layer of complexity to your code for the benefit of better testability.

Title: Showing a View from another View in MVP

Body:
Displaying a second view on btnShowView2.Clicked is some kind of business logic, so the right place for implementing this is in the event handler of presenter1 which deals with that event (I assume that presenter1 is registered to all relevant button-click events of View1). Lets call it HandleBtnView2Click, so the initial code inside that handler might look like this:

  void HandleBtnView2Clicked(object sender, EventArgs e))
  {
       IView2 view2 = new View2();
       Model2 model2 = model1.GetRefToModel2(); // or whatever is needed to get model2
       View2Presenter presenter2 =new View2Presenter(view2,model2);
       presenter2.show();
  }

But actually, this is not a good solution, since it would imply the presenter2 layer must be linked against the UI library (in your case WinForms), which in worst case prevents automatic testing.

The better solution is to delegate the creation of View2 to a third instance, which can be easily mocked out. In general, its possible to use an abstract factory for this. In the specific case, it is also possible to use View1 for the creation of View2. Add a method to your IView1 interface:

 interface IView1
 {
    // ...
      IView2 CreateView2();
 }

and use it in the code above:

  void HandleBtnView2Clicked(object sender, EventArgs e))
  {
       IView2 view2 = view1.CreateView2(); // view1 is of type IView1 and a member of presenter1
       Model2 model2 = model1.GetRefToModel2(); // or whatever is needed to get model2
       View2Presenter presenter2 =new View2Presenter(view2,model2);
       presenter2.show();
  }

Now when you want to automatically test your presenter1, provide it with a mock implementation of view1 which implements the CreateView2 method in a manner returning a mock of view2. In the View1 class, you implement CreateView2() to return the new View2(), so the responsibility for creating views stays at the the view layer.

You can go a step further if you want and make presenter1 testable in isolation from presenter2. If you think that is necessary, create an interface IPresenter2 and put the whole creation code above into an abstract "presenter factory":

   void HandleBtnView2Clicked(object sender, EventArgs e))
   {
        IPresenter presenter2 = presenterFactory.CreatePresenter2(model1);
        presenter2.show();
   }

The presenterFactory has to be injected into your presenter1 at construction time and can be replaced by a mock in your test suite. If that's necessary, you have to decide for yourself. It will add an additional layer of complexity to your code for the benefit of better testability.


问:
Do you have your own 'misc utils' library? What part are you most proud of?
I know that many of us maintain our own little personal library with tools and utilities that we use often.

I've had mine since I was 16 years old so it has grown to quite a considerable size. Some of the stuff I've written has since been added to the framework. I wrote my own little implementation of expression trees for use with genetic algorithms long before LINQ, which I quite like and was proud of at the time - of course its pretty useless now. But recently I have been going through it and upgrading to .NET 4.0 and re-kindled an interest.

So I'm curious as to what you use your library for. Maybe we could get some cool ideas going for useful little snippets and share them amongst ourselves.

So my questions are:

Do you have a miscellaneous utility library?

Which part are you most proud of and why?

Give an example of code if you like :-)

答:
Currently, no. I had one when I was doing C, but now that I do Java, it no longer makes sense, considering all the standard libs available, plus all the goodies coming from the Apache project.

One of the useful things in my C lib was a quick&dirty finite state machine implementation, which allowed the definition of a finite state machine with just two strings and an array of strings. It could be used to check strings against rules (e.g. "must be 4..6 characters long, first one a letter, rest digits") , but the availability of regexes made that thingy completely pointless.