答:
This sounds much like the original C language. (Plus a whole bunch of other languages from the period.).

You had to define variables functions etc. before you could reference them. "before" meaning strictly "in a previous line of source".

This is why you see the "main()" function at the back of most C programs and not at the front where it logically belongs.

The language designers did not think this was a great idea! They did this to save the compiler making two passes through the source code, and, so compile programs in a reasonable time on the hardware available.

And no its not really a good idea -- it just annoys programmers that they have to define stuff where they would rather not in order to satisfy some picky syntax.

Title: What negative consequences can arise from this language design rule?

Body:
Clarification: the rule is meant to prevent accessing variables that are not declared yet.

Clarification 2: the rule mandates that the compiler follows calls to functions which are defined in the same scope as the call and happen before the actual definition (forward referencing)  - making the compiler much alike an interpreter.

I'm thinking about a fictional programming language that behaves similar to JavaScript when declaring functions: that is, when using the function keyword to create named functions, they get "hoisted" to the top of the scope and can be used anywhere where their name is visible.

For example, the following is legal:

```<code>f();
function f() { console.log("f called") };
</code>```

However, there is a potential problem: what if the function f uses a variable x, that is defined after the call, like here:

```<code>f();
var x = 1;
function f() { console.log(x); }
</code>```

In case of JavaScript, this is also legal, because variables are hoisted as well - the program gets essentially transformed into something like this:

```<code>var x;
function f() { console.log(x); }

f();
x = 1;
</code>```

And therefore just prints undefined.

In my fictional language, variables wouldn't get hoisted, which means that the example before would produce an error. The rule concerns how this error is generated:

Functions are visible for the entire block in which they are defined,
  but it is illegal to call a function that accesses a variable declared
  after the call.

This means that each time the compiler for this language would encounter a function call, it would have to check if the function is defined in the current scope, and if it is, check if it accesses variables in the current scope that are declared after the call.

The reason for this rule is that it makes no sense to access variables before they are declared. Hoisting the variables to the top of their scopes like JavaScript does is a hack that only leaves room for error! This is why I believe it must not be done, but such situations should be detected and treated as errors (because they are, you're referencing something that doesn't chronologically exist yet).

I'm looking for reasons why this is a bad rule, i.e. results in complications or inconsistencies.

The reason I suspect that the rule is a bad one is that it does not exist in the Scala language. Scala solved this problem with a much more general rule:

The scope of a name introduced by a declaration or definition is the
  whole statement sequence containing the binding. However, there is a
  restriction on forward references in blocks: In a statement sequence
  s[1]...s[n] making up a block, if a simple name in s[i] refers to
  an entity defined by s[j] where j >= i, then for all s[k]
  between and including s[i] and s[j],

s[k] cannot be a variable definition.

If s[k] is a value definition, it must be lazy.

UPDATE:

For the time being I have adopted Scala's approach.

This approach is a more general version of my rule: it will catch all illegal accesses, but also some that are not - this is a tradeoff that I'm willing to make since I think that my rule may be too complicated or even impossible to implement.

Here's the rephrased/explained rule from Scala:

Variables cannot be forward-referenced, but lazy values, functions defined with def (which are just syntax sugar for lambdas assigned to (lazy) values, might even remove them as Doval suggested), classes, and modules can.

The restriction is that between the reference and the declaration (inclusive), there must be no variable definitions, because they might be altered by the entity being referenced before they are introduced to the program.


问:
Can the author of code licensed under CC-NC-ND use it in commercial closed-source software?
I am working on project on which I need to open-source part of my code in order to simplify extension by the enduser.

What I want, is to make an npm module, that will expose part of my code, so my users can build extensions for the product (in JavaScript), but I want a guarantee that this code will not be used for commercial or other development work, beside extensions for my product.

I found Creative Commons Attribution NonCommercial NoDerivs license to be a fit.

My problem: Can I, as the author of this code, use it in a commercial closed-source application?

Disclaimer: I know this is kind of a legal question, but please, state what you think, no one is holding you accountable/liable for it. Thanks.

答: Besides what has been written so far, I think it is important to add that CC licenses are non exclusive, as most other open source licenses. As hinted by Peteris, this means that as the copyright holder you can license your work under a CC license and some other commercial license of your choice (as long as that one isn't exclusive either). This is in fact a pretty common practice known as multi-licensing.

ContentLicense: CC BY-SA 3.0


问:
Universal means of describing what functions a library should expose
I am busy with a hobby OS and I am planning on making the project open-source and eventually have support for multiple platforms. With this in mind I have taken the approach of putting all hardware specific code in a separate Hardware Abstraction Layer (HAL) library so that the kernel does not need to know how the specific hardware handles things such as memory and interrupts. The kernel will just call the HAL function asking for some memory or to hook an interrupt by calling hal_memory_malloc(...); and hal_interrupts_hook(...); respectively.

My question is, I would like to know if there are any universal means of describing what functions the library has to expose if a developer wants to port the HAL to another platform. Seeing the Kernel knows the name of the function because it's in the kernel's header files the library just needs to have a function with that specific name in it. As the kernel I don't care how your function works as long as its there and I can call it.

Edit
My kernel and library is written in C so the library will be a normal statically linked libray

At the moment I have a Word Document that has a diagram showing the different functions but this is going to become a mess soon.

Any advice would be greatly appreciated.

答:
Define it with C header file containing all the prototypes declared extern. Documented with comments in the file itself using doxygen or similar format. That way the compiler will check that the functions have correct signatures when building the library. Doxygen is fully suitable for writing complete documentation and being a text format it is easily versionable, which word or similar binary document formats are not.

But there is not much reason to make it a library anyway. You certainly do want to separate what has to be implemented for each platform and what is generic. But on each platform you only need one HAL and since you still have to compile the generic part for each platform separately (because the object form is not generic), you can just compile it all together.

Besides there are things where you probably should define as C or preprocessor definitions in the platform dependent header included by the generic part for performance reasons, so just a library won't do. While general rule is to not bother with micro-optimizations, some things in kernel like locks (with disabling interrupts in some cases) and atomic operations (for reference counting and other lockless concurrent operations) really need to be inlined.


问:
Should utility base classes be avoided
Knowing that C# doesn't support multiple inheritance, is it considered bad form to write a utility base class?

Some initial thoughts:

I could create an interface and a concretion, but then the implementation isn't portable

Should the developer need to extend the class in say, a decorator pattern, they could implement this new class and inherit the base class in their new class

EDIT:

N.B. I'm not talking about vanilla inheritance here e.g. poodle<--dog<--mammal<--animal

More this sort of thing (lifted from here):

```<code>    using log4net;
    using log4net.Config;

    public class LogTest2
    {
        private static readonly ILog logger =
              LogManager.GetLogger(typeof(LogTest2));

    static LogTest2()
    {
        DOMConfigurator.Configure();
    }

    static void Main(string[] args)
    {
        logger.Debug("Here is a debug log.");
        logger.Info("... and an Info log.");
        logger.Warn("... and a warning.");
        logger.Error("... and an error.");
        logger.Fatal("... and a fatal error.");
    }
}
</code>```

If I were to drop this into say, a WCF service, it would be expedient for the private member variable, constructor and perhaps some wrapper methods to sit in a base class to save cluttering up the service code (and make it reusable).

So far, so dull.

However:

What if I wanted to add some other sort of logging not supported by log4net? E.g. Acme Corp provide some class to iMessage the support team if an issue occurs.

Base class

Had I implemented the log4net stuff in a base class, I'd then have to create some new master base class that supports both classes and inherit this.

Interface

I could implement an interface but the concretion would still be in the service code which we're trying to avoid. Acme Corp's class can of course now drop straight in but we're implementing two sets of code which do very similar things in different ways.

答: I think you are on the road to a very often seen form of wrong use of inheritance. If you want a class X which uses an exchangeable type of logger, inject an object of type ILog by passing it as a constructor parameter. If your logger needs specific initialization, create a specific logger, inherited from ILog. Don't bury the logger initialization in some kind of artifical base class A of X, in attempt to make this reusable. The latter would actually work against reusability (and testability) of X, and also against the reusability of your specific logger outside of the context of X.

Title: Should utility base classes be avoided


问:
How often should a Scrum team meet its Sprint commitment?
Commitment is a promise, and we all have been taught that you need to keep your promises.
But is it realistic to keep the commitment for each Sprint? Sometimes people get sick, sometimes the technical approach is proven wrong and you have to rethink everything, sometimes during further discussions with the product owner or the users you understand that the feature should be very different from what was originally thought.

I know that the official Scrum Guide now uses the word "forecast" rather than commitment, probably to address these problems.

So my question is how often do teams in your organizations keep their commitment and whether you like this approach or you want to change it.

Thank you.

答:
It's not so much a question of how often a team should "keep its promises".

It's more a question of investigating why a team would have a problem meeting its commitments.

If it's some godly intervention, that doesn't really matter. But if you find that you frequently need to return to the drawing board, because your technical approach is plain wrong, or that the PO keeps changing his/her mind, or that stories are not clear enough at the start of a sprint, then you need to investigate why.

Not meeting a sprint commitment is a symptom; you need to be interested in the root cause.


问:
Does designing a method that changes the argument's (if was object) values a good practice?
The premise is using a language (e.g. C#, javascript) which passes an object by reference into a method.

Assume there is an object "Player" which has a property "Level" and there is a method takes Player as parameter and its function is to increase the player's level by 1.

The method can be designed something like (c# syntax):

```<code>void AddLevelBy1(Player player)
{
 player.Level +=1;
}
</code>```

The concern was this method changed the value of the argument and I could not find a generic way to indicate (or may prevent?) this.

One might get some hints from the method name "AddLevelBy1". But such a way is not reliable and if the method was name "foo" then it becomes even more ambiguous.

So is there a solution / convention for this case (indicate whether arguments get changed)? Or such method design was considered a bad practice?

Added:

Try to describe my case more clearly:

I have an object "Player" which was not defined by myself (cannot change).

I wrote a method (AddLevelBy1() in this example) which takes "Player" as parameter (I know what happened).

I also pass this "Player" to some other methods (e.g. foo()) which were not written by me (so this is no way to know whether the "Player" got changed).

Thanks for some answers below but what if the codes were designed in the manner I described above.

I have added a demo of the case I described: http://jsfiddle.net/54sun/srhHt/9/

答:
If you have method like that, then such method should actually be part of Player class. This then clearly indicates the method might change the state of the object.

```<code>class Player
{
    void AddLevelBy1()
    {
        this.level += 1;
    }
}

player.AddLevelBy1()
</code>```

The problems start when you have more than 1 objects being changed, but there is no general solution to that.

If using c#, the "out" keyword can be used to indicate the change.

This is wrong. out keyword is to indicate something completely else. See more here: https://stackoverflow.com/questions/9875333/c-sharp-passing-reference-type-directly-vs-out-parameter

Body:
If you have method like that, then such method should actually be part of Player class. This then clearly indicates the method might change the state of the object.

class Player
{
    void AddLevelBy1()
    {
        this.level += 1;
    }
}

player.AddLevelBy1()

The problems start when you have more than 1 objects being changed, but there is no general solution to that.

If using c#, the "out" keyword can be used to indicate the change.

This is wrong. out keyword is to indicate something completely else. See more here: https://stackoverflow.com/questions/9875333/c-sharp-passing-reference-type-directly-vs-out-parameter


问:
Can a system be 100% Data Driven?
My new boss has been working on this project for many years.  I've only been here a few weeks, but I am not sure it's possible.  He would like to design a system that is "100% data driven".

So if we put in enough data, we can define and generate any application.  I've managed to at least get him to concede some things like users, or apps should have predefined values, but he likes the concept of the structure of the system, the user interface and the logic all being stored as data.

There are some demos of simple things and he's basically rediscovered some simple ideas of object oriented programming and your basic template systems, but I think overall that this goal might be actually impossible.

I don't know how you can define logic using data without the system becoming so complex that you are doing actual programming anyway.

I think theoretically it isn't because the thing that interprets the data ends up needing to become turing complete to describe the application so you've just shifted the problem one level higher to no net benefit.

Is such a 100% Data Driven Application possible?

答:
You mean your boss wants you to write this:

```<code>[
  {
    "statement": "Assignment ",
    "variable": "App",
    "value": {
      "type": "Function",
      "arguments": [],
      "function-body": [
        {}
      ]
    }
  },
  {
    "statement": "Assignment",
    "variable": "App.prototype.action",
    "value": {
      "type": "Function",
      "arguments": [
        "data"
      ],
      "function-body": [
        {
          "statement": "Call",
          "function-name": "console.log",
          "arguments": [
            "data"
          ]
        }
      ]
    }
  }
]
</code>```

To generate this:

```<code>var App = function () {};
App.prototype.action = function ( data ) {
    console.log( data );
}
</code>```

First one is JSON and the second one is JavaScript.

Clearification

I think theoretically it isn't because the thing that interprets the data ends up needing to become turing complete to describe the application so you've just shifted the problem one level higher to no net benefit.

Is such a 100% Data Driven Application possible?

This is where I just started. With my answer I'm trying to agree with the original post that: It is possible, but you're correct, it will just shift the problem one level higher for no [obvious] benefit.

Title: Can a system be 100% Data Driven?

Body:
You mean your boss wants you to write this:

[
  {
    "statement": "Assignment ",
    "variable": "App",
    "value": {
      "type": "Function",
      "arguments": [],
      "function-body": [
        {}
      ]
    }
  },
  {
    "statement": "Assignment",
    "variable": "App.prototype.action",
    "value": {
      "type": "Function",
      "arguments": [
        "data"
      ],
      "function-body": [
        {
          "statement": "Call",
          "function-name": "console.log",
          "arguments": [
            "data"
          ]
        }
      ]
    }
  }
]

To generate this:

var App = function () {};
App.prototype.action = function ( data ) {
    console.log( data );
}

First one is JSON and the second one is JavaScript.

Clearification

I think theoretically it isn't because the thing that interprets the data ends up needing to become turing complete to describe the application so you've just shifted the problem one level higher to no net benefit.

Is such a 100% Data Driven Application possible?

This is where I just started. With my answer I'm trying to agree with the original post that: It is possible, but you're correct, it will just shift the problem one level higher for no [obvious] benefit.


问:
Will using multiple recordsets in one database request be more efficient?
I am redeveloping an old ecommerce website which is currently written in C# ASP.NET 2.0.

Because this is a reasonably high volume website and has suffered performance issues I want to develop in the most efficient manner possible.

To minimise database trips (using SQL Server 2012), as database performance is the usual bottleneck in the current system, I am looking at creating stored procedures that return everything required for the current page in one query as multiple recordsets.

For example the home page query might return the promotional banner image filenames and text, the new release products, the top selling products, etc. The product page might return the product details, related products, etc.

I can't remember seeing this technique used often if at all. Is returning all data in a single database request more efficient than retrieving the same data in several database requests? Are there any flaws in doing this?

答:
Yes if:

there are lots of queries per page (latency will be reduced)

your web site and database are on different machines (network latency will be reduced)

No (not much) if:

there are not many queries per page

the web site and database are on the same server

So basically it will make it more efficient only if latency is significant.


问:
What could be used to get data from server to android as fast as it reaches server?
What is the best way to get data from server as fast as it gets to it? (Like instant message, or simple broadcast for example).

I first thought about using miniature web server in android and get post requests to it with data. However with this approach I soon understood that I will get many problems with NAT and similar issues.

Later I thought about manually pooling the server from android, but it seems somewhat flaky approach to problem, because data is got in irregular intervals (like image with some text).

I was thinking about using something like webrtc or rtp to have connection between server, but these approaches are somewhat complex and half baked. I found very little info on those about data operation. Thought I managed to get in my „experiments“ video and sound transfer, I found very little info how to get data transfers.

What should I do? Now I am thinking about having some connection to server and getting some events in android, which when I got update in server could download everything from server.

Update:

My data is encode64 processed html5 canvas png image. Probably I will add to it some text data to blob. It is generated on webpage it should reach phone as fast as it can through server. The problem is part where image data goes from server to phone. Data size per request is ~50KB.

答: I'm not quite sure about the scenario you are trying to describe but would a pub sub model help? Publish messages to a topic and have anyone who is interested in that information subscribe to the same topic. MQTT is a light weight pub / sub messaging protocol that only has 2 bytes of header and so is quick. There are several clients and servers available, some that are open source or free to use e.g. Eclipse Paho client and the Mosquito server. </p>


答:
Although your example is simplistic, and may be modeled differently (like @Euphoric suggested, or by using extension methods if the class is not in your code-base), there are a lot of use-cases where it is legitimate for a method to change the state of their parameters.

For example, builder processes, your recursive algorithms, like DFS detecting cycles.

You can use the Law of Demeter as a rule of thumb of what should a method do and not do:

You can play with yourself.

You can play with your own toys (but you can’t take them apart),

You can play with toys that were given to you.

And you can play with toys you’ve made yourself.

Of course, when a method has side-effects, it should be declared in its name: IncrementPlayerLevel(Player player) plainly states that it is going to change the level of the player...

On the other side of the design considerations, sometimes it is critical that methods do not change the state. For example - implementing an Actor model for parallel computations. When considering this, you are better off designing your state objects as immutable, so you don't need to ask yourself whether any method has changed your objects without you being aware of it.

Title: Does designing a method that changes the argument's (if was object) values a good practice?

Body:
The premise is using a language (e.g. C#, javascript) which passes an object by reference into a method.

Assume there is an object "Player" which has a property "Level" and there is a method takes Player as parameter and its function is to increase the player's level by 1.

The method can be designed something like (c# syntax):

```<code>void AddLevelBy1(Player player)
{
 player.Level +=1;
}
</code>```

The concern was this method changed the value of the argument and I could not find a generic way to indicate (or may prevent?) this.

One might get some hints from the method name "AddLevelBy1". But such a way is not reliable and if the method was name "foo" then it becomes even more ambiguous.

So is there a solution / convention for this case (indicate whether arguments get changed)? Or such method design was considered a bad practice?

Added:

Try to describe my case more clearly:

I have an object "Player" which was not defined by myself (cannot change).

I wrote a method (AddLevelBy1() in this example) which takes "Player" as parameter (I know what happened).

I also pass this "Player" to some other methods (e.g. foo()) which were not written by me (so this is no way to know whether the "Player" got changed).

Thanks for some answers below but what if the codes were designed in the manner I described above.

I have added a demo of the case I described: http://jsfiddle.net/54sun/srhHt/9/


问:
What is the difference between Repository Pattern and Facades Pattern?
I've always used the repository pattern in my applications. But I have seen that many people use facades instead of the repository for naming convention, but the operation is the same, I Think. Why is there this difference? There are a real difference between them or not?</p>

答:
A facade is more general than a repository.

A facade can apply to anything that is not persistence based, whereas a repository is supposed to encapsulate access to an underlying source and make it look like an in memory data source.

Facades are for creating a simple interface for some other, complicated interface.


答:
If all is well, then it will be normal for the teams to be meeting their scrum commitments. They should be be running cool enough to cope with small scale, reasonable and likely disruptions such as a days illness, child care emergencies etc... without it immediately and automatically triggering a failure to deliver its sprint commitment.  If it can't then in my view the sprints are over committing and are running too hot for their long term good as a team.

If sprints are consistently failing to deliver, then scrum has delivered on its promise, to make 'problems' visible.  Problems may include not having properly defined tasks, insufficient experience in the team, or a management culture of continually attempting to over deliver - and so constantly falling short.

Either way, the solution is to identify the root cause, and fix it, rather than whipping the developers harder.

Teams that are always 'close' to meeting their commitments are failing in a more serious way.  You can be sure that they are not performing enough testing.

Title: How often should a Scrum team meet its Sprint commitment?

Body:
Commitment is a promise, and we all have been taught that you need to keep your promises.
But is it realistic to keep the commitment for each Sprint? Sometimes people get sick, sometimes the technical approach is proven wrong and you have to rethink everything, sometimes during further discussions with the product owner or the users you understand that the feature should be very different from what was originally thought.

I know that the official Scrum Guide now uses the word "forecast" rather than commitment, probably to address these problems.

So my question is how often do teams in your organizations keep their commitment and whether you like this approach or you want to change it.

Thank you.


问:
Understanding "programming to an interface"
I have come across the term "programming to an interface instead of an implementation" a lot, and I think I kind of understand what it means. But I want to make sure I understand it's benefits and it's possible implementations.

"Programming to an interface" means, that when possible, one should refer to a more abstract level of a class (an interface, abstract class, or sometimes a superclass of some sort), instead of refering to a concrete implementation.

A common example in Java, is to use:

List myList = new ArrayList(); instead of ArrayList myList = new ArrayList(); .

I have two questions regarding this:

I want to make sure I understand the main benefits of this approach. I think the benefits are mostly flexibility. Declaring an object as a more high-level reference, rather than a concrete implementation, allows for more flexibility and maintainablity throughout the development cycle and throughout the code. Is this correct? Is flexibility the main benefit?

Are there more ways of 'programming to an interface'? Or is "declaring a variable as an interface rather than a concrete implementation" the the only implementation of this concept?

I'm not talking about the Java construct Interface. I'm talking about the OO principle "programming to an interface, not an implementation". In this principle, the world "interface" refers to any "supertype" of a class - an interface, an abstract class, or a simple superclass which is more abstract and less concrete than it's more concrete subclasses.

答:
There are perhaps two usages of the word interface being used here. The interface you are mainly referring to in your question is a Java Interface. That is specifically a Java concept, more generally it's a programming language interface.

I would say that programming to an interface is a broader concept. The now popular REST APIs that are available for many websites are another example of the broader concept of programming to an interface at a higher level. By creating a layer in between your code's inner workings and the outside world (people on the internet, other programs, even other parts of the same program) you can change anything inside your code as long as you don't change what the outside world is expecting, where that is defined by an interface, or contract that you intend to honour.

That does then provide you the flexibility to refactor your internal code while not having to tell all the other things that depend on its interface.

It also means that your code should be more stable. By sticking to the interface then you shouldn't break other people's code. When you really have to change the interface then you can release a new major version (1.a.b.c to 2.x.y.z ) of the API which signals that there are breaking changes in the interface of the new version.

As @Doval points out in the comments on this answer there is also locality of errors. These I think all boil down to encapsulation. Just as you would use it for objects in an Object Oriented design, so this concept is also useful at a higher level.


答:
I can only talk about my personal experience, as this has never been formally taught to me either.

Your first point is correct.  The gained flexibility comes from not being able to accidentally invoke implementation details of the concrete class where they shouldn't be invoked.

For example, consider an ILogger interface which is currently implemented as a concrete LogToEmailLogger class.  The LogToEmailLogger class exposes all the ILogger methods and properties, but also happens to have an implementation-specific property sysAdminEmail.

When your logger is used in your application, it shouldn't be the concern of the consuming code to set the sysAdminEmail.  This property should be set during the logger setup and should the be concealed from the world.

If you were coding against the concrete implementation, then you might accidentally set the implementation property when using the logger.  Now, your application code is tightly coupled to your logger, and switching to another logger will require first decoupling your code from the original one.

In this sense, coding to an interface loosens coupling.

Regarding your second point:  Another reason I have seen for coding to an interface is to reduce the complexity of code.

For example, imagine I have a game with the following interfaces I2DRenderable, I3DRenderable, IUpdateable.  It is not uncommon for a single game components to have both 2D and 3D renderable content.  Other components may be only 2D and others only 3D.

If 2D rendering is done by one module, then it makes sense for it to maintain a collection of I2DRenderables.  It doesn't matter if the objects in its collection are also I3DRenderable or IUpdateble as other modules will be responsible for treating those aspects of the objects.

Storing the renderable objects as a list of I2DRenderable keeps the complexity of the rendering class low.  3D Rendering and Update logic is none of its concern and so those aspects of its children objects can and should be ignored.

In this sense, coding to an interface keeps complexity low by isolating concerns.

Title: Understanding "programming to an interface"

Body:
I have come across the term "programming to an interface instead of an implementation" a lot, and I think I kind of understand what it means. But I want to make sure I understand it's benefits and it's possible implementations.

"Programming to an interface" means, that when possible, one should refer to a more abstract level of a class (an interface, abstract class, or sometimes a superclass of some sort), instead of refering to a concrete implementation.

A common example in Java, is to use:

List myList = new ArrayList(); instead of ArrayList myList = new ArrayList(); .

I have two questions regarding this:

I want to make sure I understand the main benefits of this approach. I think the benefits are mostly flexibility. Declaring an object as a more high-level reference, rather than a concrete implementation, allows for more flexibility and maintainablity throughout the development cycle and throughout the code. Is this correct? Is flexibility the main benefit?

Are there more ways of 'programming to an interface'? Or is "declaring a variable as an interface rather than a concrete implementation" the the only implementation of this concept?

I'm not talking about the Java construct Interface. I'm talking about the OO principle "programming to an interface, not an implementation". In this principle, the world "interface" refers to any "supertype" of a class - an interface, an abstract class, or a simple superclass which is more abstract and less concrete than it's more concrete subclasses.


答:
"Programming to an interface" means, that when possible, one should refer to a more abstract level of a class (an interface, abstract class, or sometimes a superclass of some sort), instead of refering to a concrete implementation.

This is not correct. Or at least, it is not entirely correct.

The more important point comes from a program design perspective. Here, "programming to an interface" means focusing your design on what the code is doing, not how it does it. This is a vital distinction that pushes your design towards correctness and flexibility.

The main idea is that domains change far slower than software does. Say you have software to keep track of your grocery list. In the 80's, this software would work against a command line and some flat files on floppy disk. Then you got a UI. Then you maybe put the list in the database. Later on it maybe moved to the cloud or mobile phones or facebook integration.

If you designed your code specifically around the implementation (floppy disks and command lines) you would be ill-prepared for changes. If you designed your code around the interface (manipulating a grocery list) then the implementation is free to change.


答:
As mentioned in Uri's answer, ideally your types would be immutable. Mutability complicates programs. But mainstream languages have poor support for immutability, and we have a long history of mutation which goes all the way back to the assembly days, so there's no getting around dealing with mutability sometimes. Sometimes mutating an argument is unavoidable - for example, if the class is not under your control, and it provides no way of cloning (i.e. deep copying) its values. So, it may not be a best practice, but sometimes you can't get around it.

Some have suggested making the mutator a method of the class. Even if the class is under your control, this doesn't necessarily make sense - there's an infinite number of things you might want to do with your mutable class, and thus an infinite number of functions that may need to mutate it. Secondly, not everything is a method. If you have a commutative operation, there is no "recipient" for the function; either argument is equally valid. If you have a function that operates on arguments of two different types, why should the function belong to one class or the other? Sometimes this makes no sense. If you don't need access to the class's private members, it doesn't make sense to make the function a method.

Ok, so you need to mutate the argument. What can you do to mitigate the potential damage? As you pointed out, it's critical that the function name unambiguously informs you that that's going to happen. Secondly, you should avoid creating functions that are accessors and mutators at the same time. If a function's purpose is to return some information about an object, people are going to be surprised if it also mutates that object or any other.

Uri brings up the Law of Demeter, which is an excellent guideline, but be warned that it's relevant only to abstractions. The idea is that an abstraction should hide its implementation, so chains like foo.bar.baz() are usually a sign that you're not doing a very good job there. But not everything is an abstraction! Some types (e.g. tuples, records) are simply data containers, and accessing their members is not a violation of the law, even if the end result is still a dotted chain. (Of course, if your abstraction shouldn't be exposing that tuple in the first place, it's still a problem.)


问:
What are the hardest parts of the C++/C#/Java programming languages?
Just wondered what are the features of the three main programming languages which show you are an 'expert'? Please exclude 'practical' skills such as indenting.

Am I right in saying for C++ the most difficult aspect to master is STL/generics? Java seems much easier as memory is handled for you. I'm not entirely sure on C# either?

I'm trying to use this to guage my current level of ability and what i wish to aim for.

ps this was posted on stackoverflow but got binned due to arguing, please do try to keep it civil as I am really interested in the answers from everyone :)

答:
The Programmer Competency Matrix can be a good way to gauge your skill level and goals in a language-agnostic way.

You can then make it language-specific by asking yourself if you can reliably do thing X in a given language.

OwnerDisplayName: tom

ContentLicense: CC BY-SA 2.5


问:
How to prevent the vicious circle of testing via customer
I recently asked this question and this comment and made me ponder the whole process of releasing an update to the customers. The next update for our software is planned and the previous time it went horribly wrong because of regression, bad testing, etc...

This time we want to prevent the scenario that we test via our customer and made some unit tests and other minor improvements.
However, there is not enough time to make unit tests for all the features that lack unit tests or the features that need to be build yet.
So the answer for this question 'Make more unit tests' is not fitting because of the lack of time, infrastructure etc...

Every bug and feature will be tested/reviewed by a different developer, but that won't be done perfectly of course (we're still human :)).

My question is: Once we released the update, how do we prevent the vicious circle of testing via customers while not be able to add more unit tests?

The previous time we tried our best to test the software before and after release. After the deadline we were still searching and fixing bugs but the customer would also find some of these. So we post an update as soon as we were confident that the patch was increasing quality. We were so busy with finding bugs and fixing them that we weren't spending any time on creating unit tests.

This time we don't have a solid plan yet, hence the question. As stated before we did added some unit tests, but surely not enough. We are also looking for new colleagues but they are not easy to come by and management has rather high standards. We do have quite some candidates and it looks like we do get at least one new colleagues very soon, but it still takes time to get him/her up and running. The first thing we put the new colleague on will be creating unit tests. So the dependencies there are experience, skills and the time he/she can join the time.

Another problem that comes in hand with the lack of developers is that we are so focused on getting the bugs and features fixed that we don't have much time to spend on thinking about 'how we can improve the update process'. (I ask these questions in my own spare time).

Summary of steps I will try to take:

Try to get a tester before the release is done

Add unit tests while creating the features, if there isn't enough time, schedule them for after the release.

After releasing, if there is any regression, create unit tests when fixing the bugs.

Release more often in smaller chunks after the release, making it easier to release features and repair bugs with a minor priority.

答:
Pain Reduction

One approach that can work and hasn't yet been mentioned here is to lower the cost of failure. One contributing factor to the magnitude of the disaster of your last release is the pain caused to the customer. If you make it trivial to roll back a release version - hopefully in a self-serving manner so customers really are minimally inconvenienced, then you can release with more confidence that your software release won't ruin anyone's day.

Now, this obviously adds more complexity to your product, costing its own amount of time and budget to implement and introducing another channel for bugs. Especially if your app is responsible for managing large amounts of customer data, this could be more trouble than it is worth. (How to tell? If you rely on a file system store with no watching or auto-load hooks, you're probably safe. If you install a database on a client's machine, you need to be very cautious.)

However, if you have a simple desktop application, there are plenty of ways to make version swapping painless. You could also take the precaution of forcing customers to backup their data before updating. Or if part of your new features include a new file format, you could auto-convert files on first load and disallow the user from overwriting their previous version files.

This approach is even more practical if you host your application on the web. In that case, a browser is essentially downloading and re-installing your software for your every time the customer loads a page.

Testing Priority

The other way to quickly build out your test suite with high-priority tests is to require every bug fix to include a test that fails if the bug is not fixed and passes when it does. Cbojar mentioned this in their answer, but I wanted to expound upon the many reasons this is a good idea.

This approach is often popular with management, because it doesn't require an up-front block of test writing and it addresses your customers' problems in real time. So when a customer runs into a bug and complains loudly, you get to say "Yes, we've just fixed that bug for you. And we're confident it will never happen again." And that's an extra incentive to writing the test and writing it thoroughly and well, because you know a customer is depending on it.


答:
My understanding of "programming to an interface" is different than what the question or the other answers suggest. Which is not to say that my understanding is correct, or that the things in the other answers aren't good ideas, just that they're not what I think of when I hear that term.

Programming to an interface means that when you are presented with some programming interface (be it a class library, a set of functions, a network protocol or anything else) that you keep to using only things guaranteed by the interface. You may have knowledge about the underlying implementation (you may have written it), but you should not ever use that knowledge.

For example, say the API presents you with some opaque value which is a "handle" to something internal. Your knowledge might tell you that this handle is really a pointer, and you could dereference it and access some value, which might allow you to easily accomplish some task you want to do. But the interface doesn't provide you with that option; it's your knowledge of the particular implementation that does.

The problem with this is that it creates a strong coupling between your code and the implementation, exactly what the interface was supposed to prevent. Depending on the politics it might either mean that the implementation can no longer be changed, because that would break your code, or that your code is very fragile and keeps breaking on every upgrade or change of the underlying implementation.

A big example of this is programs written for Windows. The WinAPI is an interface, but many people used tricks that worked because of the particular implementation in, say Windows 95. These tricks maybe made their programs faster, or allowed them to do things in less code than would have otherwise been necessary. But these tricks also meant that the program would crash on Windows 2000, because the API was implemented differently there. If the program was important enough, Microsoft might actually go ahead and add some hack to their implementation so the the program would continue to work, but the cost of that is increased complexity (with all the ensuing problems) of the Windows code. It also makes life extra-hard for the Wine people, because they try to implement the WinAPI as well, but they can only refer to the documentation for how to do this, which leads to many programs not working as they should because they (accidentally or intentionally) rely on some implementation detail.


问:
Feature vs. Function
Often I hear PMs (Project Managers) talk about feature and function. And I'm just so puzzled to differentiate them. Sometimes I think of a feature to be equivalent to a user story. Something like "As a user, Bob should be able to see a list of his payments", and they call it a feature. Sometimes it gets as big as a subsystem, something like "the ability to send SMS via web application". Function on the other hand sometimes gets as small as a task, "implementing digit grouping for number inputs", while there are cases when it gets as big as a whole CRUD operation.

My question is, how can we differentiate feature from function?

答: I would agree that it is not worth obsessing over since the terms are often used interchangeably in some contexts. Yet in the broader management context I think there are some important points. First, PM can also mean product manager. Someone must take responsibility for deciding what the market will support in price, delivery date and features. I generally find that feature is preferred when you are in a marketing context. The project manager's role is to manage the project such that the desired product is delivered on time and within budget. To the architect and designers, the feature are given and can be thought of as delivered functions in the human organization offering data transformation and storage but must be reified until the design has been reduced to delegate-able units of work that can be assigned to developers. It is often the case that a feature does not cleanly map to a set of functions in the machine system. For example, fast and secure are features desired by consumers but cannot be segregated in the code. These emergent properties are what make non-functional requirements so difficult to satisfy. </p>

Title: Feature vs. Function


答:
Honestly, I don't think that you can really group those three languages together for such a question. Java and C# might be close enough to work together - though it wouldn't suprise me if some of C#'s more interesting features were more difficult and therefore more in the "expert" realm than the features that C# and Java have in common - but C++ is in a different league entirely. It just has too many things in it that do crazy stuff if you don't use them right. And some features - like templates - are just way more powerful and complicated in C++ than in Java or C#. I would rate very few features that these three languages have in common as being of "expert" level. In general, the stuff that makes you an expert at a language is the esoteric stuff that other languages don't necessarily have and which are more likely to trip you up.

Measuring your knowledge as a programmer without regard to programming language means measuring stuff more along the lines of algorithms and data structures. How well you understand design patterns and good software engineering principles matters far more in general than how you indent.

The types of skills that make you an expert programmer in general are not the same types of skills which make you an expert at a particular programming language. It's good to have both (and if you're not at least reasonably competent in the language that you use, your non-language specific knowledge doesn't do you much good), but you're talking about two very different things when you're talking about what makes someone an expert at a particular programming language and what makes them an expert programmer in general. And since even relatively similar languages such as C++, C#, and Java differ quite a bit in the details - especially the ones which would tend to qualify you as an expert in the language itself - trying to group them together when trying to determine what makes you an expert at them really doesn't work.

Title: What are the hardest parts of the C++/C#/Java programming languages?

Body:
Just wondered what are the features of the three main programming languages which show you are an 'expert'? Please exclude 'practical' skills such as indenting.

Am I right in saying for C++ the most difficult aspect to master is STL/generics? Java seems much easier as memory is handled for you. I'm not entirely sure on C# either?

I'm trying to use this to guage my current level of ability and what i wish to aim for.

ps this was posted on stackoverflow but got binned due to arguing, please do try to keep it civil as I am really interested in the answers from everyone :)


问:
Why are string resources generally kept external to the code and not inside the code?
Generally, on many platforms, I'm writing my string resources to a .resx or .xml file, and then I'm getting them using some platform-dependent approach.

That is, on iOS, I'm getting them via NSBundle.MainBundle, and by using Context.Resources on Android.

What are the advantages of this approach, and why not having it directly accessible in the code, so, for example:

In a cross-platform project, any platform can access it directly, with no integration.

There are no concerns during building about whether or not the resources built well.

The coder can use functionalities such as multilanguage handling

Long story short: what is the reason why string resources are structured that way?

[Edit]

Let's say that my file is part of a "core" project shared between other project. (Think about a PCL, cross-platform project file structure.)

And suppose that my file is just totally similar to a .resx/.xml file, looking like this (I'm not a pro in xml, sorry!):

  Parameters
  Paramètres

So, this is basically a custom xml, where you point to the key/language to get the proper string.

The file would be part of the application just like you add any accessible file inside an app, and the system to access the string resources, coded using PCL. Would this add an overhead to the applications?

答:
This is just the way that your language/platform has decided to implement localization of strings. All approaches to localization need some kind of external resource files to get the translations from. The main pain point is how you maintain these resources.

Looks like you need to maintain these resource files manually, which can be quite a burden. It also complicates the sharing of repeated strings. And having to do this when you're currently shipping only one language, is even more of a burden.

A common alternative is the GNU Gettext approach of just marking up the translatable strings in source code and automatically extracting these strings to standard PO files which work nicely cross-platform and cross-languages. From a developer perspective it beats the manual maintenance of XML resource files any day.


问:
How can Scrum be adapted to allow for support obligations?
Scrum's great for new development and proactive tasks. But I've never been sure how to use it when the department's obligations also include analyzing/answering/fixing customer support questions, which come in unpredictably, typically have high enough priority to interrupt what we planned on doing, and whose complexity ranges from trivial to major.

The books I've seen so far don't seem to cover that situation.

So how are other folks handling it?

答:
Support and Scrum should not be an issue in a sane, well managed environment.

Ideally, the product should be developed and tested and maintained well enough that bugs are normally caught before they are shipped to customers.  Likewise, the small percentage of bugs that do slip through should be documented, prioritised and added to the backlog to become part of the normal scrum process.

However, from time to time, there is bound to be a 'catastrophic' event that cannot be managed that way, and a crisis team is removed from the scrum sprint to address this issue, with the business accepting that scum commitments may slip as a consequence.

What should not happen though, is that there is such a volume of support requests at a high enough urgency that they continually disrupt the scrum sprint.  If this occurs, then the solutions may include improving testing and QA before shipping, better training for support to solve more support issues without referring everything to 'software' for an answer, or perhaps as a last resort people with developer skills on the support team to handle these support issues.


答:
If the development team is the same group that would be handling customer support, the first thing to do would be to adjust the amount of story points that the team brings into the sprint to account for the amount of time doing this. For example, if you were originally basing your story points on a 350 man-hour sprint (5 people over 2 weeks at 35 hours/week dedicated to the project), if you have people required to do customer support work, you may only have 270 man-hours in the sprint remaining. If, under the 350 man-hour sprint you had a velocity of 20 story points per sprint, I'd reduce your planned velocity to closer to 15-16. If a separate entity is handling customer support questions, then you don't need to worry about this as much.

Next, allow the bug reports and enhancement requests from customers to flow into the product backlog. The Product Owner would work with the customer support staff to understand the priority that the external customer is placing on the request and to organize it with the product vision. These stories generated from external entities would be managed just like any other story - they would be ordered by priority, estimated by the development team, and the appropriate number of internally and externally generated stories would be brought into the sprint.

In the event of a critical issue comes during a sprint, the team can take a small period of time to estimate it and work with the Product Owner to determine if it's feasible to address in the current sprint and what would have to be slipped from the current sprint to make it happen or if it would be the first story pulled into the next sprint. The team should consider maintaining sustainable development, product quality, and ensuring customer satisfaction when deciding what to do with a story, negotiating as necessary.

Title: How can Scrum be adapted to allow for support obligations?

Body:
Scrum's great for new development and proactive tasks. But I've never been sure how to use it when the department's obligations also include analyzing/answering/fixing customer support questions, which come in unpredictably, typically have high enough priority to interrupt what we planned on doing, and whose complexity ranges from trivial to major.

The books I've seen so far don't seem to cover that situation.

So how are other folks handling it?


答:
Most of the scrum teams where I work have these support obligations.  There are a couple different approaches they take to handle them.

One way is to just let it factor into your velocity as interruptions.  In other words, you might have a velocity of 20 points per iteration instead of 30 because of your support obligations.

One way is to create a buffer story called "Customer Support" and assign it an appropriate number of points for the amount of support you expect to give that iteration.  This method is a little better than the first if the amount of support varies over time.  For example, if you do a lot of support right after a major deployment, then expect hardly any for a year.

Some teams separate the initial triage from the actual fixing. We create a separate story for fixing an underlying cause that gets prioritized with the other stories, but finding workarounds and configuration problems gets taken care of immediately.


答:
I personally believe that if nobody in the organisation cares about meeting your commitment, you are not talking about a commitment. You need two partners to make a deal and to form a commitment.

A sprint commitment is something that you should be able to keep, taking into account all "normal variation". You can read my blog post on basics of agile planning if you want to know more about what I mean with basic variation. And as Stefan stated, not meeting your commitment is a symptom not the disease.

After every sprint you have a moment to inspect the actual velocity of that sprint and adapt your "average velocity" to that (like explained in the post mentioned above). If your velocity keeps going down, sprint after sprint, you start to see patterns that can help you detect the actual root cause of this. This could be too much unplanned work (e.g. small urgent tasks coming in, bugs in the code that you are working on, changes to the acceptance criteria during the sprint, ...). All of this data needs to be tracked, most probably by the scrum master to help her to figure out which patterns are in there. That will help the team to come up with actions during the retrospective.


问:
secure photos on server
I would like to hear advice from the more experienced developers. The project is now in the design stage. It's mobile application and a simple web application. Content is pictures, comments, personal correspondence.

Pictures can be quite personal. Need a very serious attitude to security.

The question is simple: where to store photos and how to secure it?

I think it's will be in the following way:

1. User make some photo. Via SSL the application sends photo to the server.

2. The server recieve photo, encrypt it and store somewhere.

Also, via app the user can see all own photos.

1. Request to server for photos.

2. Server decrypt stored photos and send via SSL to client.

I need some technical advices: where to save images, I know that database is quite slow for this case, which algorithms use for encrypt/decrypt, what about cache. It will be highload project and performance is very important.

Mobile application is planned on cross-platform framework like phoneGap, Titanium. On the server is .NET. But it is planned. I also consider full stack frameworks for javascript.

答:
where to save images

Like you realised, saving images onto a database isn't worthwhile for your purpose. The usual approach is to -

Save the uploaded image into any directory on the server.

And then save the path to the image in the database.

Since you are encrypting the images too, it shouldn't matter if somebody figures out where the images are on the server. (Ofcourse, you need to make sure your crypto keys are safe but that's another topic.)

Title: secure photos on server


答:
I believe the hardest part about the languages is not knowing the features but knowing when to use them. Take iterators in C# as an example:

```<code>IEnumerable<int> Ints()
{
    yield return 1;
    yield return 2;
    yield return 3;
}
</code>```

Well yeah that is a working example but is it an appropriate usage of the feature? I think not. The same really applies to the features of any language. I've been working with computational expressions in F# and I do understand them. I even know a few good examples of when to use them. The thing is I'm not yet skilled enough to apply them to a new problem.

Body:
I believe the hardest part about the languages is not knowing the features but knowing when to use them. Take iterators in C# as an example:

IEnumerable<int> Ints()
{
    yield return 1;
    yield return 2;
    yield return 3;
}

Well yeah that is a working example but is it an appropriate usage of the feature? I think not. The same really applies to the features of any language. I've been working with computational expressions in F# and I do understand them. I even know a few good examples of when to use them. The thing is I'm not yet skilled enough to apply them to a new problem.


答:
If you aren't meeting your commitment then you should reduce your velocity. If you are always meeting it, you should increase until you fail sometimes.

The issue is how badly do you fail? It should always be close. Either you make it with a little bit of slack or fail just by a little bit. That is a healthy goal for any discipline, running times, weight lifting, etc. Ideally the average amount of work done in a sprint should be a normal distribution around your velocity.

What's more important is the long-term trend in your velocity. If each week you add 15 story points to your velocity but only accomplish 10 more than you did the week before is that really a bad thing? At some places they consider this "stretch goals".


问:
Why is Web SQL database deprecated?
I am making a hybrid Android app.

At first I decided to use localStorage, after spending 2 days, I realized that it is very strange and so dropped it.

Then, I picked up indexedDB, after spending today's whole day and actually getting the output in Google Chrome, it is not running inside a WebView of the android app.

And I never used Web SQL database at all because it was deprecated. Anyhow, it has come to my notice that PhoneGap still uses Web SQL and android's browsers support it.

Why was Web SQL deprecated in the first place? And will it be a good idea for me to go with Web SQL now?

答:
Josh Kelley's answer is so far the BEST answer ever I've found about the reason of the standard work to be stopped.  That said, I think there is an additional perspective to consider regarding the user-base.

Eventhough, I disagree on Ido Green's approach to the subject ("This is a recommendation for web developers to no longer use the technology as effectively")...

I believe (as vi4m states in the comments of Ido Green's article):

We (developers) can still use this technology. No browser vendor requested removal of this technology, nor plan to remove it. Developers are the voice of the web. We can just still using it, maybe Mozilla will change mind ;-)

And I would add another logical approach: If you are developing for mobile ambient... ¿what ambients are in more hands? Answer: iOS and Android...
So if BOTH support webSQL, and your target is MASSIVE MOBILE, go for it!

Think as big apps have done almost always at the beggining, get the MOST first, then (once achieved success) recreate the work to get the remaining less (if you really want to achieve them or are asked to do so). Finally, ins't always success who marks the path?

After reading Nolan Lawson's article (in which is clear his intention to give a chance to his invention) I believe this matter became a new cold-war between tech-giants that shouldn't even exist.
I believe specs are made to stay (as -longer and untouched as possible- the better for client oriented performance). Ironically the "specs guys" job is to generate NEW specs (sometimes where there is none needed, so he can have something more to do), and likewise programmers jobs sometimes focus on changing and rewriting what already works instead of doing solutions for new problems and new tendencies.

For me, Client-Side Databases was a matter of simply making parallels (between server and client sides) so we could create, store, upload and download data easily. Under this approach, having the same languages and structures (at least for us, LAMP opensource developers) is straight forward and logic.

I believe IndexedDB intention for being an alternative with wider and newer possibilities is an always good approach, but somehow it resembles for me to the need of developing software that NEEDS to be installed (even when the core solution can stay on the cloud). In a world that tends to stay connected it sounds like A) a matter of control and possession or B) focusing on developing monsters for the client-side... but for those kind of needs exist Apps (in the Mobile world) and software (in the PC world).
I believe the goal of Webapps should stay mainly on extending the web no matter the device.

I believe a nice infographic could come out of this approach.

UPDATE (2021):

Nowadays, Mozilla (Firefox) and Apple (Safari) do NOT support the technology on any of their browsers.

All other full Browsers (not mini) do support it (Edge, Chrome, Opera, etc):

https://caniuse.com/sql-storage

For web client-side DB's, we still have indexedDB, which has nowadays even more support than WebAssembly (96% vs 92%). Native is double or triple job if you want to cover as many users as possible, unless you have a specific need that still can't be done with Web (fewer every year). I personally prefer the approach of Progressive WebApps, so I'm using IndexedDB.

Title: Why is Web SQL database deprecated?

ContentLicense: CC BY-SA 4.0


问:
How to manage multiple database credentials across multiple projects
We have 10 separate projects that all access the same database. Initially, all 10 projects had database credentials hardcoded into them. I decided to move the credentials into a utility method and have all of the projects call that instead. For example

```<code>public String getDBUser() {
   return "username";
}
</code>```

So instead of hardcoding it in 10 places, I hardcode it in one place. All was fine.

Fast-forward some months and I run into a wall with this solution, because now there are different credentials depending on which database server we're trying to connect to.

For context, I'm trying to set up properly separated testing/production environments, but the servers have different username and passwords.

One solution is to simply change the credentials to make them the same, but I imagine this is sometimes not an option and if I run into such a situation I would like to be prepared.

What is a good way to manage multiple database credentials across multiple applications?

答:
In .NET, for example, connection strings are stored in web.config, which is an XML file in the app's directory. There you can store as many connection strings as you need. Then, in your app, you just configure which of those you need (reading the file and extracting the connection string), you configure this parameter as you go.

This is for one project. For many projects, the .NET solution is to add every connection string in a "master file" and then, when the project is built, the building process will copy the relevant connection string from the "master file" to the project's web.config.

I quickly tried to find some Java equivalent but I was unsuccessful. In Java the equivalent is persistence.xml (thanks, Bob!), so an option would be to transform that file. It shouldn't be too hard to do, even if it means running an extra command every time you change something to the master file.

Something about having the exact same credentials rubs me the wrong way, but that would depend on your architecture. Also, just as an extra suggestion if you haven't done so, take your time to properly store sensitive information. You never know...


答:
In project I'm working currently on I had to solve same problem.

My solution is :

Store resources on HDD as files (HDD is made for this task so this is the best solution imho).

Store in database id's of resources with path's and additional 'meta data'.

To provide client (iPad in this case) with secured photos we are using Spring MVC with Basic Authentication and REST interface.

Basic auth over HTTPS satisfies authentication requirement. You can easily implement it with Spring. Spring also provides you with REST interface for HTTP requests. Files should be stored on hard disk. Additional meta data can be stored in database to provide fast searching (f.e upload date or upload user).

It can be easily implemented with tools I've mentioned. That's why I think it's good solution. There are also many content repositories which can be installed on server where webapp will be deployed. I considered using Jackrabbit but solution I've provdied satisfied our needs.

Title: secure photos on server

Body:
I would like to hear advice from the more experienced developers. The project is now in the design stage. It's mobile application and a simple web application. Content is pictures, comments, personal correspondence.

Pictures can be quite personal. Need a very serious attitude to security.

The question is simple: where to store photos and how to secure it?

I think it's will be in the following way:

1. User make some photo. Via SSL the application sends photo to the server.

2. The server recieve photo, encrypt it and store somewhere.

Also, via app the user can see all own photos.

1. Request to server for photos.

2. Server decrypt stored photos and send via SSL to client.

I need some technical advices: where to save images, I know that database is quite slow for this case, which algorithms use for encrypt/decrypt, what about cache. It will be highload project and performance is very important.

Mobile application is planned on cross-platform framework like phoneGap, Titanium. On the server is .NET. But it is planned. I also consider full stack frameworks for javascript.


答:
That won't be a long answer but maybe it helps.

How about storing it on Azure, AWS, Google or Manta. Then you encrypt the data with a secure algorithm by using the device IMEI.

As storage I would prefere Azure, I use it on my own atm and is very nice for .net and node.js.

As algortihm how about Rijndael or RSA.

A bit more explanation, the IMEI is unique and so nobody else can decrypt it, without access to the device. The other stuff, the cloud is the only option for global access.

Title: secure photos on server


问:
Is there a software license "for personal use only" and against any derivative work
I want to release an npm (NodeJS) module that will be a development dependency for extensions built for my product (will be used in testing). I don't want this module to be used in any released derivative work (commercial or free, open or closed source).

Is there an existing suitable license that I can use?

答: Such a license cannot possibly exist. The requirements you list are inconsistent. You want the license to be open-source, but you want it to violate the definition of "open-source". A license cannot be open-source and not open-source at the same time.</p>


问:
Is there a named anti pattern for historically grown software?
Is there an anti pattern that describes a historically grown software system where multiple developers just added new features to the system but no one really kept an eye on the overall architecture nor were refactorings ever done?

I think this happens when management/customer asks for new feature constantly and no one ever refactors anything but just adds on to what other developers haven done before.

A reason could also be that the developer is just overwhelmed with the software system and does not really understand how it currently works and then just adds/glues his code at the very end (instead of refactoring the code and changing it.)

So over time it's getting harder and harder to maintain the system.

(I wonder if there are pictures for these kind of anti pattern to make this more clear to none programming folks - like a car that was built by just adding more and more features without thinking of the overall design. Like someone has the need to tow trailers while riding backwards and then an engineer just welds a tow bar to the front of the car. Job done. But now the cowl doesn't open anymore.)

答:
You refer to technical debt.

We all accrue technical debt in the products we develop over time; refactoring is one of the very common and effective ways of reducing this technical debt, though many companies never pay down their technical debt. These companies tend to find their software extremely unstable years down the road, and the technical debt becomes so gruesome that you can't pay it down incrementally, because it would take too long to pay it down that way.

Technical debt has the term, because it follows the same behaviours of debt. You get the debt, and as long as you continue spending (creating features) and not paying down that debt, it'll only grow. Much like debt, when it get's too large you get to points where you may wish to shed it entirely with dangerous tasks like full-out rewrites. Also like real debt, as it accrues to a certain point, it hinders your ability to spend (creating features) altogether.

Just to throw another term in the mix, cohesion refers to how well a system, micro to the line level, or macro to the system level, fits together. A highly cohesive system will have all of its pieces fit together very well and look like one engineer wrote all of it. Your reference above to somebody just gluing their code to the end would be violating the cohesion of that system.

Managing Technical Debt

There are a lot of ways to manage technical debt, though like real debt the best approach is to pay it down frequently. Unfortunately like real debt it's occasionally a better idea to accrue more for a short period, where for instance time to market for a feature may double or triple your revenue. The tricky part is weighing these competing priorities as well as identifying when the debts ROI isn't worth it for the given feature vs. when it is.

So sometimes it is worth it to accrue the debt for a short period, but that's rarely the case, and as with all debt, the shorter the period the better. So eventually (preferably quickly) after you accrue technical debt, you have to pay it down, these are common approaches:

Refactoring

This allows you to take bits of code that were only realized to be misplaced partway through or after implementation was complete, and put them in their correct place (or a more correct one anyway).

Rewrite

This is like a bankruptcy. It wipes the slate clean, but you start with nothing and have every opportunity to make the same mistakes, or even bigger ones. High risk high reward approach to technical debt, but sometimes it's your only option. Though that's more rarely the case than many will tell you.

Architecture Overview

This is more of an active technical debt pay-down approach. This is done by having someone with authority over the technical details to halt an implementation regardless of project plans and schedules to ensure it accrues less technical debt.

Code Freeze

Freezing the code of changes can allow you breathing room where your debt doesn't go up or down. This gives you time to plan your approach to reducing the technical debt with hopes of having the highest ROI on your approach.

Modularization

This is like a tier-2 approach only available when you employ either Architecture Overview to have a modular system already, or Refactoring to move towards one. When you have a modular system, you can then pay down debt in whole pieces of the system in an isolated way. This allows you to do partial re-writes, partial refactoring, as well as minimizing the rate technical debt accrues because the isolation keeps the debt only in those areas where the features went in, as opposed to spread around the system.

Automated Tests

Automated testing can aid in managing your technical debt, because they can help you identify trouble spots in the system, hopefully before the debt in those areas has grown very large, but even after the fact they can still make engineers aware of those dangerous areas they may not have already realized. Furthermore, once you've got automated tests, you can more freely refactor things without concern for breaking too much. Not because developers won't break things, but because they'll find out when they do break things, relying on manual testers in highly indebted systems tends to have a poor track record for finding issues.


问:
Nested CSS styles ~ Where have I seen this concept before?
I can't find this now but I've read it before on various blogs discussing the topic. I'll give an example and hopefully it's clear (albeit it may not clarify anything at all).

Given this piece of markup (arbitrary on purpose):

```<code><div class="myWrapper">

    <img url="someimage.url">

</div>
<div class="yourWrapper">

    <img url="someimage.url">

</div>
</code>```

While the CSS could read like this:

```<code>.myWrapper .img img {border: thin black solid;}
.myWrapper .img {margin:10px;}
.yourWrapper .img img {border: thick red dashed;}
.yourWrapper .img {margin:20px;}
</code>```

It could also be written like this:

```<code>.myWrapper {
  .img {
    margin:10px;
    img {
        border: thin black solid;
    }
  }
}
.yourWrapper {
  .img {
    margin:10px;
    img {
        border: thick red dashed;
    }
  }
}
</code>```

But I can't remember seeing where that was discussed or if it's something in the works. Anybody know what the hell I'm talking about?

And I don't think this is an SO question or I would've put it on SO.

答:
LESS CSS

dynamic stylesheet language designed by Alexis Sellier. It is influenced by Sass and has influenced the newer "SCSS" syntax of Sass, which adapted its CSS-like block formatting syntax. LESS is open-source. Its first version was written in Ruby, however in the later versions, use of Ruby has been deprecated and replaced by JavaScript. The indented syntax of LESS is a nested metalanguage, as valid CSS is valid LESS code with the same semantics. LESS provides the following mechanisms: variables, nesting, mixins, operators and functions; the main difference between LESS and other CSS precompilers being that LESS allows real-time compilation via LESS.js by the browser.] LESS can run on the client-side and server-side, or can be compiled into plain CSS...

LESS uses those nested styles.

```<code>#header {
  color: red;
  a {
    font-weight: bold;
    text-decoration: none;
  }
}
</code>```

Body:
I can't find this now but I've read it before on various blogs discussing the topic. I'll give an example and hopefully it's clear (albeit it may not clarify anything at all).

Given this piece of markup (arbitrary on purpose):

```<code><div class="myWrapper">
  <a href="somepage.url" class="img">
    <img url="someimage.url">
  </a>
</div>
<div class="yourWrapper">
  <a href="somepage.url" class="img">
    <img url="someimage.url">
  </a>
</div>
</code>```

While the CSS could read like this:

```<code>.myWrapper .img img {border: thin black solid;}
.myWrapper .img {margin:10px;}
.yourWrapper .img img {border: thick red dashed;}
.yourWrapper .img {margin:20px;}
</code>```

It could also be written like this:

```<code>.myWrapper {
  .img {
    margin:10px;
    img {
        border: thin black solid;
    }
  }
}
.yourWrapper {
  .img {
    margin:10px;
    img {
        border: thick red dashed;
    }
  }
}
</code>```

But I can't remember seeing where that was discussed or if it's something in the works. Anybody know what the hell I'm talking about?

And I don't think this is an SO question or I would've put it on SO.

Body:
LESS CSS

dynamic stylesheet language designed by Alexis Sellier. It is influenced by Sass and has influenced the newer "SCSS" syntax of Sass, which adapted its CSS-like block formatting syntax. LESS is open-source. Its first version was written in Ruby, however in the later versions, use of Ruby has been deprecated and replaced by JavaScript. The indented syntax of LESS is a nested metalanguage, as valid CSS is valid LESS code with the same semantics. LESS provides the following mechanisms: variables, nesting, mixins, operators and functions; the main difference between LESS and other CSS precompilers being that LESS allows real-time compilation via LESS.js by the browser.] LESS can run on the client-side and server-side, or can be compiled into plain CSS...

LESS uses those nested styles.

#header {
  color: red;
  a {
    font-weight: bold;
    text-decoration: none;
  }
}


问:
How often should a Scrum team meet its Sprint commitment?
Commitment is a promise, and we all have been taught that you need to keep your promises.
But is it realistic to keep the commitment for each Sprint? Sometimes people get sick, sometimes the technical approach is proven wrong and you have to rethink everything, sometimes during further discussions with the product owner or the users you understand that the feature should be very different from what was originally thought.

I know that the official Scrum Guide now uses the word "forecast" rather than commitment, probably to address these problems.

So my question is how often do teams in your organizations keep their commitment and whether you like this approach or you want to change it.

Thank you.

答:
My perspective is that teams aren't making a commitment. Arguably, they aren't even making a forecast. The forecast is made before the sprint is planned -- the forecast is that on average they will meet their velocity. That means sometimes they will do a few more points than their velocity, sometimes they will do a little less.

If you're doing less than your velocity on a regular basis, your velocity drops to reflect that. The forecast thus drops as well. If you keep pulling in more stories than your historical velocity says you can do sprint after sprint, it's not a failure in execution, it's a failure in planning. You know your velocity, so you shouldn't be bringing in more points than history says you can accomplish.

To answer your specific question, of the three organizations where I've used scrum, only one tracked the "miss the commit" metrics over time. For that company, teams typically hit their forecast around 85% of the time.


答:
Your description fits Foote and Yoder's Big Ball of Mud:

Over the last several years, a number of authors... have presented patterns that characterize high-level software architectures... In an ideal world, every system would be an exemplar of one or more such high-level patterns. Yet, this is not so. The architecture that actually predominates in practice has yet to be discussed: the BIG BALL OF MUD.

A BIG BALL OF MUD is haphazardly structured, sprawling, sloppy, duct-tape and bailing wire, spaghetti code jungle. We’ve all seen them. These systems show unmistakable signs of unregulated growth, and repeated, expedient repair. Information is shared promiscuously among distant elements of the system, often to the point where nearly all the important information becomes global or duplicated. The overall structure of the system may never have been well defined. If it was, it may have eroded beyond recognition. Programmers with a shred of architectural sensibility shun these quagmires. Only those who are unconcerned about architecture, and, perhaps, are comfortable with the inertia of the day-to-day chore of patching the holes in these failing dikes, are content to work on such systems...

Why does a system become a BIG BALL OF MUD? Sometimes, big, ugly systems emerge from THROWAWAY CODE. THROWAWAY CODE is quick-and-dirty code that was intended to be used only once and then discarded. However, such code often takes on a life of its own, despite casual structure and poor or non-existent documentation. It works, so why fix it? When a related problem arises, the quickest way to address it might be to expediently modify this working code, rather than design a proper, general program from the ground up. Over time, a simple throwaway program begets a BIG BALL OF MUD.

Even systems with well-defined architectures are prone to structural erosion. The relentless onslaught of changing requirements that any successful system attracts can gradually undermine its structure. Systems that were once tidy become overgrown as PIECEMEAL GROWTH gradually allows elements of the system to sprawl in an uncontrolled fashion.

If such sprawl continues unabated, the structure of the system can become so badly compromised that it must be abandoned. As with a decaying neighborhood, a downward spiral ensues. Since the system becomes harder and harder to understand, maintenance becomes more expensive, and more difficult. Good programmers refuse to work there. Investors withdraw their capital. And yet, as with neighborhoods, there are ways to avoid, and even reverse, this sort of decline. As with anything else in the universe, counteracting entropic forces requires an investment of energy. Software gentrification is no exception. The way to arrest entropy in software is to refactor it. A sustained commitment to refactoring can keep a system from subsiding into a BIG BALL OF MUD...

...One of mud's most effective enemies is sunshine. Subjecting convoluted code to scrutiny arrow can set the stage for its refactoring, repair, and rehabilitation. Code reviews are one mechanism one can use to expose code to daylight.

<img src="https://i.stack.imgur.com/AAk1Q.gif" alt="http://www.laputan.org/images/pictures/Mir-Mud.gif" title="The Russian Mir ("Peace") Space Station Complex was designed for reconfiguration and modular growth. The Core module was launched in 1986, and the Kvant ("Quantum") and Kvant-2 modules joined the complex in 1987 and 1989. The Kristall ("Crystal") module was added in 1990. The Spektr ("Spectrum") and shuttle Docking modules were added in 1995, the latter surely a development not anticipated in 1986. The station’s final module, Priroda ("Nature"), was launched in 1996. The common core and independent maneuvering capabilities of several of the modules have allowed the complex to be rearranged several times as it has grown...">

Title: Is there a named anti pattern for historically grown software?

Body:
Is there an anti pattern that describes a historically grown software system where multiple developers just added new features to the system but no one really kept an eye on the overall architecture nor were refactorings ever done?

I think this happens when management/customer asks for new feature constantly and no one ever refactors anything but just adds on to what other developers haven done before.

A reason could also be that the developer is just overwhelmed with the software system and does not really understand how it currently works and then just adds/glues his code at the very end (instead of refactoring the code and changing it.)

So over time it's getting harder and harder to maintain the system.

(I wonder if there are pictures for these kind of anti pattern to make this more clear to none programming folks - like a car that was built by just adding more and more features without thinking of the overall design. Like someone has the need to tow trailers while riding backwards and then an engineer just welds a tow bar to the front of the car. Job done. But now the cowl doesn't open anymore.)


问:
Faster reads, on an infinite grid plane, than using a hash table?
In the past, I've had alot of success just using a .NET Dictionary, with a TKey consisting of the X,Y coordinates merged together. However its read performance, despite being amortized constant time, is a bottleneck in a design of mine.

My application needs to perform alot of reads, and would benefit greatly if the performance of the read was similar to that of an array. My data has a very high degree of spatial locality; attached is an image showing two graphs of the distribution of some sample data on a 2D plane (sorry for the lack of labels); on the left is data with low spatial locality, and on the right is how my data looks (it's always a single connected mass, and blocky in form).

I could use an array (by computing a bounding rectangle (bRect) around the data and then doing data=array[(y-bRect.Top)*bRect.Height+x-bRect.Left]) but then I'd have to rebuild the entire array each time bRect.Height changed, or bRect.Width increased.

And so my question is, given the high degree of spatial locality, is Dictionary really the best choice here? Is there another approach I could take where I could get near array like read performance, yet not have to rebuild the array when data is added? (I don't need to ever remove data)

答:
I could use an array (by computing a bounding rectangle (bRect) around the data and then doing data=array[(y-bRect.Top)*bRect.Height+x-bRect.Left]) but then I'd have to rebuild the entire array each time bRect.Height changed, or bRect.Width increased.

Utilize the Cantor pairing function as your hash function.
I would also assume that using the cantor pairing function to index in a plain array is somewhat faster than an hash table because the overhead of checking for an collision and modulo operations can be avoided.

How big is your array? If it doesn't fit in L2 cache, you may want to consider Z-order curves to help with spatial locality. It is also possible to use hilbert curves with the same result, but that seems quite expensive compared to Z-order curves.

I should also note that when you have a single connected mass, storing data per pixel may not be the best approach. It might be possible to speed up your algorithm by generating mipmaps (lower resolution versions of your data) and reading from that to help keeping everything in cache.

Since you mentioned reading is the bottleneck, moving the computation to the GPU may lead to some degree of success.


答: The most complicated feature of C++ is templates, because of their power and awkward syntax.  It isn't hard to use pre-written ones, and it isn't hard to write a simple templated class or function, but C++ templates are a compiler-executed Turing-complete language.</p>


问:
How does package naming affects Android application once deployed?
Are there conventions to follow when naming an application package for an Android application?

I'm coding in Xamarin Studio, using .Net, so I feel far from this "com.myapp.etc" naming convention.

Are there rules to follow when naming an Android package?

答: The com.domain.myapp convention is to prevent namespace collision globally.  Android doesn't allow two packages of the same name, so you can't use a generic name.  If you don't have a web site for your app, a lot of people use com.github.myGithubUsername.myApp if they use github to host their version control.</p>


问:
How to completely avoid business logic in DAL?
In our ASP.NET MVC application, we try really hard to separate concerns to each layer (we use DDD). Nevertheless, it seems that we can't avoid having at least some business logic in DAL.

For instance, there are named objects, where business requirement is that each name must be unique (but the name isn't a key). If there is a request to create new named object, the service checks whether some object with that name exists in repository, if it doesn't, factory creates new object and repository persists it (we use EF for repositories and stored procedures for query objects).

The problem is with race conditions - if two requests come concurrently (it's unlikely, but possible), both requests want to create new object under the same name, in this case both checks come out negative and two objects with the same name would be created. So far, we handle that with constrains in SQL database, so if something like this happens, an exception is thrown in repository - but this approach is simply wrong, since such requirement is strictly business requirement and it shouldn't bubble to persistence layer; if we change such requirement, e.g. that names become case sensitive, such constrain would also have to be changed, etc.).

How to implement such scenario correctly? Thanks.

答:
So far, we handle that with constrains in SQL database, so if something like this happens, an exception is thrown in repository - but this approach is simply wrong, since such requirement is strictly business requirement and it shouldn't bubble to persistence layer.

You can make that argument if you like, but your relational database already has the necessary indexing and concurrency mechanisms to make it very convenient and reliable to do it there.

If the idea of detecting duplicates in a database makes you uncomfortable, then think of uniqueness as an attribute of the data.  Enforcing such an attribute is a perfectly valid thing to do in a database.  You wouldn't argue that the type of a data field (i.e. text, float, currency) is a business rule, would you?

OwnerDisplayName: Robert Goldwein

OwnerDisplayName: Robert Harvey


问:
A module which is used by most other modules
I am pursuing object oriented design. So we don't want to use globals but yet sometime we have a module that most other modules use.  This means we have to just pass it to all other modules and this can be literally all modules!

```<code>class Logger
{
public:
    Logger(void);
    ~Logger(void);
};

class Calculator
{
public:
    Calculator(Logger *logger);
    ~Calculator(void);
};

class Taxation
{
public:
    Taxation(Logger *logger);
    ~Taxation(void);
};
</code>```

So the idea is that the Calculator and Taxation modules use the Logger module to log everything. Similarly most other modules will use it too, and logging is required everywhere. Is this method okay or should Logger be global instead?

答:
It would be better if you define the Logger as a Singleton instead of passing the object on each class.

Define the Logger like:

```<code>class Logger
{
  private:
    Logger()
    {
        //private constructor
    }
  public:
    static Logger& sharedInstance()
    {
        static Logger singleTon;
        return singleTon;
    }
    ~Logger()
    {
       // Cleanup
    }
};
</code>```

Wherever you need logger, get it like:

```<code>Logger::sharedInstance();
</code>```

OwnerDisplayName: zadane

Body:
It would be better if you define the Logger as a Singleton instead of passing the object on each class.

Define the Logger like:

class Logger
{
  private:
    Logger()
    {
        //private constructor
    }
  public:
    static Logger& sharedInstance()
    {
        static Logger singleTon;
        return singleTon;
    }
    ~Logger()
    {
       // Cleanup
    }
};

Wherever you need logger, get it like:

Logger::sharedInstance();

OwnerDisplayName: Midhun MP


答:
BTW Agree with @Robert Harvey.

There's a subtle but problematic shift in your question -- the original question is "how to isolate business logic" but then you switch over to isolating "business requirements".

Business requirements will permeate your system. Of necessity. During the data modelling effort, that's going to be driven by the data that the business has identified, and constraints on the data. Your data model will always reflect the business requirements. For example, the business may require that you capture First, Middle and Last names for customers. So your database will contain those fields, and there's just no way to isolate that from the business requirements.

Business logic, on the other hand, is a different beast. That is, business logic is little snippets of code like the calculation for a customer's monthly fee. Or a predicate, like whether or not a customer is eligible for some promotion. If your DAL has those calculations built into it, then you've crossed a line.

Providing a mechanism like uniqueness or concurrency is definitely going to come from a business requirement, but it's not business logic. The business doesn't care how you provide concurrency and uniqueness, as long as you do. You could say it supports business logic, but isn't specified by the business.

On the other hand, a calculation of the user's annual contribution percentage, or whatever, is code the business specifies directly, and is something you want to isolate for the sake of testing, validation, flexibility, etc.

Title: How to completely avoid business logic in DAL?

Body:
In our ASP.NET MVC application, we try really hard to separate concerns to each layer (we use DDD). Nevertheless, it seems that we can't avoid having at least some business logic in DAL.

For instance, there are named objects, where business requirement is that each name must be unique (but the name isn't a key). If there is a request to create new named object, the service checks whether some object with that name exists in repository, if it doesn't, factory creates new object and repository persists it (we use EF for repositories and stored procedures for query objects).

The problem is with race conditions - if two requests come concurrently (it's unlikely, but possible), both requests want to create new object under the same name, in this case both checks come out negative and two objects with the same name would be created. So far, we handle that with constrains in SQL database, so if something like this happens, an exception is thrown in repository - but this approach is simply wrong, since such requirement is strictly business requirement and it shouldn't bubble to persistence layer; if we change such requirement, e.g. that names become case sensitive, such constrain would also have to be changed, etc.).

How to implement such scenario correctly? Thanks.


答:
No, there are no major software licenses that allow only personal use.  Unless for some reason you want someone to be able to rebuff you when you try and bring them to court for going too far, there's no reason to write a formal license of any kind.

A simple copyright statement is all that you really need.  And even that may be overkill, if your product is otherwise still unreleased and in testing.

Update from the guy that asked the question: I have spoken with someone from npm and they are fine with a copyright notice "All rights reserved" in the LICENSE file.

Title: Is there a software license "for personal use only" and against any derivative work

Body:
I want to release an npm (NodeJS) module that will be a development dependency for extensions built for my product (will be used in testing). I don't want this module to be used in any released derivative work (commercial or free, open or closed source).

Is there an existing suitable license that I can use?