问:
Advise on How To migrate a huge monolithic java application towards something service-oriented
I am confronted with the problem of migrating a huge monolithic java web application towards a more service oriented approach. The application has grown for years from what it was originally desinged for and is still growing. That means a lot of changed customer requriements where development under time pressure with few concernce about code quality. That led to very very complex code structure (no modular packaging, a lot of complex inheritants, mix of functionality in classes and as good as no documentation).

Now step by step funcionality shall be extracted and run as service.

Replacement/Redevelopment is currently out of questions. So the code should be extraced and wrapped so it can be replaced later with a new cleaner version.

The problem I now have to deal with is that it is really hard to identify the code that represents a functionality and extracting it without breaking other functionalities or even the whole application.

Any ideas how I can approach this problem? I am open to everything.

答:
The main way to achieve this is by first identifying shearing layers - those parts that seems slightly less firmly embedded in the rest of the app. For example, DB access - every bit of that calls an external system, so its an ideal place to look for replacing with SOA calls.

Next you can look at larger areas that are more modular, and replace those with an external SOA call. You're basically splitting up the monolithic code as best you can into chunks that are accessed via a SOA rather than an ordinary method call. You may need to ensure that some of the replaced modules are wrapped in classes that look like the old so the rest of the old app doesn't know anything's changed - just that the internals are now calling an external system rather than internal code.

Once you've got all that done, you'll have a smaller codebase, but it'll still be messy and monolithic. At that point, you have to really get dirty and change the way the code works, you'll need to start changing the GUI or the bulk of it in more intrusive ways, take a part that is on the edge of the main program and start there, once you've done a few of those it'll become easier.


答:
Thoroughly construct and define an API, or set of different APIs if needed, then implement by just wrapping requests to this webapp (and/or packages which are used by this webapp).

This will help you to "multithread" following development. You'll be able both build new tools, which will use your new API, and, at the same time, you can start gradually change API implementation, thus getting rid from old webapp.

Divide and conquer, nothing has changed since Romans :)

ContentLicense: CC BY-SA 3.0

Title: Advise on How To migrate a huge monolithic java application towards something service-oriented

Body:
I am confronted with the problem of migrating a huge monolithic java web application towards a more service oriented approach. The application has grown for years from what it was originally desinged for and is still growing. That means a lot of changed customer requriements where development under time pressure with few concernce about code quality. That led to very very complex code structure (no modular packaging, a lot of complex inheritants, mix of functionality in classes and as good as no documentation).

Now step by step funcionality shall be extracted and run as service.

Replacement/Redevelopment is currently out of questions. So the code should be extraced and wrapped so it can be replaced later with a new cleaner version.

The problem I now have to deal with is that it is really hard to identify the code that represents a functionality and extracting it without breaking other functionalities or even the whole application.

Any ideas how I can approach this problem? I am open to everything.


问:
What's more restrictive, the RPL or the AGPL?
What's the difference between the RPL licence and the AGPL licence?

Which one is more restrictive?

答:
The Reciprocal Public License requires any changes to be released (publically!) even when software is used only internally, the GNU Affero General Public License does not.

The AGPL is also GPL-compatible, while the RPL is not.

These are the core differences.


问:
Is it a good idea to design an architecture thinking that the User Interface classes can be replaced by a command line interface?
In Code Complete page 25, it's said that it's a good idea to be able to easily replace the regular user interface classes by a command line one.

Knowing its advantages for testing, what about the problems it may bring?

Will this extra work really pay off for web and mobile projects? What about small and medium projects; do the same rules apply?
What if it makes your design more complex?

答:
One key advantage that doesn't seem to have been mentioned is that being able to do this pretty much enforces strict decoupling of the UI from the underlying code. One key advantage of this is that it means that if you need to significantly change the GUI (say iOS standards to OSX standards, or one graphical engine to another), that's all you need to change, as the underlying code isn't dependent on the layout of the UI. It can't be, because if it was, the command line tools wouldn't work.

Other than that, being able to automate tests is a key advantage.


问:
Is Object Oriented Programming a solution to complexity?
Do you think Object Oriented Programming is a solution to complexity. Why? This topic may be a bit controversial but my intentions to know the answer of Why from the experts here !</p>

答:
There are many kinds of complexity to software development.  At the programming level, OOP seeks to address complexity by using objects and classes to model the problem domain.  A well-known guru said problem solving is just representing the problem so that the solution is the representation itself. Hence, by abstraction using classes, encapsulation using access modifiers and methods, inheritance for specifying relationship and reuse, composition in establishing relationship and collaboration between classes, polymorphism as a means to simplify the determination of different behaviors in similar objects, complexity can be managed.

There are also other ways to manage software complexity, for example, Logic (Prolog) and Functional (Haskell) programming.

At a level higher than programming, we need Design Patterns and Principles to guide OOP. Hence OOP is managing complexity at a low (coding) level while these methodologies such as Design Patterns and Principles guide the design of the solution at a higher (system and application) level and make software development and handling complexities more manageable.

To answer your question, yes, OOP is just a solution to handling complexity among many other solutions.  It is a solution at a low level.  We need Design Patterns and Principles to guide OOP in a higher level.

ContentLicense: CC BY-SA 2.5


问:
Are all programming problems algorithm problems?
I like how "Introduction to Algorithms" by Cormen et al. conveys knowledge. One reason is that everything has to do with programming problems and the book is not implemented in any particular programming language. This language independency provides focus on the ideas in general.

So my question is, as it says in the title. Is every solveable programming problem solveable by thinking in this algorithmic fashion. No matter which language, field, etc ? If yes, give arguments, else, give arguments!

I have not implemeted many complex programs with GUI, AI, Graphics, etc ... But are these types of problems also a matter of thinking out good algorithms?

答:
I suppose you could say that all computer programs are algorithms, because you are prescribing a sequence of instructions to achieve a desired result.  However, some of the most difficult problems aren't in communicating a program to a computer, they are in communicating a program to humans who will be testing and modifying the software.

In other words, computers don't care if your code is completely incomprehensible to humans.  They will run it just fine either way.  The challenge is in making code clear enough that any bugs will stand out like a sore thumb.

Interestingly, the technical things I learned in college about algorithms have long been eclipsed by what I've learned on my own since then.  At this point if I wanted to get a 3rd college degree to help me in my job, it would be in English composition.


问:
How can you tell whether to use Composite Pattern or a Tree Structure, or a third implementation?
I have two client types, an "Observer"-type and a "Subject"-type. They're both associated with a hierarchy of groups.

The Observer will receive (calendar) data from the groups it is associated with throughout the different hierarchies. This data is calculated by combining data from 'parent' groups of the group trying to collect data (each group can have only one parent).

The Subject will be able to create the data (that the Observers will receive) in the groups they're associated with.
When data is created in a group, all 'children' of the group will have the data as well, and they will be able to make their own version of a specific area of the data, but still linked to the original data created (in my specific implementation, the original data will contain time-period(s) and headline, while the subgroups specify the rest of the data for the receivers directly linked to their respective groups).

However, when the Subject creates data, it has to check if all affected Observers have any data that conflicts with this, which means a huge recursive function, as far as I can understand.

So I think this can be summed up to the fact that I need to be able to have a hierarchy that you can go up and down in, and some places be able to treat them as a whole (recursion, basically).

Also, I'm not just aiming at a solution that works. I'm hoping to find a solution that is relatively easy to understand (architecture-wise at least) and also flexible enough to be able to easily receive additional functionality in the future.

Is there a design pattern, or a good practice to go by, to solve this problem or similar hierarchy problems?

EDIT:

Here's the design I have:

The "Phoenix"-class is named that way because I didn't think of an appropriate name yet.

But besides this I need to be able to hide specific activities for specific observers, even though they are attached to them through the groups.

A little Off-topic:

Personally, I feel that I should be able to chop this problem down to smaller problems, but it escapes me how. I think it's because it involves multiple recursive functionalities that aren't associated with each other and different client types that needs to get information in different ways. I can't really wrap my head around it. If anyone can guide me in a direction of how to become better at encapsulating hierarchy problems, I'd be very glad to receive that as well.

答:
Here's a simple "Group" implementation that allows you to navigate to the Root, and navigate that Root's tree as a collection.

```<code>public class Group
{
  public Group Parent
  public List<Group> Children

  public IEnumerable<Group> Parents()
  {
    Group result = this;
    while (result.Parent != null)
    {
      result = result.Parent;
      yield return result;
    }
  }
  public Group Root()
  {
    return Parents.LastOrDefault() ?? this;
  }

  public IEnumerable<Group> WalkTreeBreadthFirst(
  {
    //http://en.wikipedia.org/wiki/Breadth-first_search
    HashSet<Group> seenIt = new HashSet<Group>()
    Queue<Group> toVisit = new Queue<Group>();
    toVisit.Enqueue(this);

    while (toVisit.Any())
    {
      Group item = toVisit.Dequeue();
      if (!seenIt.Contains(item))
      {
        seenIt.Add(item);
        foreach (Group child in item.Children)
        {
          toVisit.Enqueue(child);
        }
        yield return item;
      }
    }
  }

  public static IEnumerable<Group> WalkTreeDepthFirst()
  {
    // http://en.wikipedia.org/wiki/Depth-first_search
    HashSet<Group> seenIt = new HashSet<Group>();
    Stack<Group> toVisit = new Stack<Group>();

    toVisit.Push(this);

    while (toVisit.Any())
    {
      Group item = toVisit.Pop();
      if (!seenIt.Contains(item))
      {
        seenIt.Add(item);
        foreach (Group child in item.Children.Reverse())
        {
          toVisit.Push(child);
        }
        yield return item;
      }
    }
  }
}
</code>```

So - given a group, you can walk that Group's tree:

```<code>Group myGroup = GetGroup();
Group root = myGroup.Root;
foreach(Group inTree in root.WalkTreeBreadthFirst())
{
  //do something with inTree Group.
}
</code>```

My hope in posting this, is that by showing how to navigate a tree (and dispelling the complexity thereof), you may be able to visualize about the operations you want to perform on the tree, and then revisit the patterns on your own to see what best applies.

OwnerDisplayName: Aske B.

Body:
Here's a simple "Group" implementation that allows you to navigate to the Root, and navigate that Root's tree as a collection.

public class Group
{
  public Group Parent
  public List<Group> Children

  public IEnumerable<Group> Parents()
  {
    Group result = this;
    while (result.Parent != null)
    {
      result = result.Parent;
      yield return result;
    }
  }
  public Group Root()
  {
    return Parents.LastOrDefault() ?? this;
  }

  public IEnumerable<Group> WalkTreeBreadthFirst(
  {
    //http://en.wikipedia.org/wiki/Breadth-first_search
    HashSet<Group> seenIt = new HashSet<Group>()
    Queue<Group> toVisit = new Queue<Group>();
    toVisit.Enqueue(this);

    while (toVisit.Any())
    {
      Group item = toVisit.Dequeue();
      if (!seenIt.Contains(item))
      {
        seenIt.Add(item);
        foreach (Group child in item.Children)
        {
          toVisit.Enqueue(child);
        }
        yield return item;
      }
    }
  }

  public static IEnumerable<Group> WalkTreeDepthFirst()
  {
    // http://en.wikipedia.org/wiki/Depth-first_search
    HashSet<Group> seenIt = new HashSet<Group>();
    Stack<Group> toVisit = new Stack<Group>();

    toVisit.Push(this);

    while (toVisit.Any())
    {
      Group item = toVisit.Pop();
      if (!seenIt.Contains(item))
      {
        seenIt.Add(item);
        foreach (Group child in item.Children.Reverse())
        {
          toVisit.Push(child);
        }
        yield return item;
      }
    }
  }
}

So - given a group, you can walk that Group's tree:

Group myGroup = GetGroup();
Group root = myGroup.Root;
foreach(Group inTree in root.WalkTreeBreadthFirst())
{
  //do something with inTree Group.
}

My hope in posting this, is that by showing how to navigate a tree (and dispelling the complexity thereof), you may be able to visualize about the operations you want to perform on the tree, and then revisit the patterns on your own to see what best applies.

OwnerDisplayName: David B


问:
Is it ever too early to learn a new language?
Personal context: I've been learning C++ formally the last 6 months at university. Prior to this I dabbled in JavaScript for a year. Now I am considering learning Python during a month off school.

By splitting my focus early in the learning process am I degrading the efficiency of my learning? Should I spend the month off continuing in C++? Or is it never too early to learn a new language?

答:
To a practicing programmer I would unreservedly say learning a new language is almost never a bad idea.  To a university student, I would urge a little caution, depending on what classes are coming up.  The reason is, in a school exam you frequently have to recite language details without the benefit of a compile/execute environment that will easily point out your mistakes.

Especially when you only have a few month's experience, it's very easy to mix up the details in your mind.  If you care about your grades and are taking a class with exams like that, I would be careful.  In the real world, that's not a concern.

edit: I originally said syntax, but non-syntactic details are just as important to professors, and there are a lot more of those.


问:
Django application strategy
I have been working a while on a Django project which has been growing a bit lately. I have been think a bit about what strategy to use to make it easier to handle. One thing I would like to get some input on would be if I should split my application into several smaller applications. That would make my view and model files smaller and separate some of the concerns.

One thing that bothers me with this is that in my applications I would have several helper methods that will be used across applications. Also some models will also have to be shared/used across applications. Would this make sense? This doesn't go well with the separation of concerns I was hoping to achieve by splitting my app in several smaller apps.
What would be a good approach for sharing helper methods, models etc. across applications?

答:
I like to create a base/ app with no views and no moments for shared stuff.

One problem that can occur when you have models spread over multiple apps is circular imports. This can be avoided by using strings to refer to other models (foo = ForeignKey("someapp.Foo") instead of foo = ForeignKey(someapp.models.Foo)). Django lets you use strings like this in more places.

Title: Django application strategy


问:
Efficient algorithm to sort html list of players
We have list of players, which is represented in form like this:

```<code><div class="players_list">
   <div class="player" data-points="500">
        <div class="name">Player1</div>
        <div class="position">1</div>
   </div>
   <div class="player" data-points="400">
        <div class="name">Player2</div>
        <div class="position">2</div>
   </div>
   <div class="player" data-points="300">
        <div class="name">Player3</div>
        <div class="position">3</div>
   </div>
   <div class="player" data-points="200">
        <div class="name">Player4</div>
        <div class="position">4</div>
   </div>
</div>
</code>```

Something happens, and Player 4 recieves 600 points. So it goes on 1st place.
With him - player3 recieves 300 points and goes on 2nd place.

It happens after same event - let's assume, that they get these points from server, but that's all load that is allowed on server and server does not calculate positions.

What is most efficent way to get view like this:

```<code><div class="players_list">
   <div class="player" data-points="800">
        <div class="name">Player4</div>
        <div class="position">1</div>
   </div>
   <div class="player" data-points="700">
        <div class="name">Player3</div>
        <div class="position">2</div>
   </div>

   <div class="player" data-points="500">
        <div class="name">Player1</div>
        <div class="position">3</div>
   </div>
   <div class="player" data-points="400">
        <div class="name">Player2</div>
        <div class="position">4</div>
   </div>
</div>
</code>```

It's not question about code, it's question about:

What kind of task it is? Just sort?

Is it ok to use JavaScript to solve this task if lists are less than 500 rows?

Is it ok to re-render whole players list, or there are some ways to just change div element position(index in DOM or something like this)?

Are there any tools and libraries around, that can help solve this task efficiently?

P.S.: If we want to animate all this story - we should create a queue of animation tasks each time scores for all players recalculates?

Update:

I have followed @Jalayn's answer, and stuck on following problem:

Let's assume that list [1,2,3,4] transforms to [2,3,4,1]. If we map it, we will get following position diffs [+1, +1, +1, -3].. Now, if we move one by one elements to it's position change, all will be ok, till we get to negotiate position diff - 1st position diff can't move down any more..

So, my update to question - how we can animate rows more than twice?

And final problem, on which I am stucked:

Not sure, if it most be solved in this question. BTW, if 2 players have same points - animation plan brakes and element_ids duplicates.

My question now is how to make following transformation of  structures list:
[(#id1, 1, 100),(#id2, 2, 50), (#id3, 2, 50), (#id4, 4, 25)] => [(#id3, 1, 150), (#id1, 2, 100), (#id4, 3, 75), (#id2, 4, 50)]

For now my solution is to refresh whole list, but not completly regenerate it - just move all elements to the first position in order they sorted in backed JSON. Animation is too complex to be done cause of final problem.

答:
Assuming you have multiplayers on different systems and some type of hosts (could be node.js).

I would say, that this is a typical update-score event. Something that gets triggered on the server. Since when the scores are changing, the server should send to each  player the new (ranked) scores.

I would use javascript (jquery) on the client side for rendering the score-list. With HTML5 you could use web sockets, and stream the new scores the moment the server (done calculating) sends out the event (or just notify the client that new score list is available).

I would keep as much as logic (as reasonable possible) on the server (MVC).


答:
The only danger I see in doing this is that to get to a certain part in the UI, the user normally has to traverse other parts of the UI.

Where as the developer can just execute the UI directly. I've seen situations where a developer could not reproduce a users issue until they actually used the product.

So factor that in as well when creating tests.

Title: Is it a good idea to design an architecture thinking that the User Interface classes can be replaced by a command line interface?

Body:
In Code Complete page 25, it's said that it's a good idea to be able to easily replace the regular user interface classes by a command line one.

Knowing its advantages for testing, what about the problems it may bring?

Will this extra work really pay off for web and mobile projects? What about small and medium projects; do the same rules apply?
What if it makes your design more complex?


答:
The reason Object-oriented programming seems to help us handle complexity is because it forces us to write code in a specific fashion instead of a huge variety of ways.  Task-oriented programming is much more intuitive, which is why programming started that way.  Object-orientation takes training and practice to understand and use effectively, but by constraining programming into a certain path, it allows those trained to effectively maintain the code that was written.

It's no more logical or real-world than any other method, it's just a way of focusing our problem solving through similar lenses.  A lot of technical specialties use the paradigm of a non-intuitive rigid methodology to handle the complexity of their tasks.

A third method to handle complexity would be functional programming, and there will be probably be other new methods in the future also.

Title: Is Object Oriented Programming a solution to complexity?

Body: Do you think Object Oriented Programming is a solution to complexity. Why? This topic may be a bit controversial but my intentions to know the answer of Why from the experts here !</p>


问:
What are the practical examples of code exploration techniques?
Code Exploration (CE) is quite a new term and I wonder if there already any successful examples of implementing this techniques in terms of Continuous Integration principles?

In short, Code Exploration can be described as the process of testing your code using different parameters to achieve high code coverage. The one-and-only tool for .NET world is PEX, but I know there are commercial instruments for code exploration in java world.

This topic is very powerful in conjunction with Design By Contract, because it provides you with the means of some formalism in reasoning about code correctness. For example PEX would show that next code contains error (source code uses Code Contracts and I assume default assembly configuration):

```<code>public int Factorial(int number)
{
    //postcondition of positive result, precondition is omitted
    Contract.Ensures( Contract.Result<int>() > 0 );

    return number <= 0 ? 1 : number * Factorial( number - 1 );
}
</code>```

Because by default overflow is not checked in arithmetic operations the input 17 will give the result of -288522240.

PEX was discussed here several times here:

How does Pex work

Pex and Code Contracts

But I don't want to touch internal implementation details, I'm interested in practical aspects of this problem.

Main questions are:

How exactly do you integrate Code Exploration with Continuous Integration?

Do you reject build if PEX gives errors or you notify team about inconsistencies and contracts violations?

Scott Hanselman has point, that PEX should run on separate machine (or multiple machines) continuously testing your code for errors (so called Continuous Exploration). You can listen to the talk Hanselminutes Podcast 93 - Pex. Are there any practical implementations of dedicated machine (would it be virtual or physical), that digs into your codebase in search of errors?

How do you treat test coverage of such tools? I think it would be unreasonable to merge code coverage results for unit tests written manually with the results by a code exploration tool.

Are there any examples of Parameterized Unit Tests in real projects, that would increase you productivity and unit tests quality?

答:
Even if you have a boundary checking tool generate your unit tests, they're still just unit tests.

Do you reject build if PEX gives errors or you notify team about inconsistencies and contracts violations?

Do you have gated check-ins turned on for your other unit tests?

This really isn't some new, distinct concept that needs us to make new rules to handle it. It's just being better about making the unit tests we should've been writing if we weren't too lazy or too naive about how corner cases impact code quality.


问:
What are the typical naming conventions for OO C public and private functions?
Short Question

Is there a typical way to name 'public' and 'private' members of an OO C project?

Background

I fully understand that public and private members do not really exist in the C language.  However, like most C programmers, I still treat members as public or private to maintain the OO design.  In addition to the typical OO methods I have found my self following a pattern (see example below) that makes it easier for me to distinguish which methods are meant for the outside world vs the private members that may have fewer checks / are more efficient etc... Does a standard or best practice exist for such a thing or is my example below a good way to approach this?

Example Header

```<code>#ifndef _MODULE_X_H_
#define _MODULE_X_H_

bool MOD_X_get_variable_x(void);
void MOD_X_set_variable_x(bool);

#endif /* _MODULE_X_H_ */
</code>```

Example Source

```<code>// Module Identifier: MOD_X
#include "module_x.h"

// Private prototypes
static void mod_x_do_something_cool(void);
static void mod_x_do_something_else_cool(void);

// Private Variables
static bool var_x;

// Public Functions - Note the upper case module identifier
bool MOD_X_get_variable_x(void)      {return var_x;}
void MOD_X_set_variable_x(bool input){var_x = input;}

// Private Functions  - Note the lower case module identifier
void mod_x_do_something_cool(void){
     // Some incredibly cool sub routine
}

void mod_x_do_something_else_cool(void){
     // Another incredibly cool sub routine
}
</code>```

答:
If an actual "class" exists, in the form of a struct, opaque type or similar, then I name it according to:

```<code>typedef struct classname_t classname_t;
</code>```

The _t suffix is a very common naming convention in C, used by the C standard itself. Less common is to use a capital letter for classes/types.

The next thing you do is to come up with a naming prefix for all public functions. Typically some 3 letter thing. All functions belonging to the "apple class" would perhaps be named app_set_something(), app_get_something() etc.

Then you will want to use a consistent naming convention. The "constructor" could be named app_init() or app_construct(), the "destructor app_clear(), app_destruct(), app_destroy() or similar. Use the same naming convention for all your classes. Then do the same for setter/getter functions, and so on.

Private (static) functions don't really need a class prefix since they aren't accessible outside the .c file anyhow. You could still give them the same prefix for consistency reasons, or perhaps simply name them all with a private prefix, such as private_func(). A very common way is to give them names starting with an underscore, but this is bad since it may collide with library functions. Strictly speaking you aren't allowed to use identifiers starting with an underscore.

I would not recommend to use upper case as a way to distinguish between private and public. The convention in almost all C coding standards is that all letters upper case indicates a constant, macro or a pre-processor define. That convention is used by the C standard itself, by the Windows API, by the Linux kernel and so on.

Body:
If an actual "class" exists, in the form of a struct, opaque type or similar, then I name it according to:

typedef struct classname_t classname_t;

The _t suffix is a very common naming convention in C, used by the C standard itself. Less common is to use a capital letter for classes/types.

The next thing you do is to come up with a naming prefix for all public functions. Typically some 3 letter thing. All functions belonging to the "apple class" would perhaps be named app_set_something(), app_get_something() etc.

Then you will want to use a consistent naming convention. The "constructor" could be named app_init() or app_construct(), the "destructor app_clear(), app_destruct(), app_destroy() or similar. Use the same naming convention for all your classes. Then do the same for setter/getter functions, and so on.

Private (static) functions don't really need a class prefix since they aren't accessible outside the .c file anyhow. You could still give them the same prefix for consistency reasons, or perhaps simply name them all with a private prefix, such as private_func(). A very common way is to give them names starting with an underscore, but this is bad since it may collide with library functions. Strictly speaking you aren't allowed to use identifiers starting with an underscore.

I would not recommend to use upper case as a way to distinguish between private and public. The convention in almost all C coding standards is that all letters upper case indicates a constant, macro or a pre-processor define. That convention is used by the C standard itself, by the Windows API, by the Linux kernel and so on.


答:
I think the answer is emphatically no.
Algorithms are just building blocks in a much larger skill set.

I got my degree in C.S., specializing in A.I.

There the fundamental problem, at least as I saw it, was to find good representations for information.
These representations should try to be good matches for the knowledge structures that are in people's heads, and should facilitate the kinds of manipulations and alterations that are done on them.

In terms of day-to-day programming, this means the basic problem is to identify the right domain-specific-language (DSL) for the situation at hand.
There are many ways to create DSLs.
Ordinary programming, where classes, variables, and methods are defined is in fact creating a DSL because it allows you to say things (map your mental structures to code) that you could not say without them.

Algorithms are important too, but they are only part of the story.

Title: Are all programming problems algorithm problems?

Body:
I like how "Introduction to Algorithms" by Cormen et al. conveys knowledge. One reason is that everything has to do with programming problems and the book is not implemented in any particular programming language. This language independency provides focus on the ideas in general.

So my question is, as it says in the title. Is every solveable programming problem solveable by thinking in this algorithmic fashion. No matter which language, field, etc ? If yes, give arguments, else, give arguments!

I have not implemeted many complex programs with GUI, AI, Graphics, etc ... But are these types of problems also a matter of thinking out good algorithms?


问:
How does the GPL work in regards to languages like Dart which compile to other languages?
Google's Dart language is not supported by any Web Browsers other than a special build of Chromium known as Dartium. To use Dart for production code you need to run it through a Dart->JavaScript compiler/translator and then use the outputted JavaScript in your web application.

Because JavaScript is an interpreted language everyone who receives the "binary"(Aka, the .js file) has also received the source code.

Now, the GNU General Public License v3.0 states that:

"The “source code” for a work means the preferred form of the work for making modifications to it."

Which would imply that the original Dart code in addition to the JavaScript code must also be provided to the end user. Does this mean that any web applications written in Dart must also provide the original Dart code to all visitors of their website even though a copy of the source code has already been provided in a human readable/writable/modifiable form?

答:
Yes, if the code is under the GPL and you deliver the outputted JavaScript, you must also provide the original Dart code. This would typically be done with a link to download the source code from your site but you could also embed it in a comment or something like that.

I think the easiest way to comply with the GPL in this case is to use option d for distributing the source

d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.

Essentially you do this when you include the JS file in your page

```<code><script src="file.js" /><!-- source at http://example.com/path/to/modified/source/file.dart -->
</code>```

Body:
Yes, if the code is under the GPL and you deliver the outputted JavaScript, you must also provide the original Dart code. This would typically be done with a link to download the source code from your site but you could also embed it in a comment or something like that.

I think the easiest way to comply with the GPL in this case is to use option d for distributing the source

d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.

Essentially you do this when you include the JS file in your page

<script src="file.js" /><!-- source at http://example.com/path/to/modified/source/file.dart -->


答:
In general, it really depends on the license.  In your case, Dart is a bad example since it's BSD, and it seems GNU 3.0 covers the case you are talking about.  As a non-lawyer I would interpret that quote as "The generated code isn't specifically covered"

Dart Home Page  Refers to this: BSD License

So you question about GPL is moot

Also: GNU 3.0 License

Is there some way that I can GPL the output people get from use of my program? For example, if my program is used to develop hardware designs, can I require that these designs must be free? (#GPLOutput)

In general this is legally impossible; copyright law does not give you any say in the use of the output people make from their data using your program. If the user uses your program to enter or convert his own data, the copyright on the output belongs to him, not you. More generally, when a program translates its input into some other form,> the copyright status of the output inherits that of the input it was generated from.

So the only way you have a say in the use of the output is if substantial parts of the output are copied (more or less) from text in your program. For instance, part of the output of Bison (see above) would be covered by the GNU GPL, if we had not made an exception in this specific case.

You could artificially make a program copy certain text into its output even if there is no technical reason to do so. But if that copied text serves no practical purpose, the user could simply deletethat text from the output and use only the rest. Then he would not have to obey the conditions on redistribution of the copied text.

Title: How does the GPL work in regards to languages like Dart which compile to other languages?

Body:
Google's Dart language is not supported by any Web Browsers other than a special build of Chromium known as Dartium. To use Dart for production code you need to run it through a Dart->JavaScript compiler/translator and then use the outputted JavaScript in your web application.

Because JavaScript is an interpreted language everyone who receives the "binary"(Aka, the .js file) has also received the source code.

Now, the GNU General Public License v3.0 states that:

"The “source code” for a work means the preferred form of the work for making modifications to it."

Which would imply that the original Dart code in addition to the JavaScript code must also be provided to the end user. Does this mean that any web applications written in Dart must also provide the original Dart code to all visitors of their website even though a copy of the source code has already been provided in a human readable/writable/modifiable form?


问:
Using a GPLv3 library in a freemium business model
I read several related questions about the use of GPLv3 in a commercial app but they don't say anything about a freemium app. I would like to use a GPLv3 library in two apps, a free one (with limited features) and a paid one.

Basically, the free app will allow to use the library without limitations, and the paid one will include it as well as other unrelated features.

I will release the free app under GPLv3 but do I need to release the paid one under the same license?

I don't want to release the whole source code of my paid app (for obvious reasons), as the other features don't use the library in any way. It would just be more convenient for users who bought the full version to have all features in a single app instead of putting the library in a separate one.

答:
Please look into the Apache license.  It allows you to distribute closed-source code with Apache-licensed open-source code.

As someone else pointed out, you can distribute a work under two licenses, one a traditional copyright, and another under GPL (for years, MySQL has successfully made this their business model), but the whole work must be open-source in order to distribute it under the GPL.  That's the point of the GPL and the reason that the Apache license came into being.

If you wanted to freely distribute all the source code for your application, while at the same time preventing others from distributing closed-source code with your code, then GPL would be perfect.  There is no way to distribute a single creative work that is part GPL and part closed-source.

Kudos for using an existing license and asking this question instead of making up your own license!


问:
Which approach to follow for developing applications targeting multiple platforms?
For applications targeting multiple platforms, I see mainly two development approaches-

Go for some JAVA-like development platform. Have one code solution and let the intermediate runtime handle different platforms. If something goes wrong in any platform, tweak the code a bit. But keep it same for all.

Make modular code separating core logic and UI. Develop separate UIs for respective platforms which will be calling same core libraries. Build the application separately for each of the target platforms.

So, which one to follow? I know, the answer will start with "It depends". But I want to hear your opinions on these approaches and the factors to be considered to choose any of them.

答: Go for HTML5. Any platform with a HTML5 browser can run your application.  Although HTML5 is not ready for big time yet, the Web application approach is.</p>


答: These days (at least for Java) it seems like sooner or later all programs add a web service (SOAP or Ajax or both) sooner or later.  So in general yes think that way but a web service front end is more likely than a command line if you want a better mental metaphor...  and a more likely one.  </p>


问:
How to explain that sample size does not influence project length
We have big enterprise projects they normally involve copying data from a source database to a destination database and then setting up a number of additional applications that sync this data etc.

The last project contained 250,000 items (rows of data). The next project will only contain 4,000 items. Project managers / business people believe the project should be 1/10 the time to complete because its only a fraction of the size of the last project.

What is a good analogy I can use to explain that writing code to transfer data from one system to another takes the same amount regardless of the number items - writing it for 1 item or for 100,000,000 will take roughly the same amount of time from a programming point of view.

答:
Maybe a telephone?  Your customer wants a custom-made phone. If he makes 0 calls per day or 100 calls per day it would take the same amount of time to create his phone.

The data a phone transmits is analogous to the data copied by your program.

Your managers seem to confuse dev-time with the actual run-time of the program. But their misunderstanding may be different.  They may assume that there are fewer "fields" involved. Not just fewer data records. If there are 100000 individual data fields it would be a massive dev effort compared to only 10 fields. More mapping work from system to system. In this case they may actually be correct, but there is still some constant overhead involved and you can't simply divide by the number of fields to get the time.


答:
Notice the phrase again: "[It']s a good idea to be able to easily replace the regular user interface classes by a command line one". It doesn't mean you have to write a CLI, just that you could do it easily.

So, what it says is that your UI should be decoupled from the rest of the code.


问:
Is it typical for a unit test suite to be larger than the code it tests?

Possible Duplicate:

  What is a normal “functional lines of code” to “test lines of code” ratio?

I've found that more often than not, when you write lots of unit tests, and have good coverage (80% or so), the test suite ends up being larger than the code itself.

Do my observations match that of everyone else?

I've also found that more often than not, a the larger the test suite, the harder it is to maintain the test suite.  What ends up happening is that the test suite rots away as for every X lines you change you make to the code, X^2 lines need to change in the test suite.

Is this an attribute of unit test suites in general?  Or am I just working on crappy unit test suites?

答:
the test suite ends up being larger than the code itself.

Do my observations match that of everyone else?

If you mean that the test suite as a whole has more LoC than all your application's code, then no, I haven't experienced that. Maybe because I've worked on projects with lots of unit tests, not many integration tests, and zero automated UI tests. The UI can really be huge in terms of lines of code, so I guess you really have to have comprehensive UI tests in order for the size of the test code base to exceed the total size of the production code base.

If you mean your average test fixture has more LoC than the module it tests, it's possible, especially if your production code has a lot of short, public methods.
However, it could also mean that you're testing too many things. Stuff like accessors and code constructs that contain no logic are generally considered not worth testing.

the larger the test suite, the harder it is to maintain the test
  suite.

I guess there's not a lot you can do about that mathematical fact. You can't expect your test suite to come at no cost, and the cost will naturally increase with its size. There are things you can do about overly fragile tests though. See http://xunitpatterns.com/Fragile%20Test.html.


答:
It depends and when I say it depends, it's not just a matter of having a couple edge cases, but it is very dependent upon the application and the target audience. Assuming that we are eliminating games from the equation then there is still a wide array of applications that you may be writing where a command like is unlikely or never going to be implemented. Off the top of my head, any application targeting a mobile (e.g. iOS, Android, etc.) environment is likely going to fall under this heading.

With that in mind, in the general software space, any application that is heavily dependent upon visualization (e.g. PowerPoint, Maya, etc.) is unlikely to ever see a command line replacement be implemented. In fact, in the case of graphics software such as Maya, it is arguable a good mental exercise to determine how a full and proper command line version would work and it may not be possible to do so from a user standpoint. Thus, it is clear that there are definitively common applications that can be encountered where a command like interface is unlikely to ever be seen, or desirable even if scripting of the application may be desirable.

Next, if we look at the suggesting form the standpoint of general software architecture, I can see where it would make sense to periodically ask yourself "How can I access this feature without the user interface?" In general, if there is no way to do it and it is not directly interacting with the user (e.g. gesture input) then you likely have a situation where the overall architecture needs to be improved. In order to allow for ease of testing you are going to want to be able to directly access command without going through the user interface, even though they may not be invoked though a command line. This generally means that a solid API needs to be in place and theoretically a good API should allow for access via command line or user interface. Furthermore, in the long run, you will save yourself time if you need to add a new user interface to the application.

At the end of the day, I think that what the suggestion is trying to get at makes sense (i.e. Have a good API and build your user interface off of that) but the word selection might have been a bit better to get the point across.


答:
You have to create an API that exposes methods than can be made into SOAP services.

Other apps can use your functionality.

Your current app can continue to exist although I'd recommend to refactor it to call the API functions ( no SOA necessary here ).

SOA is for sharing useful business logic between applications. But it doesn't mean that the app that originated the bussiness logic has to use SOA to use it's own business logic. That app could use SOA to consume others' bussiness logic.


问:
Why is Java the lingua franca at so many institutions?
EDIT: This question at first seems to be bashing Java, and I guess at this point it is a bit. However, the bigger point I am trying to make is why any one single language is chosen as the one end all be all solution to all problems. Java happens to be the one that's used so that's the one I had to beat on here, but I'm not intentionality ripping Java a new one :)

I don't like Java in most academic settings. I'm not saying the language itself is bad -- it has several extremely desirable aspects, most importantly the ability to run without recompilation on most any platform. Nothing wrong with using the language for Your Next App ^TM. (Not something I would personally do, but that's more because I have less experience with it, rather than it's design being poor)

I think it is a waste that high level CS courses are taught using Java as a language. Too many of my co-students cannot program worth a damn, because they don't know how to work in a non-garbage-collected world. They don't fundamentally understand the machines they are programming for. When someone can work outside of a garbage collected world, they can work inside of one, but not vice versa. GC is a tool, not a crutch. But the way it is used to teach computer science students is a as a crutch.

Computer science should not teach an entire suite of courses tailored to a single language. Students leave with the idea that all good design is idiomatic Java design, and that Object Oriented Design is the ONE TRUE WAY THAT IS THE ONLY WAY THINGS CAN BE DONE. Other languages, at least one of them not being a garbage collected language, should be used in teaching, in order to give the graduate a better understanding of the machines.

It is an embarrassment that somebody with a PHD in CS from a respected institution cannot program their way out of a paper bag.

What's worse, is that when I talk to those CS professors who actually do understand how things operate, they share feelings like this, that we're doing a disservice to our students by doing everything in Java. (Note that the above would be the same if I replaced it with any other language, generally using a single language is the problem, not Java itself)

In total, I feel I can no longer respect any kind of degree at all -- when I can't see those around me able to program their way out of fizzbuzz problems.

Why/how did it get to be this way?

答:
Are universities really doing this? Or is this just a perception people get when they get a bad job interview candidate?

I got my CS degree 4 years ago and while Java was used in the intro classes, it was not particularly emphasized after that. Off the top of my head, the core required courses required you to learn Java, C, C++, SML (functional programming language), assembly, matlab and CAST (circuit description language). This doesn't take into account all the math and theoretical CS courses and of course, the half dozen elective CS courses that would have exposed you to a whole bunch more. From talking with friends at a number of different universities, it didn't sound like what they were doing was much different.

If there are universities solely teaching Java, then that is indeed a tragedy. Not because Java is bad, but because it is just one tool of many that should be available to a programmer. A developer who only knows Java is equivalent to a carpenter who only knows how to use a hammer. However, I have trouble believing that's really the case, at least for respected universities. I suspect that this is just the perception from seeing bad candidates and blaming the school for the candidates' incompetence rather than the candidate's own lack of drive/motivation/curiosity/professionalism/etc.


问:
Is it worth converting a Django project to Rails?
I have a project I shelved a while back- it was essentially a working web app built in django but I stopped working on it to work on something else.

I plan on starting it up again in my spare time, but I'm wondering if it's worth converting a django project with about 5kloc to Rails. I'm considering this because I've been told that it'll be easier for other people to work on and easier to work on myself.

I don't have any ruby or rails experience: is it worth learning ruby, rails and then converting my django project to Rails? I understand it's a bit of a loaded / language war kind of question but would appreciate any input.

答: Five KLOC isn't very much.  If you would rather continue with Rails, go ahead.  It will only take you a couple of days.  You will almost certainly make improvements as you go, so when you finish you will have made some engineering progress.  If the spirit moves you, then do it. </p>


问:
Is it easier to write robust code in compiled, strictly-typed languages?
I'd like to read the opinion of experts on whether compiled, strictly-typed languages help programmers write robust code easier, having their backs, checking for type mismatches, and in general, catching flaws in compile time that otherwise would be discovered in runtime ?

Has unit testing in loosely typed, interpreted languages need to be more thorough because test cases need to assess things that in a compiled languages wouldn't simply compile ?

Need the programer in compiled, strictly-typed need to write less code since he/she doesn't have to constantly check for correct types ( instance of operator ) since the compiler catches those things ( the same applying to misspelled variable names or uninitiated variables ) ?

NOTE: by strictly typed language I mean languages that force you to declare variables and assign a type to them in order to be able to use them, and once a variable is declared, you cannot change its type or assign incompatible type values.

```<code>int myInt = 0;
String myString = "";
myInt = myString; // this will not fly in a strictly typed language
myInte = 10;   // neither will this ( myInte variable doesn't exist )
</code>```

答:
Yes, type-safety leads to more robust code.  But at what cost?

You never find every bug in testing.  The earlier you find a bug, the cheaper it is to fix (fewer people involved, less communication, etc).  The cheapest way to fix a bug is to have your language or compiler prevent it from happening.

I had a client who had a standing bet for over a year, offering a free hamburger for finding an actual bug in my code.  Type safety helped make that possible.

In general, compilers or languages preventing bugs is a good thing, but it can be taken to an extreme.  XSLT does not allow you to update the value of a variable.  As a result, you have to use recursion to make a simple loop (I'm writing this in pig-java/pig-C because XSLT has awful syntax which I fail to remember):

```<code>function sumList(x) {
    if (x.length > 1) {
        return sumList(x.tail) + x.head;
    } else {
        return x.head;
    }
}
</code>```

There are benefits to this approach (few side effects), but this also forces fragmentation on the code where all kinds of things were broken off into separate little functions.  It was difficult to avoid doing things multiple times, and this led to all kinds of other bugs and slow performance that were worse than accidentally changing the value of a variable.

Back to type safety.  Usually, if I have a function washFabric(Fabric f) and I pass it a Cat instead of a Fabric, this is a simple error on my part.  When you have this hidden in layers of function calls, such a mistake is very easy to make and hard to test for.  When my code compiles in a type-safe language, I know I didn't make this kind of error.  For this reason, I find type-safety a good trade-off between speed of slapping something together that works, and being sure it won't break.

Type safety does slow you down.  In Ruby or perl, you can create a wash(f) method and throw a cat in the wash and either the cat comes out clean, or dead, or still dirty.  But in Java, you have to create a Washable interface and painstakingly define methods like soak(), addSoap(), agitate(), spin() and rinse() and think about what it means to be washable so that someone making a Cat class can study the Washable interface and decide whether a cat should be Washable or not.  That takes a lot of time and effort.

If you want a one-time use report written in an hour, then type safety will just slow you down.  But if you have a bunch of programmers working on a huge system that will last for years and has to be very fault tolerant, then you can pry type safety from my cold dead hands.  :-)

Body:
Yes, type-safety leads to more robust code.  But at what cost?

You never find every bug in testing.  The earlier you find a bug, the cheaper it is to fix (fewer people involved, less communication, etc).  The cheapest way to fix a bug is to have your language or compiler prevent it from happening.

I had a client who had a standing bet for over a year, offering a free hamburger for finding an actual bug in my code.  Type safety helped make that possible.

In general, compilers or languages preventing bugs is a good thing, but it can be taken to an extreme.  XSLT does not allow you to update the value of a variable.  As a result, you have to use recursion to make a simple loop (I'm writing this in pig-java/pig-C because XSLT has awful syntax which I fail to remember):

function sumList(x) {
    if (x.length > 1) {
        return sumList(x.tail) + x.head;
    } else {
        return x.head;
    }
}

There are benefits to this approach (few side effects), but this also forces fragmentation on the code where all kinds of things were broken off into separate little functions.  It was difficult to avoid doing things multiple times, and this led to all kinds of other bugs and slow performance that were worse than accidentally changing the value of a variable.

Back to type safety.  Usually, if I have a function washFabric(Fabric f) and I pass it a Cat instead of a Fabric, this is a simple error on my part.  When you have this hidden in layers of function calls, such a mistake is very easy to make and hard to test for.  When my code compiles in a type-safe language, I know I didn't make this kind of error.  For this reason, I find type-safety a good trade-off between speed of slapping something together that works, and being sure it won't break.

Type safety does slow you down.  In Ruby or perl, you can create a wash(f) method and throw a cat in the wash and either the cat comes out clean, or dead, or still dirty.  But in Java, you have to create a Washable interface and painstakingly define methods like soak(), addSoap(), agitate(), spin() and rinse() and think about what it means to be washable so that someone making a Cat class can study the Washable interface and decide whether a cat should be Washable or not.  That takes a lot of time and effort.

If you want a one-time use report written in an hour, then type safety will just slow you down.  But if you have a bunch of programmers working on a huge system that will last for years and has to be very fault tolerant, then you can pry type safety from my cold dead hands.  :-)


问:
Is it a good idea to design an architecture thinking that the User Interface classes can be replaced by a command line interface?
In Code Complete page 25, it's said that it's a good idea to be able to easily replace the regular user interface classes by a command line one.

Knowing its advantages for testing, what about the problems it may bring?

Will this extra work really pay off for web and mobile projects? What about small and medium projects; do the same rules apply?
What if it makes your design more complex?

答:
It depends on how useful the command line program would be.  Some things, like plotting a route on a map, or playing a 3-d game, just don't lend themselves to a command-line interface.  But other things, like system tools are much better from the command line than from a GUI, for the simple reason that they can be scripted.

Dr. Richard Hipp once said that his ideal GUI operating system was a blank desktop with an icon to open up command windows and another icon to open a web browser.  I feel almost the same way.  If it would be useful as a command-line program, and not too difficult to build that way, I would do it.  The GUI could be a completely separate program, maybe built by someone else!


问:
What does a good "definition of done" for a mature team look like?
When looking at examples of definitions of done in various sources, they usually include points like

code completed

unit tests run

code peer-reviewed or paired

code checked in

documentation updated

…

In our team, we have a similar list, but nobody ever looks at it because those points seem so blatantly obvious that it wouldn't occur to anyone to skip any of these steps. So we were wondering whether that's mainly a tool for teams transitioning to an agile process and whether we shouldn't just get rid of it.

On the other hand, lots of literature claims that all high-performing teams have a strong definition of done. This kind of hints that we might miss an opportunity to improve here.

So what are examples of strong definitions of done of a mature team? What kind of points do they include typically?

答:
This actually sounds like you are one lucky guy:

In our team, we have a similar list, but nobody ever looks at it
  because those points seem so blatantly obvious

Your team is already "mature" ;-). But there is always room for improvement!

To your question:

So what are examples of strong definitions of done of a mature team?
  What kind of points do they include typically?

On top of your list, you could add:

Various code quality metrics:
 - Instability, Abstraction
 - LOC vs DLOC (documented)
 - etc...

The rule of thumb could be that the metric should not get worse with your commit.
On top you could formulate a "done:withExcellence" if someone actually makes the metrics get way better. Although this (metrics getting better) is usually not part of development phases (new features) but refactoring phases.

In one of my past companies we had a definition of "done" that said that your metrics need to stay below certain thresholds, if you go above, you are not done yet. (Cyclomatic Complexity should never go above 15, unless you have a very very very good excuse, like complicated calcs.)

Same goes for Checkstyle type of violations, especially if you have a custom rule-set to check on your teams code-style. If you are in violation of the coding standard, your are not done yet.

Then you could not only execute UnitTest, you could measure code coverage. If not at least 50% are covered, you are not done. Although this is kind of a flaky defintion of done, since you should have tests for the core/main/critical methods, and not necessarily for 100% of your code base.

Oh yea... and if you have (you should) a CI server with automated branch integration... you are only done if your commit in the DEV Branch merged with the current LIVE-Branch and causes no errors either. (Unit Tests, etc.)

hmmm... that's all I can remember right know from past companies/projects, which hasn't been mentioned in your list.

I hope that gave you some ideas ;-)

Cheers,

anann


答:
The guidelines are there for everyone. In a mature team, as you mentioned, everyone is doing it, so it does not mean there is no place for it. Suppose, a new member joins, who has not been exposed to this methodology before. Having the structure in place, would be vital for him. He wouldn't have to bother other members, or wouldn't "forget" a deliverable.

In my opinion, List everything, including the obvious. Perhaps, have a "short cheat list" for non-obvious ones if it helps those who want a shorter list, but consider the case of new members hopping on.

It is an iterative process, every time you see something you can improve, add it in the definition of done. Overtime, you will develop a list which is relevant to your company. Anann has already mentioned some which are worthwhile.

Title: What does a good "definition of done" for a mature team look like?

Body:
When looking at examples of definitions of done in various sources, they usually include points like

code completed

unit tests run

code peer-reviewed or paired

code checked in

documentation updated

…

In our team, we have a similar list, but nobody ever looks at it because those points seem so blatantly obvious that it wouldn't occur to anyone to skip any of these steps. So we were wondering whether that's mainly a tool for teams transitioning to an agile process and whether we shouldn't just get rid of it.

On the other hand, lots of literature claims that all high-performing teams have a strong definition of done. This kind of hints that we might miss an opportunity to improve here.

So what are examples of strong definitions of done of a mature team? What kind of points do they include typically?


问:
Are all programming problems algorithm problems?
I like how "Introduction to Algorithms" by Cormen et al. conveys knowledge. One reason is that everything has to do with programming problems and the book is not implemented in any particular programming language. This language independency provides focus on the ideas in general.

So my question is, as it says in the title. Is every solveable programming problem solveable by thinking in this algorithmic fashion. No matter which language, field, etc ? If yes, give arguments, else, give arguments!

I have not implemeted many complex programs with GUI, AI, Graphics, etc ... But are these types of problems also a matter of thinking out good algorithms?

答:
Most programming problems are actually system administration problems.

That's kind of a flippant answer, but I've found this is true more often than one might expect. I don't know how many times I've encountered failures because DNS was misconfigured on the test machine, a stale process is still running that's hogging CPU/memory/ports, the program is running with the wrong user ID and thus has the wrong permissions, the disk was partitioned incorrectly and so space ran out, the wrong version of the configuration file was installed, etc.

Getting the algorithms right is usually only a small part of the problem. The rest of the problem is putting the program to work solving real problems in the real world.


答:
I would think that yes, all programming problems are solvable by thinking in an algorithmic fashion. After all an algorithm is just a set of instructions that tells the computer what to do.

Taking some of the examples from above

For example, GUIs are often straightforward to "program", but the actual problem involved is to have a good design (from a useability point of view, not just the graphical appearance).

In terms of the programming and even design that will know patterns/rules that lead to effective GUI designs that are user friendly and efficient. These rules be reduced to an algorithm that if followed should help produce a user friendly GUI. In fact the actual steps of placing the controls on the GUI can also be reduced to an algorithm

To give you an example, a programming problem I have right now is that I have to deal with a legacy spaghetti source code by adding unit tests, then refactoring it. It also involves adding comments in the right places, normalize the capitalization of names, etc. It has nothing or few to do with algorithms.

But the manner in which you approach adding unit tests can be described by an algorithm such as

Identify new Unit Test

Write Unit Test

Apply Capitalisation Normalisation Algorithm

Apply Comments algorithm

Example: internationalization
  This a perfect example of an algorithm solution. As its simplest you are looking up a known word in a dictionary and replacing with the different language form. (Of course real life involves sentences and context and the algorithm may involve steps to verify with native speakers but the basics hold true)

The issue with most of the Yes answers is that people are thinking of algorithms in terms of QuickSort, Bubble sort instead of a set of instructions that reduces a verbose vague description of a problem to a set of clearly defined logic/rules.


答:
Just because the points are blatantly obvious doesn't mean that people will always carry them out. Let's take two other examples - pilots and surgeons. A cockpit of a commercial airliner or an operating room has multiple people, with a good deal of education and experience between them. However, things still go wrong - steps are done out of order, something is forgotten, something is done incorrectly. I've seen a number of sources site that a large number (up to 70%) of aircraft incidents attributed to pilot error could have been prevented with a checklist. In the medical world, up to 29% of malpractice lawsuits in the Netherlands could have been prevented with the use of a checklist, according to researchers. Although these people have been trained, and in hindsight would probably easily identify what they did wrong, something happened that caused them to lapse. I haven't read it yet, but The Checklist Manifesto is supposed to be relevant. It's written from a medical profession, but the advantages of making a checklist or flowchart visible as a reminder of what to do are applicable to any profession.

So, step one would be to create a list of things that are part of your definition of done and make it visible. It doesn't matter how obvious that task is, if it needs to be complete for the story to be considered done, it needs to be on that list. The list needs to be somewhere visible to the team. Note that it doesn't have to be anything fancy or formal - perhaps just a series of questions that everyone needs to ask themselves before a story can be called done.

Step two is to decide what goes on that checklist for your definition of done. Everything that you need to do to complete a task should be specific, unambiguous, acceptable, and realistic. It also needs to be within a context of time for consideration of done. For example, you don't need to include "modify code" or "modify design" in a definition of done - if you didn't need to change a work product, there was no need for the story.

I would suspect that a good checklist to serve as a basis for a definition of done would be:

Have all associated unit, integration, system, and acceptance tests been updated?

Has the work product been transformed into its releasable form? For example, code built, documentation in the exportable file format, etc.

Have all associated work products been peer-reviewed? Examples of work products include source code (production and test), comments, design documents, test procedures, and user manuals.

Have all associated tests (at all levels of testing) been executed and pass?

Has the code been merged into the integration repository?

Of course, you'll need to come up with a good definition of done that includes any other activities that your team and your customer feel add value. If it's on the checklist, it should be something that needs to be done to add value to someone (the team, the customer, the user). By clearly enumerating what you do, you can also identify and eliminate extraneous activities to improve the process.


问:
How to visually document interactive user interfaces for fast consumption
I'm writing documentation for some interactive Ajax user interface but instead of writing everything in words I would rather provide diagrams that are faster consumed than whole paragraphs of text. I did provide page navigation flow diagram but that's very high level before you drill down to individual pages and their inner workings.

Example

Suppose I have to document a typical search panel:

is collapsed by default and can be expanded on click

has basic search fields that provide basic search criteria over my model entity

has advanced fields as well that show when one clicks a particular link which expands search with additional fields

has two actions Search and Reset that are pretty much self explanatory, but have particular behaviours attached to them

I know you will say that this already is documentation, but it's usually not this simple and trivial. Search panel is just an example.

I can see that most of my interfaces (or interface components) need two types of documentation:

properties related to contained controls (i.e. drop down field with these and those values of which that particular one is selected by default)

actions and behaviours that describe what happens when user interacts with controls related to those properties

What would be the best diagram or documentation format to describe these kind of interactive interfaces so that it's easy and quick to consume by implementers?

答:
The best documentation I've been given to implement was drawn as wireframes with notes.  Each page of the documentation was one wireframe with as many notes as necessary.  Each state of any element that needed further explanation spawned another page.  For example, a standard drop-down is obvious, but an expanding menu would get notes about sliding effects and what other page of the document it goes to on click of each element.

Advantages of this type of document:

It can include as much or as little detail as you like.

It can be very helpful to non-developers.  Some I've seen included margin spacing, etc. for the designers and an appendix for color choices.

Disadvantages:

It can be cumbersome - potentially many document pages to explain a single web page

Not visually automated, as a prototype or slide show might be

I'll add this was the preferred style for at least a few user interface experts I've worked with.


答:
Not really an analogy, but I still believe a good way to deal with this argument: demonstrate there is a fatal flaw in it.

Your previous project included (from what I get) copying data with some modifications on it.

If I got it right, that's something a team of, say, 100 accountants can do in a matter of a few months. Then why did they throw software developers at the problem?

Because the software you created doesn't care whether it will process 10 or 10 million pieces of data (not exactly, but I doubt your managers care for O(n) complexity). Thus, it was probably cheaper, faster and cleaner (less error-prone process).

If you're more radical, you might even suggest that if they don't like how fast the software team works, they can always call in the accountants to do the work by hand.

This made your managers' lives much easier while you were developing the last project, and now, when they have to apply the same logic to figure out the next piece of software doesn't care either if it's going to work on 10 million or 4 000 rows, they suddenly forget about it.

I think in your case the managers are simply playing an estimation game and are trying to force the team to work faster, by pointing out the difference between 4000 and 250000 and hoping for some 'guilt'. I could be wrong, but I've seen this done before.

It's a terrible way to manage a team of programmers (actually any type of creative team) and it doesn't help anyone.

Title: How to explain that sample size does not influence project length

Body:
We have big enterprise projects they normally involve copying data from a source database to a destination database and then setting up a number of additional applications that sync this data etc.

The last project contained 250,000 items (rows of data). The next project will only contain 4,000 items. Project managers / business people believe the project should be 1/10 the time to complete because its only a fraction of the size of the last project.

What is a good analogy I can use to explain that writing code to transfer data from one system to another takes the same amount regardless of the number items - writing it for 1 item or for 100,000,000 will take roughly the same amount of time from a programming point of view.


答:
In a TDD/BDD environment, the definition of "done" (technically "Code Complete", as Matt S's definition of "really 'done'" is correct) is pretty simple:

All automated tests pass (those automated tests should include new ones written for the story in question to verify the required functionality or behavior exists and works)

Code review passed (at least one senior dev on the team is content to let your work become part of the codebase, and that you didn't "cheat" or "hack" your way through the story)

Commit successful (including the build bot passing all automated tests, code coverage metrics, style cop checks, etc)

At this point, you can move on. These three points are critical, but they're all that the average team coder must be concerned with. Written or unwritten, they are inviolable in a TDD environment. Documentation, when the coders are the ones doing the documenting, is an additional point. In my last Agile team, documentation was handled by the BAs/QAs; they knew what the client wanted, had run the UATs, and thus were best able to document the new feature in a way that was meaningful to the client, so documentation was not part of the coder's definition of "done", though it was part of the team's definition.


问:
SQL Server Management Studio Show last executed query
I am looking for a way for SQL Server Management studio to show me the last SQL query that was run. For example, when I make modifications to a table in the designer mode, I will eventually want to make the same changes to the production DB without recreating the entire table. I'm looking for functionality similar to PHPMyAdmin for MySQL which tells you the last query ran and the results of the query at the top of the page after the modifications are complete.</p>

答: WHy are you not making the changes through scripts and committing them to source control like any other code? Then you know what is supposed to be pushed to prod.</p>


答:
This is generally a good idea, yes.

By-metaphor, people may think of this as a form of RESTful design.   .... it's not, per se, as a typical (G)UI could involve complex multi-stage transactions like account creation.

```<code>Better that one stays away from multi-stage complexity through shopping-cart-like models for transactional setup.
</code>```

I once programmed a drag'n'drop UI metaphor in the browser.  Very complex interaction rules on the back-end to make the UX feel natural.  I solved this by making the site an API and the GUI was a full app that generated events upon action.  A module caught these events and, on a timer, bundled them into 'API calls' (for network efficiency).

The result was a completely RESTful core system.  The second upshot was that I had an interface for 3rd parties, that I could expose using affiliation profiles as per the business model.

Body:
This is generally a good idea, yes.

By-metaphor, people may think of this as a form of RESTful design.   .... it's not, per se, as a typical (G)UI could involve complex multi-stage transactions like account creation.

Better that one stays away from multi-stage complexity through shopping-cart-like models for transactional setup.

I once programmed a drag'n'drop UI metaphor in the browser.  Very complex interaction rules on the back-end to make the UX feel natural.  I solved this by making the site an API and the GUI was a full app that generated events upon action.  A module caught these events and, on a timer, bundled them into 'API calls' (for network efficiency).

The result was a completely RESTful core system.  The second upshot was that I had an interface for 3rd parties, that I could expose using affiliation profiles as per the business model.


答:
Building on what Mason Wheeler said, being able to interact with an application via a command-line makes it very easy to automate tasks.

This is particularly useful in testing.

To give a practical example, if I want to run automated tests on an application, I may want to install the application automatically. To do this, I might pass in the following parameters, "myApplication.exe /silentinstall".

I might program it so that when I specify this command-line switch, an install is performed silently in the background, without the GUI installer. Any input to the installer (such as the install directory) could be picked up from an XML file perhaps.

Take another example. Microsoft Test Manager GUI (comes with Visual Studio) allows users to launch test runs from its GUI interface, but also provides a command-line interface to do the same thing (using a combination of command-line switches and inputs). This means I can whip together a PowerShell or DOS script to automate the launching of tests, and I could then create a scheduled task so that the scripts are run every night, perhaps.

Some applications have command-line switches which specify for an application to open with certain options (for example, I might use '/maximize' to open the application in a maximized window).

There are plenty of scenarios where a command-line interface could come in use. These are just some examples.


问:
What made object oriented programming successful?
What is that feature according to you that has made object oriented programming so much successful ?

Message Passing

Inheritance

Polymorphism

Encapsulation

Or some other feature that you may like to introduce.

Also I would like to know that what is the connection between Abstract Data type and Object Oriented programming?

答:
My top three features.
Object Composition - allowing objects to collaborate.
Polymorphism - supports dynamic behaviors at runtime.
Inheritance - by reusing code and modifying behavior through methods overriding.

ADT - you can have that even in non object-oriented languages like Pascal.  A stack or a queue are examples of ADT.


答:
It depends on why you want to pick the project back up.

If you are more interested and excited about adding features or functionality to your app, then leave it in python/django, and concentrate on the functionality.

If you are more interested in learning something new, like RoR, then start fresh with a new, simple project, and then figure out if you want to port your app.

Title: Is it worth converting a Django project to Rails?

Body:
I have a project I shelved a while back- it was essentially a working web app built in django but I stopped working on it to work on something else.

I plan on starting it up again in my spare time, but I'm wondering if it's worth converting a django project with about 5kloc to Rails. I'm considering this because I've been told that it'll be easier for other people to work on and easier to work on myself.

I don't have any ruby or rails experience: is it worth learning ruby, rails and then converting my django project to Rails? I understand it's a bit of a loaded / language war kind of question but would appreciate any input.


答:
First of all we are talking about GPL, not AGPL.

If you do not distribute a GPL'd the application, if you run it on a server, you don't have to provide the source code. There is AGPL for that. GPL is all about distribution.

From Drupal FAQ:

Do I have to give the code for my web site to anyone who visits it?

No. The GPL does not consider viewing a web site to count as
  "distributing", so you are not required to share the code running on
  your server.http://drupal.org/licensing/faq/#q6

Please note that Drupal is licensed under GPL and contains js files (a lot).

From GNU:

The purpose of the GNU Affero GPL is to prevent a problem that affects
  developers of free programs that are often used on servers.

Suppose you develop and release a free program under the ordinary GNU
  GPL. If developer D modifies the program and releases it, the GPL
  requires him to distribute his version under the GPL too. Thus, if you
  get a copy of his version, you are free to incorporate some or all of
  his changes into your own version.

But suppose the program is mainly useful on servers. When D modifies
  the program, he might very likely run it on his own server and never
  release copies. Then you would never get a copy of the source code of
  his version, so you would never have the chance to include his changes
  in your version. You may not like that outcome.

Using the GNU Affero GPL avoids that outcome. If D runs his version on
  a server that everyone can use, you too can use it. Assuming he has
  followed the license requirement to let the server's users download
  the source code of his version, you can do so, and then you can
  incorporate his changes into your version. (If he hasn't followed it,
  you have your lawyer complain to him.)
  Source: http://www.gnu.org/licenses/why-affero-gpl.html


答:
Being able to reuse functionality under different interfaces (e.g. GUI vs CLI vs REST) is not always necessary but nice to have and enable serendipitous reuse for a system, as other people find new ways to interact with it.

This has a few drawbacks that need to be weighted:

It'll require additional abstraction layers (sometimes even tiers). While having these layers is good engineering practice they have an additional cost in development, understanding that may not lead to reduce effort in other areas (e.g. maintenance, reuse, testing) so it's worth to ponder a bit about it.

Flow that's optimal for a medium may be awful for others. If the functionality was designed to support a GUI it may be too chatty for the web. Not all functionality is worthwhile in every medium.

There's a trap in trying to define a generic converter between services and user interface, so one can define the service contract and derive automatically (or as much as possible) the UI for all mediums. Many projects wasted too much effort trying to build such frameworks and adding every possible customization to it as the requirements changed.

Having said that, in my experience implementing such layers always ended up paying the effort. In a couple of cases I managed to deploy systems on time because we ended up having to swap media (e.g. from Web Services integration to UI) a few weeks before the due date.


答:
As i like to describe it data has 2 dimensions length and width.
Length is the number of records, width is the total number of columns across all tables

Now when you want to import data it is like getting a block through a hole.  You need to make a hole big enough for the smallest dimension, and then carry the block through

now with 10 million and 10 thousand the smallest dimension is still the width.  So it is the width that decides how long it takes to make the hole.

TO complete the metaphor, ff it is the length that is smaller you would just type the data in manually


答:
I think inheritance is the most important point of OOP.

[from game development] You can create something like a Drawable class, with rendering methods and attributes, and create a Spaceship and Planet class, which inherits from Drawable. Take all objects from those [and other Sprite child], throw in a drawableObjArray and just call the draw method for every object. You just need to know that it's an Drawable.

Title: What made object oriented programming successful?

Body:
What is that feature according to you that has made object oriented programming so much successful ?

Message Passing

Inheritance

Polymorphism

Encapsulation

Or some other feature that you may like to introduce.

Also I would like to know that what is the connection between Abstract Data type and Object Oriented programming?


问:
Experiments correlating code metrics to bug density
I'm wondering if someone has done some experiments correlating code metrics (SLOC, Cyclomatic Complexity, etc) with bug density in Object Oriented applications.

I'm not looking for experiments that only prove or disprove a correlation, but on both. I'm not trying to find a silver bullet as I believe that the bug density of a project might correlate to one or more metrics for a given project or team and the correlation can change during the lifetime of the project / team.

My goal is to

Measure all interesting metrics for 2-3 months (we already have quite a few from sonar).

Find one metric that correlates with the number of new bugs.

Do a root-cause analysis to check why this happens (e.g. Do we lack a certain design skill?).

Improve the skill and measure change for a couple of itereations.

Rinse and repeat from 2.

If you don't have any experience on this, but remember seeing a paper / blog on this subject, I would appreciate if you can share it.

So far I've found the following links with some information about this subject

Do Bugs Reside in Complex Code? - just the slides from a presentation.

Changes and Bugs: Mining and Predicting Development Activities - Just slides frmm a presentation. Bottom line the more dependencies, the higher the chances of bugs (I think this is quite a general rule).

Failure is a four-letter word - A parady about the correlation between bugs and metrics.

答:
In the book Code Complete, p.457, Steve McConnell says that "control-flow complexity is important because it has been correlated with low reliability and and frequent errors". He then mentions a few references that support that correlation, including McCabe himself (who is credited with having developed the cyclomatic complexity metric). Most of these pre-date the widespread use of object-oriented languages, but as this metric applies to methods within those languages, the references might be what you are looking for.

Those references are:

McCabe, Tom. 1976. "A Complexity Measure." IEEE Transactions on Software
Engineering, SE-2, no. 4 (December): 308-20

Shen, Vincent Y., et al. 1985. "Identifying Error-Prone Software--An Empirical Study." IEEE Transactions on Software Engineering SE-11, no.4 (April): 317-24.

Ward, William T. 1989. "Software Defect Prevention Using McCabe's Complexity Metric." Hewlett-Packard Journal, April, 64-68.

From my own experience, McCabe's metric, as it can be calculated by a program on many code sections, is useful in finding methods and functions that are overcomplicated and that have a high probability of containing errors. Although I have not calculated, the distribution of errors within high-cyclomatic complexity functions versus low-cyclomatic complexity functions, investigating those functions has allowed me to discover overlooked programming errors.


问:
When is a BIG Rewrite the answer?
Just read the question about the Big Rewrites and I remembered a question that I've been wanting answered myself.

I have a horrible project passed down to me, written in old Java, using Struts 1.0, tables with inconsistent relationships, or no relationships at all and even tables without primary keys or fields meant to be primary keys but aren't unique at all. Somehow most of the app "just works". Most of the pages are reused (copy pasted code) and hard-coded. Everyone who's ever worked on the project has cursed it in one form or the other.

Now I had long considered to propose to upper management a total rewrite of this horrendous application.  I'm slowly attempting to on personal time but I really feel that this deserves some dedicated resources to make it happen. Having read the articles on big rewrites I'm having second thoughts. And that's not good when I want to convince my superiors to support my rewrite. (I work in a fairly small company so the proposal has the possibility of being approved)

TL;DR
When is a big rewrite the answer and what arguments can you use to support it?

答:
This graphic could help, it's a function of code base quality and business value of the application:

The chart pretends to be a guide on when a re-engineering of legacy software is justified and when it's not. For example, if the software has high business value and the quality of the code is poor, then a re-engineering is justified.

Title: When is a BIG Rewrite the answer?


答:
No. Terrible bit of advice.

It's a bit yagni (You aren't going to need it).

Exposing a command line interface is not the same as structuring your app in a way that supports unit testing, or complies with any part of SOLID, or any programming practice I'd recommend.

It doesn't work for any UI that just wouldn't suit a command line interface. MS Paint is a really simple app, but how, in any situation, would you see a benefit to being able to control it from a command line?

It wouldn't help you implement scripting. It would actually hinder any progress in that direction.

The only positive thing is it appeared on page 25, so at least you get a warning that the rest of the book might be, ... smelly. I read it a long time ago and didn't like it, so I am biased.


答:
Don't use an analogy. Just explain it.

For a very small number of items (10?) it's cheapest to manually convert. Don't write a program at all.

For a small number of items (100?) it will be worth writing a program. You may be able to make savings by ignoring some permutations of the data that are theoretically possible, but don't appear in practise in the small dataset. Or appear in such small numbers that the program can reject them, and they can be converted manually. It's feasible to run quick analyses on the data to check whether corner cases actually appear in the data. If they don't appear, they can be ignored.

Once you pass this point, the actual size of the data has no impact. You need to write a serious program that can handle any possible input. The program can handle 1,000 items or 100,000. It just takes longer to run.

Education is better than talking down :)


答:
One advantage is that you will be forced to think about the flow of the UI from the user perspective. (What am I trying to achieve? What context do I need to set up? Given that context, how do I achieve the goal?)

There's a big difference between "create bank account" and "write ms word document". Even if you don't build a CLI, it may add value just to consider the "CLI context" needed. Models don't just live in the business object model!


问:
Best approach for writing a chess engine?
I'm a chess enthusiast and a programmer. I recently decided to start making a chess engine using my chess and programming knowledge. So here's my question:

What language (I'm familiar with Java, C++ and Python) and methodology should I adapt while writing a chess engine?

A little guidance would be much appreciated.

Edit:

So I decided to make it in JavaScript. I download this Chess UI from github and now I'm all set! My first step would be to write legal moves for it. So can anybody point me in the right direction? (I'm new to jQuery but have alot of programming experience).

P.S: I'm not trying to make a very efficient engine (I know its way too difficult), I just want to get familiar with the process and learn some new techniques along the way.

答:
I actually have written a chess engine.  Prepare yourself for both a treat and a nightmare.  When my friends and I did it, it was in a timed programming contest and the language we decided to go with was Java.  I feel Java or C is your best choice, but I see that you've decided to go with Javascript.  I can't really knock it cause I'm unfamiliar with it.

The main problem here will be that there are just so many move/win scenarios with every piece that you need to account for, so I would recommend that you write out all these possible situations for each piece before you actually begin coding.  Just jumping in without planning will turn this fun project into a repetitive chore.  But that's really the main thing.  Just plan outside of code first and make sure you get every scenario for one piece at a time.

Good Luck


问:
Tools for modelling data and workflows using structured text files
Consider a case when I want to try some idea of an application. But I want to avoid investing a lot of effort in coding UI/work flows/database schema etc before I see that it's going to be useful to me (as example of potential user). My idea is stay lightweight and put all the data in text files. So the components could be following:

Domain objects are represented by text files or their fragments

Domain objects are grouped by their type using directories

Structure the files using some both human- and machine-friendly format, e.g. YAML

Use some smart text editor (e.g. vim, emacs, rubymine) to edit and navigate those files

Use color schemes and macros/custom commands of the text editor to effectively manipulate those files

Use scripts (or a lightweight web framework like Sinatra) to try some business logic ideas on top of the data model

The question is: Are there tools or toolkits that support or can be adopted to this approach? Also any ideas, links to articles/other knowledge sources are very welcome.

And more specific question: What is the simplest way to index and update index of files with YAML files?

答:
I suppose it depends on your background, but in order to forget about the persistence layer I'd concentrate on the Objects I'd nedd and use some Object <--> Relational mapping component (e.g. hibernate) instead of relying on a direct integration with text files.

You can also work with text files via hibernate >> JDBC >> ODBC >> Text files as stated here (do not expect this to work fast).


答: The Data Hiding provided by Encapsulation.</p>