问:
So Singletons are bad, then what?
There has been a lot of discussion lately about the problems with using (and overusing) Singletons. I've been one of those people earlier in my career too. I can see what the problem is now, and yet, there are still many cases where I can't see a nice alternative - and not many of the anti-Singleton discussions really provide one.

Here is a real example from a major recent project I was involved in:

The application was a thick client with many separate screens and components which uses huge amounts of data from a server state which isn't updated too often. This data was basically cached in a Singleton "manager" object - the dreaded "global state". The idea was to have this one place in the app which keeps the data stored and synced, and then any new screens that are opened can just query most of what they need from there, without making repetitive requests for various supporting data from the server. Constantly requesting to the server would take too much bandwidth - and I'm talking thousands of dollars extra Internet bills per week, so that was unacceptable.

Is there any other approach that could be appropriate here than basically having this kind of global data manager cache object? This object doesn't officially have to be a "Singleton" of course, but it does conceptually make sense to be one. What is a nice clean alternative here?

答:
Then what? Since nobody said it: Toolbox. That is if you really really need global variables.

Singleton abuse can be avoided by looking at the problem from a different angle. Suppose an application needs only one instance of a class and the application configures that class at startup: Why should the class itself be responsible for being a singleton? It seems quite logical for the application to take on this responsibility, since the application requires this kind of behavior. The application, not the component, should be the singleton. The application then makes an instance of the component available for any application-specific code to use. When an application uses several such components, it can aggregate them into what we have called a toolbox.

Put simply, the application's toolbox is a singleton that is responsible either for configuring itself or for allowing the application's startup mechanism to configure it...

```<code>public class Toolbox {
     private static Toolbox _instance;

     public static Toolbox Instance {
         get {
             if (_instance == null) {
                 _instance = new Toolbox();
             }
             return _instance;
         }
     }

     protected Toolbox() {
         Initialize();
     }

     protected void Initialize() {
         // Your code here
     }

     private MyComponent _myComponent;

     public MyComponent MyComponent() {
         get {
             return _myComponent();
         }
     }
     ...

     // Optional: standard extension allowing
     // runtime registration of global objects.
     private Map components;

     public Object GetComponent (String componentName) {
         return components.Get(componentName);
     }

     public void RegisterComponent(String componentName, Object component)
     {
         components.Put(componentName, component);
     }

     public void DeregisterComponent(String componentName) {
         components.Remove(componentName);
     }

}
</code>```

But guess what? It is a singleton!

And what is a singleton?

Maybe that's where the confusion begins.

To me, the singleton is an object enforced to have a single instance only and always. You can access it anywhere, any time, without needing to instantiate it. That's why it's so closely related to static. For comparison, static is basically the same thing, except it's not an instance. We don't need to instantiate it, we can't even, because it's automagically allocated. And that can and does bring problems.

From my experience, simply replacing static for Singleton solved many issues in a medium size patchwork bag project I'm on. That only means it does have some usage for bad designed projects. I think there's too much discussion if the singleton pattern is useful or not and I can't really argue if it's indeed bad. But still there are good arguments in favor for singleton over static methods, in general.

The only thing I'm sure is bad about singletons, is when we use them while ignoring good practices. That's indeed something not that easy to deal with. But bad practices can be applied to any pattern. And, I know, it is too generic to say that... I mean there's just too much to it.

Don't get me wrong!

Simply put, just like global vars, singletons should still be avoided at all times. Specially because they are overly abused. But global vars can not be avoided always and we should use them in that last case.

Anyway, there are many other suggestions other than the Toolbox, and just like the toolbox, each one has its application...

Other alternatives

The best article I've just read about singletons suggests Service Locator as an alternative. To me that is basically a "Static Toolbox", if you will. In other words, make the Service Locator a Singleton and you have a Toolbox. That does go against its initial suggestion of avoiding the singleton, of course, but that's only to enforce singleton's issue is how it's used, not the pattern in itself.

Others suggest Factory Pattern as an alternative. It was the first alternative I heard from a colleague and we quickly eliminated it for our usage as global var. It sure has its usage, but so does singletons.

Both alternatives above are good alternatives. But it all depends on your usage.

Now, implying singletons should be avoided at all costs is just wrong...

Aaronaught's answer is suggesting to never use singletons, for a series of reasons. But they're all reasons against how it's ill used and abused, not directly against the pattern itself. I do agree with all the worrying about those points, how can't I? I just think it's misleading.

The inabilities (to abstract or subclass) are indeed there, but so what? It's not meant for that. There is no inability to interface, as far as I can tell. High coupling can also be there, but that's just because how it's commonly used. It doesn't have to. In fact, the coupling in itself has nothing to do with the singleton pattern. That being clarified, it also already eliminates the difficulty to test. As for the difficulty to parallelize, that depends on the language and platform so, again, not a problem on the pattern.

Practical examples

I often see 2 being used, both in favor and against singletons. Web cache (my case) and log service.

The logging, some will argue, is a perfect singleton example, because, and I quote:

The requesters need a well-known object to which to send requests to log. This means a global point of access.

Since the logging service is a single event source to which multiple listeners can register, there only needs to be one instance.

Although different applications may log to different output devices, the way they register their listeners is always the same. All customization is done through the listeners. Clients can request logging without knowing how or where the text will be logged. Every application would therefore use the logging service exactly the same way.

Any application should be able to get away with only one instance of the logging service.

Any object can be a logging requester, including reusable components, so that they should not be coupled to any particular application.

While others will argue it makes difficult to expand the log service once you eventually realize it actually shouldn't be only one instance.

Well, I say both arguments are valid. The problem here, again, isn't on the singleton pattern. It's on architectural decisions and weighting if refactoring is a viable risk. It's a further problem when, usually, refactoring is the last needed corrective measure.

too long: didn't read:

disclaimer: this section contains the only comment added today, 8 years after everything else written here.

global variables (and thus, anything like a singleton such as the toolbox) must be always avoided and will never be fully eliminated.

unless you're absolutely and completely sure you need a global variable, avoid it!

Title: So Singletons are bad, then what?

Body:
Then what? Since nobody said it: Toolbox. That is if you really really need global variables.

Singleton abuse can be avoided by looking at the problem from a different angle. Suppose an application needs only one instance of a class and the application configures that class at startup: Why should the class itself be responsible for being a singleton? It seems quite logical for the application to take on this responsibility, since the application requires this kind of behavior. The application, not the component, should be the singleton. The application then makes an instance of the component available for any application-specific code to use. When an application uses several such components, it can aggregate them into what we have called a toolbox.

Put simply, the application's toolbox is a singleton that is responsible either for configuring itself or for allowing the application's startup mechanism to configure it...

public class Toolbox {
     private static Toolbox _instance;

     public static Toolbox Instance {
         get {
             if (_instance == null) {
                 _instance = new Toolbox();
             }
             return _instance;
         }
     }

     protected Toolbox() {
         Initialize();
     }

     protected void Initialize() {
         // Your code here
     }

     private MyComponent _myComponent;

     public MyComponent MyComponent() {
         get {
             return _myComponent();
         }
     }
     ...

     // Optional: standard extension allowing
     // runtime registration of global objects.
     private Map components;

     public Object GetComponent (String componentName) {
         return components.Get(componentName);
     }

     public void RegisterComponent(String componentName, Object component)
     {
         components.Put(componentName, component);
     }

     public void DeregisterComponent(String componentName) {
         components.Remove(componentName);
     }

}

But guess what? It is a singleton!

And what is a singleton?

Maybe that's where the confusion begins.

To me, the singleton is an object enforced to have a single instance only and always. You can access it anywhere, any time, without needing to instantiate it. That's why it's so closely related to static. For comparison, static is basically the same thing, except it's not an instance. We don't need to instantiate it, we can't even, because it's automagically allocated. And that can and does bring problems.

From my experience, simply replacing static for Singleton solved many issues in a medium size patchwork bag project I'm on. That only means it does have some usage for bad designed projects. I think there's too much discussion if the singleton pattern is useful or not and I can't really argue if it's indeed bad. But still there are good arguments in favor for singleton over static methods, in general.

The only thing I'm sure is bad about singletons, is when we use them while ignoring good practices. That's indeed something not that easy to deal with. But bad practices can be applied to any pattern. And, I know, it is too generic to say that... I mean there's just too much to it.

Don't get me wrong!

Simply put, just like global vars, singletons should still be avoided at all times. Specially because they are overly abused. But global vars can not be avoided always and we should use them in that last case.

Anyway, there are many other suggestions other than the Toolbox, and just like the toolbox, each one has its application...

Other alternatives

The best article I've just read about singletons suggests Service Locator as an alternative. To me that is basically a "Static Toolbox", if you will. In other words, make the Service Locator a Singleton and you have a Toolbox. That does go against its initial suggestion of avoiding the singleton, of course, but that's only to enforce singleton's issue is how it's used, not the pattern in itself.

Others suggest Factory Pattern as an alternative. It was the first alternative I heard from a colleague and we quickly eliminated it for our usage as global var. It sure has its usage, but so does singletons.

Both alternatives above are good alternatives. But it all depends on your usage.

Now, implying singletons should be avoided at all costs is just wrong...

Aaronaught's answer is suggesting to never use singletons, for a series of reasons. But they're all reasons against how it's ill used and abused, not directly against the pattern itself. I do agree with all the worrying about those points, how can't I? I just think it's misleading.

The inabilities (to abstract or subclass) are indeed there, but so what? It's not meant for that. There is no inability to interface, as far as I can tell. High coupling can also be there, but that's just because how it's commonly used. It doesn't have to. In fact, the coupling in itself has nothing to do with the singleton pattern. That being clarified, it also already eliminates the difficulty to test. As for the difficulty to parallelize, that depends on the language and platform so, again, not a problem on the pattern.

Practical examples

I often see 2 being used, both in favor and against singletons. Web cache (my case) and log service.

The logging, some will argue, is a perfect singleton example, because, and I quote:

The requesters need a well-known object to which to send requests to log. This means a global point of access.

Since the logging service is a single event source to which multiple listeners can register, there only needs to be one instance.

Although different applications may log to different output devices, the way they register their listeners is always the same. All customization is done through the listeners. Clients can request logging without knowing how or where the text will be logged. Every application would therefore use the logging service exactly the same way.

Any application should be able to get away with only one instance of the logging service.

Any object can be a logging requester, including reusable components, so that they should not be coupled to any particular application.

While others will argue it makes difficult to expand the log service once you eventually realize it actually shouldn't be only one instance.

Well, I say both arguments are valid. The problem here, again, isn't on the singleton pattern. It's on architectural decisions and weighting if refactoring is a viable risk. It's a further problem when, usually, refactoring is the last needed corrective measure.

too long: didn't read:

disclaimer: this section contains the only comment added today, 8 years after everything else written here.

global variables (and thus, anything like a singleton such as the toolbox) must be always avoided and will never be fully eliminated.

unless you're absolutely and completely sure you need a global variable, avoid it!


问:
Why not expose a primary key
In my education I have been told that it is a flawed idea to expose actual primary keys (not only DB keys, but all primary accessors) to the user.

I always thought it to be a security problem (because an attacker could attempt to read stuff not their own).

Now I have to check if the user is allowed to access anyway, so is there a different reason behind it?

Also, as my users have to access the data anyway I will need to have a public key for the outside world somewhere in between. Now that public key has the same problems as the primary key, doesn't it?

There has been the request of an example on why do that anyway, so here is one.
Keep in mind that the question is meant to be about the principle itself not only if it applies in this example. Answers addressing other situations are explicitly welcome.

Application (Web, Mobile) that handles activity, has multiple UIs and at least one automated API for intersystem communication (e.G. the accounting department wants to know how much to charge the customer based on what has been done).
The Application has multiple customers so separation of their data (logically, the data is stored in the same DB) is a must have of the system. Each request will be checked for validity no matter what.

Activity is very fine granular so it is together in some container object, lets call it "Task".

Three usecases:

User A wants to send User B to some Task so he sends him a link (HTTP) to get some Activity done there.

User B has to go outside the building so he opens the Task on his mobile device.

Accounting wants to charge the customer for the Task, but uses a third party accounting system that automatically loads the Task / Activity by some code that refers to the REST - API of the Application

Each of the usecases requires (or gets easier if) the agent to have some addressable identifier for the Task and the Activity.

答:
This is from a comment on Greystone28's answer by CodeCaster. It is an example of what you are saying:

I expose InvoiceNumber, which has a meaning to and is changeable by
  the customer, but I also expose InvoiceID, which my code uses to
  uniquely identify the invoice. You don't have to (and more often don't
  want to) let the user-key be the storage-key. This question is about the latter.

What purpose in your app does diplaying the InvoiceID serve?

By expose, I'm assuming you mean the user can see it. Only expose it if the user needs it to use your app. It could be used by techniical support or some administrative stuff. I've worked with a few apps that do this. It does make it easier to provide support when I know the specific record in question.

ContentLicense: CC BY-SA 3.0

Title: Why not expose a primary key


问:
Default vs Impl when implementing interfaces in Java
After reading Should package names be singular or plural? it occurred to me that I've never seen a proper debate covering one of my pet peeves: naming implementations of interfaces.

Let's assume that you have a interface Order that is intended to be implemented in a variety of ways but there is only the initial implementation when the project is first created. Do you go for DefaultOrder or OrderImpl or some other variant to avoid the false dichotomy? And what do you do when more implementations come along?

And most important... why?

答:
Most of these answers describe what is being done but not why.

What has happened to OO principles? What does Impl tell me about a class and how to use it? You should be concerned about understanding the usages not how it is constructed.

If I create a Person interface, what is a PersonImpl? Meaningless. At least DefaultPerson tells me whoever coded it shouldn't have created an interface.

Interfaces are typing for polymorphism and should be used as such.


答:
Because Primary Keys are an implementation detail.

If you migrate databases, your primary keys might change due to order of insertion, removal of old records... a few different reasons. If you migrate database platforms you may no longer have an actual primary key at all. Exposing the PK above the data access layer is a leaky abstraction, with all of the coupling concerns that entails.

Title: Why not expose a primary key

Body:
In my education I have been told that it is a flawed idea to expose actual primary keys (not only DB keys, but all primary accessors) to the user.

I always thought it to be a security problem (because an attacker could attempt to read stuff not their own).

Now I have to check if the user is allowed to access anyway, so is there a different reason behind it?

Also, as my users have to access the data anyway I will need to have a public key for the outside world somewhere in between. Now that public key has the same problems as the primary key, doesn't it?

There has been the request of an example on why do that anyway, so here is one.
Keep in mind that the question is meant to be about the principle itself not only if it applies in this example. Answers addressing other situations are explicitly welcome.

Application (Web, Mobile) that handles activity, has multiple UIs and at least one automated API for intersystem communication (e.G. the accounting department wants to know how much to charge the customer based on what has been done).
The Application has multiple customers so separation of their data (logically, the data is stored in the same DB) is a must have of the system. Each request will be checked for validity no matter what.

Activity is very fine granular so it is together in some container object, lets call it "Task".

Three usecases:

User A wants to send User B to some Task so he sends him a link (HTTP) to get some Activity done there.

User B has to go outside the building so he opens the Task on his mobile device.

Accounting wants to charge the customer for the Task, but uses a third party accounting system that automatically loads the Task / Activity by some code that refers to the REST - API of the Application

Each of the usecases requires (or gets easier if) the agent to have some addressable identifier for the Task and the Activity.


问:
Should package structure closely resemble class hierarchy?
Pretty simple question.  Should package structure closely resemble class hierarchy?  If so, how closely?  Why or why not?

For instance, let's say you've got class A and class B, plus class AFactory and class BFactory.  You put class A and class B in the package com.something.elements, and you put AFactory and BFactory in com.something.elements.factories.  AFactory and BFactory would be further down the hierarchy package-wise, but they'd be further up class-wise.  Is this sort of thing a good idea or a bad idea?

答:
You are asking the wrong question. It is not whether something is a good or bad idea but whether it is useful.

Consider another developer who has to deal with your code. What will they understand from the package structure? Will it improve their understanding and ability to maintain and expand you code, or will it make them want to change it?

The technical aspects of OO are clear, inheritance and polymorphism (implements/extends) amongst others, and these are apparent from the code, along with design patterns. Package structure and naming should be about describing the aims and functionality of the code base (e.g. what is an xxxImpl and how does it work?)

The previous answer talks about coupling and may help in general development, but having the business goals and requirements clearly defined in the overall structure is much more useful.


问:
How to estimate tasks in scrum?
Let's say we have a backlog of User Stories, each with an estimated number of Story Points, and now we're doing the Sprint Planning.

Now, the Stories should be broken down into tasks and many Scrum resources suggest that each task should be estimated in person-hours. Since all questions have been discussed by the team at this point, estimating a task should not take longer than a minute. However, since a task should not be longer than a day, assuming a three week sprint with 8 developers means 120 tasks, and taking two hours only for estimations seems to be a bit much to me.

I know that experienced teams can skip or short-cut task estimations, but let's say we're not at that stage yet.

In your experience, how many tasks are there in a sprint and how long should it take to estimate all of them? (Estimating only half of them doesn't make much sense, does it?)

Clarifications:

I know the answer depends on sprint length and team size, so let's assume 8 developers and three weeks.

The numbers mentioned might be rules of thumb, but even if they are off (eg, more tasks, less time needed to estimate each) we will end up with about 2 hours for the estimation. So maybe the question should be "What percentage of the planning meeting should be reserved for pure task estimation, and don't we have better things to do?"

答:
My own opinion is that the task hours estimating is wasted time in sprint planning.  Generally, the estimates are wrong, and I get no value on reporting on them.  However, many agile task tracking tools use these hours to generate burndown, so we need something in there.

To save time, I started following this process:

Set each task created to "1 hour" as soon as the task is created.

As developers tackle tasks throughout the sprint, if they think it takes more than the one hour on the task, they can update it to a more realistic value.

As tasks get completed, burndown reports update on hours remaining.

You'll still have the ability to see how progress is going, and whether you are on track, but you can use your sprint planning time for more valuable actions like understanding the stories and figuring out what tasks have to be done.

Title: How to estimate tasks in scrum?


答:
For most applications it's pretty much essential that you DO expose keys to users. To use an information system effectively the users of that system will normally need a way to identify the information within it and to relate that information to something in the world outside the database. In relational database terms, those identifiers are keys.

One well-used design pattern is to create an additional, purely "technical" key for database tables as a means of abstraction. For example to provide a stable (relatively unchanging) key where some alternative key is subject to change. Such technical keys typically aren't exposed to end users because doing so undermines the intended abstraction from user requirements. It has nothing to do with security.

The problem / misunderstanding implicit in your question is due to inappropriate use of the term primary key. A primary key is just one among several "candidate" keys (several possible identifiers in a database table). The primary key doesn't necessarily require any fundamentally different property to any other key so assertions and design principles that apply specifically to primary keys and not to other keys are always suspect and often wrong.

Given that you will usually need to expose a key to your user, what should that key be? Try to make your keys Familiar, Simple and Stable. Familiarity and simplicity make keys easy to read and remember and will help avoid data entry errors. Stability means the key changes infrequently which also helps avoid the possibility of misidentification.

Title: Why not expose a primary key


问:
Is "If a method is re-used without changes, put the method in a base class, else create an interface" a good rule-of-thumb?
A colleague of mine came up with a rule-of-thumb for choosing between creating a base class or an interface.

He says:

Imagine every new method that you are about to implement. For each of them, consider this: will this method be implemented by more than one class in exactly this form, without any change? If the answer is "yes", create a base class. In every other situation, create an interface.

For example:

Consider the classes cat and dog, which extend the class mammal and have a single method pet(). We then add the class alligator, which doesn't extend anything and has a single method slither().

Now, we want to add an eat() method to all of them.

If the implementation of eat() method will be exactly the same for cat, dog and alligator, we should create a base class (let's say, animal), which implements this method.

However, if it's implementation in alligator differs in the slightest way, we should create an IEat interface and make mammal and alligator implement it.

He insists that this method covers all cases, but it seems like over-simplification to me.

Is it worth following this rule-of-thumb?

答:
Interfaces are types. They provide no implementation. They simple define the contract for handling that type. This contract has to be met by any class implementing the interface.

The use of interfaces and abstract/base classes should be determined by the design requirements.

A single class does not require an interface.

If two classes are interchangeable within a function they should implement a common interface. Any functionality that is implemented identically could then be refactored into an abstract class that implements the interface. The interface could be deemed redundant at that point if there is no distinguishing functionality. But then what is the difference between the two classes?

Using abstract classes as types is generally messy as more functionality is added and as a hierarchy expands.

Favour composition over inheritance - all this goes away.


问:
What are the requirements for attribution in the MIT License?
choosealicense.com claims that the MIT license is “A permissive license that is short and to the point. It lets people do anything with your code with proper attribution and without warranty” (emphasis mine). Reading the license, though, I don’t see anything claiming that attribution to the original author has to be anywhere, so where are they taking that from?

答: The fourth paragraph says that the copyright notice in the second paragraph must be reproduced. Users of the licence substitute the [fullname] with their actual name. That is what constitutes "proper attribution" in the mind of the MIT: every user of the software can find out who wrote it if they want to.</p>


问:
What Functional features are worth a little OOP confusion for the benefits they bring?
After learning functional programming in Haskell and F#, the OOP paradigm seems ass-backwards with classes, interfaces, objects.  Which aspects of FP can I bring to work that my co-workers can understand?  Are any FP styles worth talking to my boss about retraining my team so that we can use them?

Possible aspects of FP:

Immutability

Partial Application and Currying

First Class Functions (function pointers / Functional Objects / Strategy Pattern)

Lazy Evaluation (and Monads)

Pure Functions (no side effects)

Expressions (vs. Statements - each line of code produces a value instead of, or in addition to causing side effects)

Recursion

Pattern Matching

Is it a free-for-all where we can do whatever the programming language supports to the limit that language supports it?  Or is there a better guideline?

答:
You may have to constrain what parts of your knowledge you use at work, the way Superman has to pretend to be Clark Kent in order to enjoy the perks of a normal life.  But knowing more will never hurt you.  That said, some aspects of Functional Programming are appropriate for an Object Oriented shop, and other aspects may be worth talking to your boss about so that you can raise the average knowledge level of your shop and get to write better code as a result.

FP and OOP are not mutually exclusive.  Look at Scala.  Some think it's the worst because it is impure FP, but some think it is the best for that same reason.

One by one, here are some aspects that work great with OOP:

Pure Functions (no side effects) - Every programming language I know of supports this.  They make your code much, much easier to reason about and should be used whenever practical.  You don't have to call it FP.  Just call it good coding practices.

Immutability: String is arguably the most commonly used Java object and it is immutable.  I cover Immutable Java Objects and Immutable Java Collections on my blog.  Some of that may be applicable to you.

First Class Functions (function pointers / Functional Objects / Strategy Pattern) - Java has had a hobbled, mutant version of this since version 1.1 with most of the API classes (and there are hundreds) that implement the Listener interface.  Runnable is probably the most commonly used functional object.  First Class Functions are more work to code in a language that doesn't support them natively, but sometimes worth the extra effort when they simplify other aspects of your code.

Recursion is useful for processing trees.  In an OOP shop, that is probably the primary appropriate use of recursion.  Using recursion for fun in OOP should probably be frowned upon if for no other reason than most OOP languages don't have the stack space by default to make this a good idea.

Expressions (vs. Statements - each line of code produces a value instead of, or in addition to causing side effects) - The only evaluative operator in C, C++, and Java is the Ternary Operator.  I discuss appropriate usage on my blog.  You may find you write some simple functions that are highly reusable and evaluative.

Lazy Evaluation (and Monads) - mostly restricted to lazy Initialization in OOP.  Without language features to support it, you may find some APIs that are useful, but writing your own is difficult.  Maximize your use of streams instead - see the Writer and Reader interfaces for examples.

Partial Application and Currying - Not practical without first class functions.

Pattern Matching - generally discouraged in OOP.

In summary, I do not think work should be a free-for-all where you can do whatever the programming language supports to the limit that language supports it.  I think readability by your coworkers should be your litmus test for code made for hire.  Where that chafes you the most I would look into starting some education at work to broaden the horizons of your co-workers.


问:
What is the difference between all-static-methods and applying a singleton pattern?
I am making a database to store information about the users of my website (I am using stuts2 and hence Java EE technology). For the database I'll be making a DBManager. Should I apply singleton pattern here or rather make all its methods static?

I will be using this DBManager for basic things like adding, deleting and updating User profiles. Also, I'll use it for all other querying purposes, for instance to find out whether a username already exists and to get all users for administrative purposes and stuff like that.

My questions:

What is the benefit of singleton pattern?

Which thing is most apt here? All static methods or a singleton pattern?

Please compare both of them.

P.S. The database is bigger than this. Here I am talking only about the tables which I'll be using for storing User Information.

答:
I hope this will answer just the main question here.

There are already few great answers in SO. I'll just quote them.

Best answer, by Heinzi:

A singleton is used to introduce some kind of global state to an
  application. If it is stateless, I also don't see the point of using a
  singleton, unless

you expect to extend it with state in the foreseeable future or

you need an object instance for some particular technical reason (for example, for the C# SyncLock statement, although this is
  already quite far-fetched) or

you need inheritance, i.e., you want to be able to easily replace your singleton with another one using the same interface but a
  different implementation. For example, the
  Toolkit.getDefaultToolkit() method in Java will return a singleton
  whose exact type is system dependent.

High relevant comment, by back2dos:

(...) singletons are misused to introduce global states. The purpose of a singleton is not to make an object globally available, but to enforce that an object is instantiated only once. Global objects are a necessary evil. Unless really required, one should try not to use them, since they generally lead to high coupling, with SomeSingleton.getInstance().someMethod() all over the place.

tzaman also wrote a good answer:

I could see a case for a stateless singleton being used instead of a
  static methods class, namely for Dependency Injection.

If you have a helper class of utility functions that you're using
  directly, it creates a hidden dependency; you have no control over who
  can use it, or where. Injecting that same helper class via a stateless
  singleton instance lets you control where and how it's being used, and
  replace it / mock it / etc. when you need to.

Making it a singleton instance simply ensures that you're not
  allocating any more objects of the type than necessary (since you only
  ever need one).

And finally Sebastien also answered himself quite well:

Actually i've found another answer not mentionned here: static methods are harder to test.

It seems most test frameworks work great for mocking instance methods but many of them no not handle in a decent way the mock of static methods.

That being said, I advise using the Toolbox pattern.

ContentLicense: CC BY-SA 4.0


问:
Is code reviewing good practice?
When the company I work in hired new managers, they offered us to overview someone's code on every meeting. We have meetings every two weeks, so each time one of developers was to show his/her code on the projector, and others were going to discuss it.

I thought this would be great: each developer would be more careful when writing code and we could share our experience better. But somehow we forgot about this and the offer just remained an offer.

What are the benefits of this and are there any drawbacks?

答: Code review helps see "the whole". Separate developers have a tendency to see just their requirements/problems. CR discovers ideas and solutions from the whole perspective. CR mainly helps eliminate waste of unnecessary work. The whole product is cheaper and in better quality.</p>

Title: Is code reviewing good practice?


问:
Can I use GPL code as textual data in my app?
In essence, I'm wondering how licenses affect the legality of using source code as data. By that I mean literally storing code in a database as strings and using it e.g. for some syntax highlighting experiments, or other such pursuits.

I can think of a couple of scenarios:

My project is closed-source, and I want to use open-source code as data. If I store code that is under GPL, does the GPL license apply to my project? What about other licenses?

My project is open-source, but licensed under e.g. MIT. Again, if I store GPL code, does that affect my project?

I was thinking about GPL specifically because of its viral nature, but if other licenses would have applicable effects, I'd be interested in hearing about them as well.

答:
(Note: I'm not a lawyer.)

From the Free Software Foundation's GPL FAQ:

If a programming language interpreter has a license that is incompatible with the GPL, can I run GPL-covered programs on it?

When the interpreter just interprets a language, the answer is yes. The interpreted program, to the interpreter, is just data; the GPL doesn't restrict what tools you process the program with.

It would seem that the "it's just data" argument applies in your case as well. The GPL's copyleft provisions only apply when the GPL'd work and some other work form a derivative work, which doesn't appear to happen in your case.

Of course, any GPL work you distribute must stay under the GPL, but the GPL provisions will not apply to your project as a whole, because it doesn't combine with your existing work into a new derived work.


答:
The usual "I'm not a lawyer" disclaimer, but because...

You're not actually linking to the code in an executable way, and

You're program will work perfectly fine without the code (i.e. the code is not part of a derived work),

you are therefore not redistributing the code, in the GPL sense, and are therefore not bound by its terms.

You can further strengthen this proposition by only using part of the code for illustration purposes (in the "fair use" sense), and not the code in its entirety.

Title: Can I use GPL code as textual data in my app?

Body:
In essence, I'm wondering how licenses affect the legality of using source code as data. By that I mean literally storing code in a database as strings and using it e.g. for some syntax highlighting experiments, or other such pursuits.

I can think of a couple of scenarios:

My project is closed-source, and I want to use open-source code as data. If I store code that is under GPL, does the GPL license apply to my project? What about other licenses?

My project is open-source, but licensed under e.g. MIT. Again, if I store GPL code, does that affect my project?

I was thinking about GPL specifically because of its viral nature, but if other licenses would have applicable effects, I'd be interested in hearing about them as well.


问:
Should I continue learning a language if in the meanwhile I became interested in another language/platform?
I started learning Java a couple of months ago. I also wanted to become more exposed to linux so I installed ubuntu and started working with Java since then. In the meanwhile however I became more interested in C# and in learning the Windows platform. At this point I'm asking myself if I should stop learning Java and move to the .NET world. I don't hate or dislike Java by the way, I am just more curious about windows/.NET at this point in time. </p>

<p>My question is, should I remain with Java or go with C#/.NET? What is your advice?  </p>

答: Study both while you can along with good programming practices in general. You're in an enviable position that may not last long due to a new project/job requirement. Hopefully, you'll learn enough about both of them to be able to compare and contrast the two and make objective decisions on when one is more appropriate than the other. I hope you can remain in control of this choice as long as possible.</p>

OwnerDisplayName: UML

ContentLicense: CC BY-SA 2.5


答:
At the request of exizt, I'm expanding my comment to a longer answer.

The biggest mistake that people make is believing that interfaces are simply empty abstract classes. An interface is a way for a programmer to say, "I don't care what you give me, as long as it follows this convention."

The .NET library serves as a wonderful example. For example, when you write a function that accepts an IEnumerable<T>, what you are saying is, "I don't care how you are storing your data. I just want to know that I can use a foreach loop.

This leads to some very flexible code. Suddenly in order to be integrated, all you need to do is play by the rules of the existing interfaces. If implementing the interface is difficult or confusing, then maybe that is a hint that you are trying to shove a square peg in a round hole.

But then the question comes up: "What about code reuse? My CS professors told me that inheritance was the solution to all code reuse problems and that inheritance allows you to write once and use everywhere and it would cure menangitis in the process of rescuing orphans from the rising seas and there would be no more tears and on and on etc. etc. etc."

Using inheritance just because you like the sound of the words "code reuse" is a pretty bad idea. The code styling guide by Google makes this point fairly concisely:

Composition is often more appropriate than inheritance. ... [B]ecause
  the code implementing a sub-class is spread between the base and the
  sub-class, it can be more difficult to understand an implementation.
  The sub-class cannot override functions that are not virtual, so the
  sub-class cannot change implementation.

To illustrate why inheritance is not always the answer, I'm going to use a class called MySpecialFileWriter†. A person who blindly believes that inheritance is the solution to all problems would argue that you should try to inherit from FileStream, lest you duplicate FileStream's code. Smart people recognize that this is stupid. You should just have a FileStream object in your class (either as a local or member variable) and use its functionality.

The FileStream example may seem contrived, but it's not. If you have two classes that both implement the same interface in the exact same way, then you should have a third class that encapsulates whatever operation is duplicated. Your goal should be to write classes that are self-contained reusable blocks that can be put together like legos.

This doesn't mean that inheritance should be avoided at all costs. There are many points to consider, and most will be covered by researching the question, "Composition vs. Inheritance." Our very own Stack Overflow has a few good answers on the subject.

At the end of the day, your coworker's sentiments lack the depth or understanding necessary to make an informed decision. Research the subject and figure it out for yourself.

 † When illustrating inheritance, everyone uses animals. That is useless. In 11 years of development, I've never written a class named Cat, so I'm not going to use it as an example.

Title: Is "If a method is re-used without changes, put the method in a base class, else create an interface" a good rule-of-thumb?

Body:
A colleague of mine came up with a rule-of-thumb for choosing between creating a base class or an interface.

He says:

Imagine every new method that you are about to implement. For each of them, consider this: will this method be implemented by more than one class in exactly this form, without any change? If the answer is "yes", create a base class. In every other situation, create an interface.

For example:

Consider the classes cat and dog, which extend the class mammal and have a single method pet(). We then add the class alligator, which doesn't extend anything and has a single method slither().

Now, we want to add an eat() method to all of them.

If the implementation of eat() method will be exactly the same for cat, dog and alligator, we should create a base class (let's say, animal), which implements this method.

However, if it's implementation in alligator differs in the slightest way, we should create an IEat interface and make mammal and alligator implement it.

He insists that this method covers all cases, but it seems like over-simplification to me.

Is it worth following this rule-of-thumb?


答:
This is really a question for the lawyers (and could be deemed off-topic for that reason), but my take on it is this:

As your code does not derive from or depend on the GPL-licensed code in any way, your code can't be seen as a derived work of the GPL-licensed code. Because of that, the GPL terms do not extent to your code.

When distributing the data that you use with your program, that is still covered by the GPL license and thus requires you to distribute the GPL-licensed 'text' in source code form as well. This is mostly relevant if you have your data in a database or something similar.


问:
In what URL segment do you have language? /en/admin/dashboard or /admin/en/dashboard?
maybe you are thinking that this is another dump question about language in URL, but I hope it is not! I've red many articles on this, but non of them was dealing with "sections of site" (described bellow).

I am programming a new application platform in laravel/php and I am still not 100% convinced where to put language slug.

There are many places where you can put it - some of them are better some are worse:

example.com/en/article

en.example.com/article

example.com/article?lang=en

My personal choice is to put language after the domain - so the first option in above list.

But what if you are in some special secion like admin or api? where do you put language then?

example.com/en/admin/dashboard

example.com/en/api/v1/user/login

or

example.com/admin/en/dashboard

example.com/api/v1/en/user/login

(in frontend it is left the same: example.com/en/some-article)

what do you preffer? what are cons and pros? One thing is using language in first segments is far more easier to programm than when it have some variants...

EDIT: I am also using two lists of avalible languages to determine what languages are avalible for app/backend and for frontend (if the app is something like CMS). Eg. web can be only in english but app (cms) can be in czech, english, italian...

P.S. whould you recoment using only en, cs or do it in full power with cz-CZ, en-US ?

thanks for any thoughts!

J.

答:
For your developer-facing API, you should obey the Accept-Language header for the reason CodeCaster mentioned in the comments:

Translations are different representations of the same resource, so the resource identifier should remain the same.

However, for UI (i.e. anything where the user-agent is a web browser) using Accept-Language to decide which language to render the page in is probably a bad idea, since it is effectively unchangeable (unless you're in the 0.001% of users who knows how) and may not reflect your users' actual language preference anyway. Using Accept-Language to select the default language a user sees is a nice idea, but even Google recommends that you keep the content for each language on separate URLs.

As to your actual question: Where in the URL should the language fragment go? Well... It doesn't really matter. There are no strict rules for this. It will largely depend on what is easiest for you to implement in your chosen framework.

Here is some additional reading:

How should I structure my URLs for both SEO and localization? (Webmasters.SE)

Working with multilingual websites (Google Webmaster Central blog)


答:
TL;DR

[H]ow many tasks are there in a sprint and how long should it take to estimate all of them?

Your question has no possible canonical answer. While you can certainly use some rules of thumb to calculate a reasonable upper bound for task volume, there's no universal conversion ratio for stories to tasks, or tasks to man-hours.

For example, a commonly-accepted rule of thumb is that a task should be sized between a half-day and two days so that the done/not-done feedback loop remains tight. Teams can and do violate this rule of thumb, as it is not a framework requirement, but the most successful teams I've worked with all follow the spirit of this rule.

Tasks Per Sprint

I know the answer depends on sprint length and team size, so let's assume 8 developers and three weeks.

This is axiomatically wrong, since the number of tasks is dependent on the number of stories and the quantity and granularity of each story's decomposed tasks. Nevertheless, you can calculate a rough upper bound for sanity checking.

If you assume a priori that:

each task requires only one developer (this is often not the case)

30% of your sprint is consumed by framework overhead (this number varies by sprint length)

you aren't applying any fudge factors for the fact that productive work hours are generally <= 6 hours per work day

then you have 10.5 "days" available for tasks per developer to allocate to tasks in each sprint. Further assuming:

8 developers

all developers are interchangeable

there are no queuing activities or dependencies between tasks

you are including Definition of Done activities as explicit tasks

then following the recommended task-sizing rule would give your team a capacity between 21-148 tasks per three-week sprint.

Avoid Estimating Tasks in Man-Hours

The simple solution here is to avoid estimating tasks in ideal man-hours and toss all the problematic (and often inaccurate) assumptions overboard. By simply not accepting stories into the sprint that exceed your sustainable velocity, you solve most of your sprint planning problems without estimating in hours.

By ensuring that your stories are decomposed into properly-sized done/not-done tasks of no more than a couple of days, you can quickly see if you mistakenly accepted a story that is more complex than your story-point estimate, or if there was hidden work that needs to be documented and re-scoped with the Product Owner during Sprint Planning.

Healthy teams dedicate about half a day to decomposing tasks for the Sprint Backlog. If you don't take the time to do this in the second half of Sprint Planning, then you are much more likely to uncover entanglements, unexpected dependencies, or unplanned work later in the sprint.

A four-hour Sprint Backlog meeting represents less than 3% of your three-week sprint length, and is where most of the design and architectural analysis is done within the Scrum framework. Is shaving that down to 2% by short-changing the task analysis really worth the risk to your project? I'd say no, but your mileage may vary.

Title: How to estimate tasks in scrum?

Body:
Let's say we have a backlog of User Stories, each with an estimated number of Story Points, and now we're doing the Sprint Planning.

Now, the Stories should be broken down into tasks and many Scrum resources suggest that each task should be estimated in person-hours. Since all questions have been discussed by the team at this point, estimating a task should not take longer than a minute. However, since a task should not be longer than a day, assuming a three week sprint with 8 developers means 120 tasks, and taking two hours only for estimations seems to be a bit much to me.

I know that experienced teams can skip or short-cut task estimations, but let's say we're not at that stage yet.

In your experience, how many tasks are there in a sprint and how long should it take to estimate all of them? (Estimating only half of them doesn't make much sense, does it?)

Clarifications:

I know the answer depends on sprint length and team size, so let's assume 8 developers and three weeks.

The numbers mentioned might be rules of thumb, but even if they are off (eg, more tasks, less time needed to estimate each) we will end up with about 2 hours for the estimation. So maybe the question should be "What percentage of the planning meeting should be reserved for pure task estimation, and don't we have better things to do?"


答:
I want to take a lingual and semantic approach towards this. An interface is not there for DRY. While it can be used as a mechanism for centralization alongside having an abstract class that implements it, it's not meant for DRY.

An interface is a contract.

IAnimal interface is a all-or-nothing contract between alligator, cat, dog and the notion of an animal. What it says essentially is "if you want to be an animal, either you must have all these attributes and characteristics, or you're not an animal anymore".

Inheritance on the other side is a mechanism for reuse. In this case, I think having a good semantic reasoning can help you decide which method should go where. For example, while all animals might sleep, and sleep the same, I won't use a base class for it. I first put the Sleep() method in the IAnimal interface as an emphasis (semantic) for what it takes to be an animal, then I use a base abstract class for cat, dog, and alligator as a programming technique to don't repeat myself.


答:
Primary key is there, just as a handle to the tuple (record, row) you try to access as a developer. It's also used in referential integrity (foreign key constraints), and maybe it has one or more use cases too.

Essentially, there is nothing bad about exposing it to users, or even hackers. Because I don't know of an attack that uses primary key for example.

But in security, we have many principles (which we accept and don't approve) and we need to adhere them:

The principle of lease privilege

Security through obscurity

And some other principles. What they say essentially is that:

If you don't need to expose your data, why would you at all?

Title: Why not expose a primary key


答:
Functional programming yields very practical, down-to-earth,
productivity in everyday's code writing: some features favour
terseness, which is great because the less code you write, the less
failures you do, and the less maintenance is required.

Being a mathematician, I find fancy functional stuff very appealing,
but it is usually useful when designing an application: these
structures can encode in the program structure a lot of invariants of
the program, without representing these invariants by variables.

My favourite combination may look pretty trivial, I however believe
that it has a very high productivity impact. This combination is Partial
Application and Currying and First Class Functions which I would
relabel never write a for-loop again: instead pass the body of the
loop to an iterating or mapping function.  I was recently hired for a
C++ job and I amusingly noticed, I totally lost the habit of writing
for-loops!

The combination of Recursion and Pattern Matching annihilates the
need of that Visitor design pattern.  Just compare the code you need
to program an evaluator of boolean expressions: in any functional
programming language this should be about 15 lines of code, in OOP the right thing
to do is to use that Visitor design pattern, which turns that
toy-example in an extensive essay. Advantages are obvious and I am not
aware of any inconvenient.

Title: What Functional features are worth a little OOP confusion for the benefits they bring?

Body:
After learning functional programming in Haskell and F#, the OOP paradigm seems ass-backwards with classes, interfaces, objects.  Which aspects of FP can I bring to work that my co-workers can understand?  Are any FP styles worth talking to my boss about retraining my team so that we can use them?

Possible aspects of FP:

Immutability

Partial Application and Currying

First Class Functions (function pointers / Functional Objects / Strategy Pattern)

Lazy Evaluation (and Monads)

Pure Functions (no side effects)

Expressions (vs. Statements - each line of code produces a value instead of, or in addition to causing side effects)

Recursion

Pattern Matching

Is it a free-for-all where we can do whatever the programming language supports to the limit that language supports it?  Or is there a better guideline?


问:
Should you always pass the bare minimum data needed into a function in cases like this
Let's say I have a function IsAdmin that checks whether a user is an admin. Let's also say that the admin checking is done by matching user id, name and password against some sort of rule (not important).

In my head there are then two possible function signatures for this:

```<code>public bool IsAdmin(User user);
public bool IsAdmin(int id, string name, string password);
</code>```

I most often go for the second type of signature, thinking that:

The function signature gives the reader a lot more info

The logic contained inside the function doesn't have to know about the User class

It usually results in slightly less code inside the function

However I sometimes question this approach, and also realize that at some point it would become unwieldy. If for example a function would map between ten different object fields into a resulting bool I would obviously send in the entire object. But apart from a stark example like that I can't see a reason to pass in the actual object.

I would appreciate any arguments for either style, as well as any general observations you might offer.

I program in both object oriented and functional styles, so the question should be seen as regarding any and all idioms.

答:
There is one negative point to send classes (reference types) to methods, and that is, Mass-Assignment Vulnerability. Imagine that instead of IsAdmin(User user) method, I have UpdateUser(User user) method.

If User class has a Boolean property called IsAdmin, and if I don't check it during the execution of my method, then I'm vulnerable to mass-assignment. GitHub was attacked by this very signature in 2012.


问:
Do you believe it's a good idea for Software Engineers to have to work as Quality Assurance Engineers for some period of time?
I believe it is.  Why?

I've encountered many Software Engineers who believe they are somehow superior to QA engineers.  I think it may help quench this belief if they do the job of a QA engineer for some time, and realize that it is a unique and valuable skill-set of its own.

The better a Software Engineer is at testing their own programs, the less cost in time their code incurs when making its way through the rest of the software development life-cycle.

The more time a Software Engineer spends thinking about how a program can break, the more often they are to consider these cases as they are developing them, thus reducing bugs in the end product.

A Software Engineer's definition of "complete" is always interesting...if they have spent time as a QA engineer maybe this definition will more closely match the designer of the software's.

Note I make above suggestion with a small time-frame in mind as I am aware having someone work in a position that is not the position they are hired for is definitely a recipe for losing that developer.

What do you all think?

答:
Making programmers accountable for their code and requiring them to fix their own bugs can take care of this. That and a loss of bonus and/or job.

Not that this experience wouldn't help, but how far can you go with this line of thinking? Technical Support, Sales, Beta User, scrub the toilets (that would be a humbling experience).


问:
Finish feature reverted commits from develop
I am using git as a version control system, and using git-flow as the branching model. I started a feature branch some weeks ago in order to maintain the system in a clean state while developping that feature. The main development continued on the develop branch, and changes from develop were merged periodically into the feature, to keep it up to date as much as possible.

However came the time where the feature was finished, and I used git-flow's finish feature to merge the feature back into develop. The merge was successfully done, but then I found out that some of the commits I made in develop were reverted by the merge commit!

Nowhere in develop or in the feature branch were these changes reverted, I can't see any commit that overwrote them. I just can't find anything. The only theory I have for the moment is that git is failing on me, but that would be extremely unlikely. Maybe I did some kind of wrong manipulation that made this situation come true?

I can trace back in the history when the commit was made. I can see that the changes from that commit were reverted by the merge commit. Nowhere in the branch I see a commit that reverts those changes. Yet they were reverted.

How is this even possible?

答:
Finally, it was an error on my part. I recently migrated the projet from SVN to Git, and I had then feature branch in SVN and it was not in sync with the trunk when I made the migration.

I created the first commit in the develop branch with the trunk, and then started a new feature-branch with git, and commited the files as they where in the SVN feature branch.

The commit being newer on the feature branch, and because it was not in sync with the latest trunk changes, Git thought, and for a reason, that the reverted changes were made after the initial commit, bringing these changes in when I merge the branch back into develop.

I resolved this in a separate branch, with a lot of manual work, but now I know that it was not git's fault.


答:
You shouldn't expose it because people who see it will start to use it as their 'account number' which it is NOT.  For example, for my bank account I know what my account number is.  I've memorized it, I use it on the phone with customer service, I use it when filling out forms for other banks to do transfers, for legal documents, for my auto-pay service, etc, etc. I don't want it to change.  The primary key (for my account) on the other hand, I don't know or ever see.

The system that stores it changes over the years from one system to another, through bank merges, system upgrades and replacements, etc, etc.

The primary keys may change through some of these transformation, so if its never been exposed, written down or remembered by any regular user that's a real good thing.

Keys with no business meaning are often termed surrogate keys and are often (but not always) used as primary keys.

btw, this even happens internally when people built interfaces and programs that misuse and expose primary keys and make them part of such systems instead of them just doing one thing - uniquely identifying a database record internally.  I actually learned the above through a 6 year stint supporting a data warehouse system in a hospital.

Title: Why not expose a primary key


问:
How is Sencha Touch performing on Android in practice?
I'm just about to start a project using Sencha Touch, and just done some minor testing on my HTC desire device. All tutorial videos at Vimeo seems to be using an iPhone emulator running on a Mac. Im not sure how fast this emulator is compared to a real iPhone device or even an real Android device, but from what i have experienced, it seems that my HTC desire is not performing that nicly as this emulator.

All animations (sliding, fading, etc) seems abit laggy. You can easily notice that the FPS is much less than on the Vimeo videos.

HTC desire is a relativly new and modern Android 2.2 phone, running with decent hardware, so im wondering if Sencha Touch is "ready" for the Android platform.

Anybody with practical experience with Android and Sencha Touch ?

答: Its Nov 2013 and Sencha 2 kitchen sink demo hangs on my HTC Android 4.0,   other html5 frameworks show better response such as intel's XDK which uses jqMobi.</p>


问:
Which data structure for representing possible navigations between a game's screens?
I am trying to find an appropriate data structure for representing available navigations between a game's screens.

Using a linked list, a node can only have one node after it : inappropriate.

Using a tree seems up to the job as nodes can have many children nodes but it's inconsistent in the sense that a supposedly children item Options can have a parent Title as a children. Also how am I supposed to represent the infinite sequence of the case Title -> Race -> Title -> Race ... without endlessly repeating it in my tree ? Still, this is the best structure I found to accomplish the job.

Here is an example of the possible sequences :

Title

Options

Race

Options

Title

Race

Race

Options

Title

Do you know whether a tree is the way to go or if there's a better structure for this job ?

Edit:

There is a great library for creating graphs for C#/WPF : http://graphsharp.codeplex.com/

It uses http://quickgraph.codeplex.com/ internally.

Here's a small example :

Code-behind:

```<code>using System.Collections.Generic;
using System.Windows;
using GraphSharp.Controls;
using QuickGraph;

namespace WpfApplication15graph
{
    internal class ScreenVertex
    {
        public string Hello { get; set; }
    }

    internal class ScreenEdge : Edge<ScreenVertex>
    {
        public ScreenEdge(ScreenVertex source, ScreenVertex target)
            : base(source, target)
        {
        }
    }

    internal class ScreenLayout : GraphLayout<ScreenVertex, ScreenEdge, ScreenGraph>
    {
    }

    internal class ScreenGraph : BidirectionalGraph<ScreenVertex, ScreenEdge>
    {
    }

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // build graph
            var screenGraph = new ScreenGraph();
            var screenVertex1 = new ScreenVertex {Hello = "1"};
            var screenVertex2 = new ScreenVertex {Hello = "2"};
            var screenVertex3 = new ScreenVertex {Hello = "3"};
            screenGraph.AddVertex(screenVertex1);
            screenGraph.AddVertex(screenVertex2);
            screenGraph.AddVertex(screenVertex3);
            screenGraph.AddEdge(new ScreenEdge(screenVertex1, screenVertex2));
            screenGraph.AddEdge(new ScreenEdge(screenVertex2, screenVertex1));
            screenGraph.AddEdge(new ScreenEdge(screenVertex1, screenVertex3));
            screenGraph.AddEdge(new ScreenEdge(screenVertex3, screenVertex1));
            screenGraph.AddEdge(new ScreenEdge(screenVertex3, screenVertex2));
            ScreenLayout.Graph = screenGraph;

            // get connections for a particular vertex
            IEnumerable<ScreenEdge> inEdges = screenGraph.InEdges(screenVertex3);
            IEnumerable<ScreenEdge> outEdges = screenGraph.OutEdges(screenVertex3);
        }
    }
}
</code>```

XAML :

```<code><Window x:Class="WpfApplication15graph.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:controls="clr-namespace:WPFExtensions.Controls;assembly=WPFExtensions"
        xmlns:controls1="clr-namespace:GraphSharp.Controls;assembly=GraphSharp.Controls"
        xmlns:wpfApplication15Graph="clr-namespace:WpfApplication15graph"
        Title="MainWindow"
        Width="525"
        Height="350">
    <Window.Resources>
        <DataTemplate x:Key="SvTemplate" DataType="wpfApplication15Graph:ScreenVertex">
            <Grid>
                <TextBlock Text="{Binding Hello}" />
            </Grid>
        </DataTemplate>
        <Style TargetType="controls1:VertexControl">
            <Style.Setters>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="controls1:VertexControl">
                            <Border CornerRadius="5" Width="50" Height="50" Background="LightBlue">
                                <ContentPresenter Content="{TemplateBinding Vertex}"
                                                  ContentTemplate="{DynamicResource SvTemplate}" />
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style.Setters>
        </Style>
    </Window.Resources>
    <Grid>
        <controls:ZoomControl>
            <wpfApplication15Graph:ScreenLayout x:Name="ScreenLayout"
                                                HighlightAlgorithmType="Simple"
                                                LayoutAlgorithmType="Circular"
                                                OverlapRemovalAlgorithmType="FSA" />
        </controls:ZoomControl>
    </Grid>
</Window>
</code>```

答:
You may want to consider a Directed Graph.

It's similar to a tree, but with fewer restrictions.  You just have nodes with one-way links between them.  You can make the structure as clean/well-organized/neat/messy/chaotic as you wish.

Be careful if your menu system becomes complicated - DGs can get messy.


问:
How accurate is "Business logic should be in a service, not in a model"?
Situation

Earlier this evening I gave an answer to a question on StackOverflow.

The question:

Editing of an existing object should be done in repository layer or in service?

For example if I have a User that has debt. I want to change his debt. Should I do it in UserRepository or in service for example BuyingService by getting an object, editing it and saving it ?

My answer:

You should leave the responsibility of mutating an object to that same object and use the repository to retrieve this object.

Example situation:

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}
```

<p><em>A comment I received:</em></p>

<blockquote>
  <p>Business logic should really be in a service. Not in a model.</p>
</blockquote>

<p><strong>What does the internet say?</strong></p>

<p>So, this got me searching since I've never really (consciously) used a service layer.
I started reading up on the Service Layer pattern and the Unit Of Work pattern but so far I can't say I'm convinced a service layer has to be used.</p>

<p>Take for example this article by Martin Fowler on the anti-pattern of an Anemic Domain Model:</p>

<blockquote>
  <p>There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters. Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. Instead there are a set of service objects which capture all the domain logic. These services live on top of the domain model and use the domain model for data.</p>

  <p>(...)  The logic that should be in a domain object is domain logic - validations, calculations, business rules - whatever you like to call it.</p>
</blockquote>

<p>To me, this seemed exactly what the situation was about: I advocated the manipulation of an object's data by introducing methods inside that class that do just that. However I realize that this should be a given either way, and it probably has more to do with how these methods are invoked (using a repository).</p>

<p>I also had the feeling that in that article (see below), a Service Layer is more considered as a façade that delegates work to the underlying model, than an actual work-intensive layer.</p>

<blockquote>
  <p>Application Layer [his name for Service Layer]: Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems. The tasks this layer is responsible for are meaningful to the business or necessary for interaction with the application layers of other systems. This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down. It does not have state reflecting the business situation, but it can have state that reflects the progress of a task for the user or the program.</p>
</blockquote>

<p>Which is reinforced here:</p>

<blockquote>
  <p>Service interfaces. Services expose a service interface to which all inbound messages are sent. You can think of a service interface as a façade that exposes the business logic implemented in the application (typically, logic in the business layer) to potential consumers.</p>
</blockquote>

<p>And here:</p>

<blockquote>
  <p>The service layer should be devoid of any application or business logic and should focus primarily on a few concerns. It should wrap Business Layer calls, translate your Domain in a common language that your clients can understand, and handle the communication medium between server and requesting client.</p>
</blockquote>

<p>This is a serious contrast to other resources that talk about the Service Layer:</p>

<blockquote>
  <p>The service layer should consist of classes with methods that are units of work with actions that belong in the same transaction.</p>
</blockquote>

<p>Or the second answer to a question I've already linked:</p>

<blockquote>
  <p>At some point, your application will want some business logic. Also, you might want to validate the input to make sure that there isn't something evil or nonperforming being requested. This logic belongs in your service layer.</p>
</blockquote>

<p><strong>"Solution"?</strong></p>

<p>Following the guidelines in this answer, I came up with the following approach that uses a Service Layer:</p>

<pre class="lang-cs prettyprint-override"><code>class UserController : Controller {
    private UserService _userService;

    public UserController(UserService userService){
        _userService = userService;
    }

    public ActionResult MakeHimPay(string username, int amount) {
        _userService.MakeHimPay(username, amount);
        return RedirectToAction("ShowUserOverview");
    }

    public ActionResult ShowUserOverview() {
        return View();
    }
}

class UserService {
    private IUserRepository _userRepository;

    public UserService(IUserRepository userRepository) {
        _userRepository = userRepository;
    }

    public void MakeHimPay(username, amount) {
        _userRepository.GetUserByName(username).makePayment(amount);
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}
</code>```

Conclusion

All together not much has changed here: code from the controller has moved to the service layer (which is a good thing, so there is an upside to this approach). However this doesn't look like it had anything to do with my original answer.

I realize design patterns are guidelines, not rules set in stone to be implemented whenever possible. Yet I have not found a definitive explanation of the service layer and how it should be regarded.

Is it a means to simply extract logic from the controller and put it inside a service instead?

Is it supposed to form a contract between the controller and the domain?

Should there be a layer between the domain and the service layer?

And, last but not least: following the original comment

Business logic should really be in a service. Not in a model.

Is this correct?

How would I introduce my business logic in a service instead of the model?

答:
I'm working on the greenfield project right now and we had to make few architectural decisions  just yesterday. Funnily enough I had to revisit few chapters of 'Patterns of Enterprise Application Architecture'.

This is what we came up with:

Data layer. Queries and updates database. The layer is exposed through injectable repositories.

Domain layer. This is where the business logic lives. This layer makes a use of injectable repositories and is responsible for the majority of business logic. This is the core of the application that we will test thoroughly.

Service layer. This layer talks to the domain layer and serves the client requests. In our case the service layer is quite simple - it relays requests to the domain layer, handles security and few other cross cutting concerns. This is not much different to a controller in MVC application - controllers are small and simple.

Client layer. Talks to the service layer through SOAP.

We end up with the following:

Client -> Service -> Domain -> Data

We can replace client, service or data layer with reasonable amount of work. If your domain logic lived in the service and you've decided that you want to replace or even remove your service layer, then you'd have to move all of the business logic somewhere else. Such a requirement is rare, but it might happen.

Having said all this, I think this is pretty close to what Martin Fowler meant by saying

These services live on top of the domain model and use the domain
  model for data.

Diagram below illustrates this pretty well:

http://martinfowler.com/eaaCatalog/serviceLayer.html


问:
Relationship between user story, feature, and epic?
As someone who's still new to agile, I'm not sure I completely understand the relationship or difference between user story, feature, and epic.

According to this question, a feature is a collection of stories.  One of the answers suggests that a feature is actually an epic. So are features and epics considered the same thing, that is basically a collection of related user stories?

Our project manager insists that there's a hierarchical structure:

Epic -> Features -> User stories

And that basically all user stories must fall within this structure.  Therefore all user stories must fall under an umbrella feature and all features must fall under an epic.

To me, that sounds awkward.  Can someone please clarify how user stories, features, and epics are related?  Or is there an article that clearly outlines the differences?

答:
Features and Epics are not the same thing.

A Feature is not a User Story.

An Epic is a User Story.

A User Story may be an Epic.

A User Story can contain many Features.

A Feature can fulfill 1 to many User Stories.

In the planning phases, the discussions result in User Stories which are typicaly identified as Epics because the effort to implement solutions for them is too big to accomplish in a few days. Product Features are identified during this phase. But that's just a by-product of the discussion. Features are then used to plan a product road map, which is a separate discussion.

The Epics are taken and discussed further, resulting in User Stories for each Epic. The Features and Epics are used to drive discussions in Backlog Refinement and Sprint Planning sessions. At which time, the User Stories coming out of those discussions are refined, prioritized, and, in Sprint Planning, accepted into sprints for implementation.


问:
Selenium-Nunit Program Structure
My office has a suite of web reporting engines written in VB.  All in all there's about 300 reports with varying displays depending on the data being input into them.  I'm trying to establish an efficient way to deal with such a major diversity, but am struggling with creating a system that won't be a nightmare to code/maintain.

What I've considered doing is:

On program launch, read the steps required for each test page.  This may have multiple tests for the same page with varying inputs.

Write each iteration of the test in XML file under $env:temp/testname

Use the TestCaseSource attribute of Nunit to funnel every related xml file as a source.

My major stumbling block has been how to get that data to the Nunit framework.  Is Nunit really appropriate for what I'm trying to do, or is it too static?

答:
You can combine TestCaseSource with a test data factory producing TestCaseData objects, like shown in the NUnit docs here http://www.nunit.org/index.php?p=testCaseSource&r=2.5.9

This will allow dynamic test data generation at run time. Maybe that is what you are looking for.

Title: Selenium-Nunit Program Structure


问:
Signing redistributed files
In order to submit a desktop application for the Windows 8 app store, you need to digitally sign any driver or .exe associated with the application. However, the application I was trying to submit contains several files that are redistributions of other companies' software, and some of these are not signed. My application was rejected on these grounds. Is it legal (or ethical) to sign other companies' work so that we can submit our application? I think it might be considered some form of false representation but I'm not sure.</p>

答:
I can only answer this question on an ethical basis. Whether my ethical viewpoint is reflected in law is totally outside of my domain of expertise. (Also, I don't know the ins-and-outs of Microsoft's signing practices, so please correct me if I say something that's inconsistent with MS's way of doing things.)

Suppose you sign some file F (having some contents C) with a signing key K. The resulting file/signature pair [F, S(K,C)] says:

The owner of key K hereby asserts that file F has contents C.

Assuming you have the right to distribute the files unsigned, it would seem that you would also have the default right to distribute them with a signature. A signature is a purely programmatic cryptographic transformation of the file that carries the above assertion. (Saying that you can't cryptographically sign something is quite close to claiming you're not allowed to produce a hash of it.)

Your signature doesn't assert that you're the author of the code, but rather it asserts that you are a point of trust in the distribution of the code. That's not being misleading; that's merely a perfectly accurate representation of what is happening. The end recipient must decide whether they trust code distributed by you. The identity of the original author isn't relevant for our trust model, because you are the last person that touched the code before it arrived at their computer.

Title: Signing redistributed files


问:
OAuth alternative for a 2 party system
I'm writing a RESTful service (Java EE, Jersey) and a client application that communicates with it, and I wish to secure it and store any usernames & passwords dedicated in my own database.

I do not want the client to store the username and password locally, not in any form such as base-64 or other encoding at all, I rather have something like the OAuth2 authorization system, where the client app only stores a refresh & access tokens after the resource owner signed-in, but I do not need to provide access to 3rd party services.

Securing my service using Basic auth means the client app has to store the password and send it for each future request, so that's not what I need.

I'm aware that OAuth is intended for different situations, where there are more than just 2 parties involved (see other question).

as mentioned here https://blog.apigee.com/detail/when_to_use_oauth:
OAuth is the only realistic choice for a web application that itself uses another web application's API on behalf of the user. For instance, consider a web application that integrates with Twitter. (Perhaps it's a geolocation app like Foursquare that offers the ability to tweet where you are and what you're doing.)

So what is the correct standardized method to secure my RESTful service if I do not wish to re-invent the wheel and create my own auth method, and if "Basic" is not what I need because it forces me to store the credentials locally on the client, and OAuth is probably an overkill with it's 3rd party access nature.

P.S-
I do wish to provide users with an option to sign-in to my service using facebook or open-id, but that's another story I guess.

答:
Oauth (not sure about Oauth2) gives 3rd party access to resources using combination of consumer key and access token. So, for 2 party communication, you could bend it to only use consumer key without (or empty) access token. This will only give you a way to authenticate requests by using Oauth Authorization header.

Then, what you use as consumer key is up to you. It could be as simple as using user id as consumer key and user password as consumer secret, so you won't have to store them anywhere.

Title: OAuth alternative for a 2 party system


问:
How do I create an environment where fixing tests is seen as a priority?
I am a software engineer at a medium sized company.  We have a fairly robust testing platform running on TeamCity.  It does unit tests on every checkin, and a daily unit test/BVT run.

The problem is - we have a great deal of broken unit tests.

Quite often, I bring up the pointlessness of unit tests if they are constantly breaking and unmaintained.  Being unable to see if a change has caused a regression removes most of the value of a unit testing platform.

I would like to get a seed planted that will create a culture of good habits - fixing tests when they're broken, seeing them as valuable, prioritizing the fixing of tests along with other work.

I've tried bribery (baked goods!), just plain asking, and speaking to team leads.  Everyone says that it's a good idea, but I see to be the only one doing anything about it.

What is the best way to get started on encouraging others to fix their tests, and prioritize test fixing within their sprints?

If there is a less subjective way to ask this, I would be happy to accept any tips.

答:
Make it so that's impossible to actually release anything without fixing the tests.

Fail the build if any tests fail.

Fail the build if any tests are ignored.

Fail the build if test coverage goes below a certain level (so people can't just delete tests to work around it).

Use the CI server to do your release builds, and only allow builds from the server's build drop to be promoted to UAT/staging/production/whatever.

The fact of the matter is, if your build is broken for more than about 15 minutes at a time (and that includes failing tests), then you aren't doing continuous integration.

The "nuclear option" is to have your source control server refuse commits/checkins from any user other than the one who broke the build. Obviously an admin needs to be able to override this temporarily if said person goes on holiday - but, if everybody knows that the whole team is screwed until they fix their tests, then they'll resolve it damn quick.

A good policy (which is even better when it's automated) is to revert the source to the last known stable commit after 15 minutes of the build failing. In other words, if you can't fix it, or don't know what caused the build or test to break, then revert it and work locally until it's resolved - never ever make other developers twiddle their thumbs while you grind away at a problem they don't care about.

P.S. If you already have a lot of tests failing, you can use a "trailing threshold" in CI. Set it up so that the build only fails if there are more test failures than last time. This, along with a coverage rule, will force developers to eventually improve the test situation if they want to be able to keep working.

P.P.S. I realize this might seem draconian to some, but it's all down your culture. If you get to a point where people just don't leave the build broken or tests failing (my team almost never does, although I occasionally have to remind them), then you don't need to continue with the strictest set of rules. Although IMO you should always fail the build on a broken unit test. Integration/browser tests can fail sometimes.


问:
Which specific practices could be called "software craftsmanship" rather than "software engineering"?
Although not a new idea there seems to have been a big increase in the interest in software craftsmanship over the last couple of years (notably the often recommended book Clean Code's full title is Clean Code: A Handbook of Agile Software Craftsmanship).

Personally I see software craftsmanship as good software engineering with an added interest in ensuring that the end result is a joy to work with (both as an end user and as someone maintaining that software) - and also that its focus is more at the coding level of things than the higher level process things.

To draw an analogy - there were lots of buildings constructed in the 50s and 60s in a very modern style which took very little account of the people who would be living in them or how those buildings would age over time. Many of those buildings rapidly developed into slums or have been demolished long before their expected lifespans. I'm sure most developers with a few years under their belts will have experienced similar codebases.

What are the specific things that a software craftsman might do that a software engineer (possibly a bad one) might not?

答:
Personally I see software craftsmanship as good software engineering with an added interest in ensuring that the end result is a joy to work with (both as an end user and as someone maintaining that software) - and also that its focus is more at the coding level of things than the higher level process things.

As a professor of mine said once (paraphrased): "As a software engineer, it's not just your job to deliver software. It's your job to deliver software that makes your customers happy."

What are the specific things that a software craftsman might do that a software engineer (possibly a bad one) might not?

Nothing - an engineer is a craftsman...but more. Engineering builds on craftmanship.

As a craftsman and an engineer, you are skilled individuals, through some combination of education and experience. You follow established procedures. You are also pragmatic and realize what is broken and needs to be better.

However, an engineer adds concerns of economics, theory, and science on top of that. You are concerned with getting the most benefit for the least cost. You want to apply theories from psychology, sociology, management, human-computer interactions, and computer science to solve your problems (both interpersonal and technical). And you definitely have an education to back up your experiences.