答: The Rexx language always produces an arithmetically correct answer. For example: 5/2 = 2.5. Rexx is a great language that has not been utilized enough. In theory, when a compiler can't determine what do you want, its better to do the correct math, however, this may not be efficient. Rexx also provides the // operator.</p>


问:
Implementing cache system in Java Web Application
I worked with JPA (Eclipselink implementation) and Hibernate. As I understand these two have great caching systems.

I am interested in caching in a Web application and in order to better understand the process I'm trying to implement something on my own.

Sadly, I cannot find any in depth documentation about this subject. I'm interested in things like high scalability, sharing memory on different machines and other important theoretical matters. Is there any tutorial or open project I could check out?

Thank you!

*LE: * I want to cache DB information in POJOs just like JPA or Eclipselink

答:
If you're attempting to cache static web pages, then using nginx or Apache is the way to go.  They'll server those files up faster then tomcat or jetty.  Pages you generate once per startup, you should consider generating those and then moving the page to nginx/Apache/etc as part of your deploy process.

If you're talking about pages that don't change that often, then you can create filter and use oscache, or other caching library to store the page in memory.  Make sure the filter you create is after whatever security you have, so your not serving cached pages to the world.

It's not covered much because you don't normally get enough return on the investment.  Most Web Aplication pages change to much to be good candidates for cacheing.

ContentLicense: CC BY-SA 3.0


问:
Why is OOP difficult?
When I started using an object-oriented language (Java), I pretty much just went "Cool" and started coding. I've never really thought about it until only recently after having read lots of questions about OOP. The general impression I get is that people struggle with it. Since I haven't thought of it as hard, and I wouldn't say I'm any genius, I'm thinking that I must have missed something or misunderstood it.

Why is OOP difficult to understand? Is it difficult to understand?

答: OOP requires the ability to think abstractly; a gift/curse that few people, even professional programmers, really have.</p>

ContentLicense: CC BY-SA 2.5

Title: Why is OOP difficult?


问:
Looking for a very memory-efficient way of finding exporting all relations in a family tree
Think of the question as a family tree, in the PS section I will explain what exactly it is but family tree is easier to imagine: so father, has kids, those kids may have more kids, those kids may have more kids, etc..

1- I don't have the whole information in memory to traverse them. With each method call and hitting the database I have just the father at some level and its kids.  See here is the high-level of the method that I have and need to some how use some good parts of it:

```<code>private void Foo(string fatherNode)
{
  // call some DB scripts and grab data you need to work with.
  int numberOfKids = // get it from the thing you populated from the DB call.
  for(int i = 1  to numberOfKids)
  {
     Node Child = // grab child[i] from the list we populated from DB calls
     //Add it to the treeView
  }
}
</code>```

Well this was working because it is a GUI application and with each you know "click" event we were really requesting just one level of info but Now I need a new functionality where I can click an Export button and it writes the WHOLE structure of this whole family tree to a XML file..( so you can expand those nodes and still see the family hierarchy)

2- There is a lot of data. One Father might have 400 children, each children might have 10 more children and each of those chilcren might have 500 more children...so I need to also be concerned about getting memory exceptions...

3- Recursion? can we really load ALL of this hierarchy to memory? I don't think so..remember the goal is to export it to a XML SO Maybe the efficient way is write a good algorithm that at each call writes one level of hierarchy to file and doesn't load the whole thing in memory...

But I am pulling my hair and banging my head on desk and can't crack the code and figure it out.. So what are your pseduo-code- suggestions... I am using C# by the way.

P.S: This is actually a Clinical Bioinformatics hierarchy, so you say Ok human genomes..ok now there 27000 genes under it, Ok now gets gene234 and let's say what are its children,...

答:
The straightforward solution

```<code>void Export(Node currentNode)
{
  WriteContentToXmlFile(currentNode); // delete this if you have only content for leafs
  int numberOfKids = currentNode.GetNumberOfChildren();
  if(numberOfKids==0)
  {
      // add "WriteContentToXmlFile(currentNode)" here if you have only content for leafs
      return;
  }
  WriteStartingTagForASubTreeIntoXmlFile(); // for example, <subtree>
  for(int i = 1  to numberOfKids)
  {
     Node child = currentNode.GetChild(i);  // gets it from your database
     Export(child);
     // leaving the scope frees "child" from memory
  }
  WriteEndingTagForASubTreeIntoXmlFile(); //  for example, </subtree>
}
</code>```

does never pull more nodes into main memory as the depth of the tree (the length of the longest path from root to a leaf). So, when you write your xml file sequentially to disk (and do not keep it in main memory), you won't run into problems, I guess.

You have to adapt this surely to the kind of XML structure you have in mind, but I hope you see that memory should not be much of a problem.

Body:
The straightforward solution

void Export(Node currentNode)
{
  WriteContentToXmlFile(currentNode); // delete this if you have only content for leafs
  int numberOfKids = currentNode.GetNumberOfChildren();
  if(numberOfKids==0)
  {
      // add "WriteContentToXmlFile(currentNode)" here if you have only content for leafs
      return;
  }
  WriteStartingTagForASubTreeIntoXmlFile(); // for example, <subtree>
  for(int i = 1  to numberOfKids)
  {
     Node child = currentNode.GetChild(i);  // gets it from your database
     Export(child);
     // leaving the scope frees "child" from memory
  }
  WriteEndingTagForASubTreeIntoXmlFile(); //  for example, </subtree>
}

does never pull more nodes into main memory as the depth of the tree (the length of the longest path from root to a leaf). So, when you write your xml file sequentially to disk (and do not keep it in main memory), you won't run into problems, I guess.

You have to adapt this surely to the kind of XML structure you have in mind, but I hope you see that memory should not be much of a problem.


问:
How to inspire an intern with programming?
The situation is this - we took an intern for a summer with a mind that if he will catch up during summer, we will keep him as a part time junior developer.

We took him after his first year in university, so his knowledge was way too low to be involved into real projects(actually he programmed only in university), so my task was to push as much stuff as I can to have him ready for joining real projects in September. As long as we are remote developing team, we gave him possibility to have its internship remotely, with flexible hours.

So two months passed and I'm not impressed with his progress. I gave several tasks to implement, access to learning resources, recommended start paths and so on, agreed that he will report every couple days, we had pair sessions from time to time, reviewed his code together and etc.

Anyway, it looks like he spent less time writing code than I expected and before I would say that he didn't performed well enough to join our team, I was thinking may be that is my fault, may be I was pushing too much stuff, that is important in real life projects (like unit testing, structuring code, database stuff, etc.) and not enough fun stuff, that would hook up him on programming and that is the reason he spent less time than I hoped.

So I have ~20 days left and I can use them to inspire him with programming, question is with what and how?

答:
I think there are a few problems on both ends.  It may be either of the scenarios you presented.

Scenario 1: Intern is underperforming

Working remote is the flag here.  It takes a very disciplined individual to actually work remotely.  With little experience, the intern may not have the combination of motivation and knowledge required to perform well remotely.  If you need a remote position, this intern is not for you.

Further, you mention the fun aspect.  I know it's more rare, but why not look for someone who thoroughly enjoys the tasks you're assigning them.  Honestly, SCRUM and TDD can be very fun, it just takes the right mindset.  Yes, they are few and far between, but there are people out there who actually enjoy learning new CS technologies and methodologies (=  Perhaps you need to continue your search.

Scenario 2: You are not mentoring close enough

I believe if this was the case, you'd know.  If the intern was motivated, he'd come to you with questions.  He would ask you when he doesn't understand something.  However, if he's writing bad code and you never said anything, then you might need to speak up more.  The deal is, with his experience, he's not going to know all the time if he's writing bad code.  So if you never spoke up when you saw issues, you only have yourself to blame.

Whatever the case, there is nothing wrong with deciding the intern is not right for the job or is not ready yet.  They are young and have much to learn.  They may need a few more years to just be a student before being really motivated to do professional work.  If you feel the problem is fixable, give it a shot over the next few weeks and try to keep the intern.  If not, you both had a summer of learning and that's that.

My personal opinion:  If I lay down guidelines and requirements and someone isn't meeting them, I'm not going to want to work with them further because I know and work with people who love what they do, even the CRUD, and who are noticeably motivated to make a great product.  Anyone like this is bound to succeed (=  In the end though, the one way to get to the bottom of the issue is to talk with the intern.  Try to have a progress meeting (or something) where you get to talk to the intern before making any decisions.


问:
Best way to remove list items from an existing record
Ok more of a conceptual question here:

Say I have an existing record of type Meeting. When I go to edit the meeting I have a listbox with all current meeting participants, and one with all employees. I then add a few employees from the master list and remove a couple from the meeting list. What is then the best approach to update my MeetingParticipant database with the new roster? The add records are no problem, but when I go to update, my callback doesn't know which items I have removed. Here are the solutions I've considered/implemented so far, but I'm hoping someone has a better answer :).

Immediately resolve the record deletion when the employee has been removed from the list. (this is what I usually implement, but I'd rather find a way where I can simply update the entire collection upon form submission)

Remove all MeetingParticipant records for the meeting and repopulate with the new list. (could possibly cause some referential integrity problems for employees who's status did not change)

Iterate through each of the MeetingParticipant records, searching the new list to see if it's still on the list or not. (seems like a lot of overkill)

If it matters, we're working w/in the .Net framework using MVC & LINQ.

答:
Just add kind of state property to your records.

Your record can potentially have at least 3 states

Added

Deleted

Changed

When your server/base/whatever.. recives the raw data-table from the UI, it just iterates over the collection and based on state of every record in that data-table executes appropriate operation.

Hope this helps.

OwnerDisplayName: Daniel Thompson

OwnerDisplayName: Tigran


答:
This is why I wish technologies like RDF/XML were popular on the .net platform..

I see two options:

If you need to write the tree depth first using XML:

You have identified your problem correctly.  The stack has the potential to get very large and each stack frame even larger in a deeply recursive tree.  The simple and slowest solution is to issue a database call for every node in the tree.  So, rather than getting all the children, simply get the node in question.  In a database backed model of your tree, when you get the Children of a Father, you don't have to store the whole level of children in memory at once.  Rather, you can retrieve and free each one as you "visit" it.  Does that make sense?  Obviously this will increase the number of database calls you need, but it is pretty memory efficient.

EDIT: This ^ is what Doc Brown describes in his answer..

I would start by not worrying about memory though and simply develop it as you described: a recursive export method where you obtain one level at a time and write the tree to XML depth first. Then rework it if you actually run into memory problems.  Despite the size of your data, I honestly don't think you'll have a problem exporting the whole tree.  If you do have out of memory issues, work at a solution.  You worst case, however, will be SPACE(N).

Use RDF properly (my recommendation):

Using RDF/XML, writing the data in constant space, SPACE(K), is trivial and basically solves all your problems.  But, RDF/XML is a highly underused technology because it has a high learning curve.  IF you're willing to switch to Java, there are numerous tools to do database backed RDF models, such as Apache's Jena, that will make this job incredibly easy.  If you are stuck on C#, but want to give RDF a shot, take a look at the C# SemWeb Library.

The idea is that you write the structure of the data along with the actual data itself to RDF/XML in a condensed n-triples format.  Since the structure is also exported, the data can be serialized k nodes at a time, thus in constant space.  This is the optimal solution especially if you have a graph that may not ever fit in a viable amount of memory (if the data set is really as big as you claim (; ).

Title: Looking for a very memory-efficient way of finding exporting all relations in a family tree

Body:
Think of the question as a family tree, in the PS section I will explain what exactly it is but family tree is easier to imagine: so father, has kids, those kids may have more kids, those kids may have more kids, etc..

1- I don't have the whole information in memory to traverse them. With each method call and hitting the database I have just the father at some level and its kids.  See here is the high-level of the method that I have and need to some how use some good parts of it:

```<code>private void Foo(string fatherNode)
{
  // call some DB scripts and grab data you need to work with.
  int numberOfKids = // get it from the thing you populated from the DB call.
  for(int i = 1  to numberOfKids)
  {
     Node Child = // grab child[i] from the list we populated from DB calls
     //Add it to the treeView
  }
}
</code>```

Well this was working because it is a GUI application and with each you know "click" event we were really requesting just one level of info but Now I need a new functionality where I can click an Export button and it writes the WHOLE structure of this whole family tree to a XML file..( so you can expand those nodes and still see the family hierarchy)

2- There is a lot of data. One Father might have 400 children, each children might have 10 more children and each of those chilcren might have 500 more children...so I need to also be concerned about getting memory exceptions...

3- Recursion? can we really load ALL of this hierarchy to memory? I don't think so..remember the goal is to export it to a XML SO Maybe the efficient way is write a good algorithm that at each call writes one level of hierarchy to file and doesn't load the whole thing in memory...

But I am pulling my hair and banging my head on desk and can't crack the code and figure it out.. So what are your pseduo-code- suggestions... I am using C# by the way.

P.S: This is actually a Clinical Bioinformatics hierarchy, so you say Ok human genomes..ok now there 27000 genes under it, Ok now gets gene234 and let's say what are its children,...


答:
I would recommend to start by letting him look over your shoulder as you code (more difficult to do remotely but with a good screen sharing program and voice software, it's possible). Take a feature from requirement to done all the while explaining to him what you're doing.

Repeat this a few times and on the next task, after you've broken ground on the code, give him the helm for a while. Be sure to provide hints when he gets stuck so he's not frustrated, but resist the temptation to take over right away. Pick a very specific step that you've probably repeated a few times prior so that you can reinforce the training.

Continue to let him take control with more frequency until he's finishing entire features on his own.

Just giving him a bunch of books and tasks to work on will cause overload.

Title: How to inspire an intern with programming?

Body:
The situation is this - we took an intern for a summer with a mind that if he will catch up during summer, we will keep him as a part time junior developer.

We took him after his first year in university, so his knowledge was way too low to be involved into real projects(actually he programmed only in university), so my task was to push as much stuff as I can to have him ready for joining real projects in September. As long as we are remote developing team, we gave him possibility to have its internship remotely, with flexible hours.

So two months passed and I'm not impressed with his progress. I gave several tasks to implement, access to learning resources, recommended start paths and so on, agreed that he will report every couple days, we had pair sessions from time to time, reviewed his code together and etc.

Anyway, it looks like he spent less time writing code than I expected and before I would say that he didn't performed well enough to join our team, I was thinking may be that is my fault, may be I was pushing too much stuff, that is important in real life projects (like unit testing, structuring code, database stuff, etc.) and not enough fun stuff, that would hook up him on programming and that is the reason he spent less time than I hoped.

So I have ~20 days left and I can use them to inspire him with programming, question is with what and how?


问:
What are the problems which I will face if all the classes I use are loosely coupled
Loosely coupled classes gives flexibility. If I understand it right, Event flow, Observer Pattern and Design Patterns like MVC focus on loose coupling.  So in this context I am aiming towards making a project where all the classes are loosely coupled.

So, for example I have a class A that uses  B:

then instead of a.b.doThis() ;

I will be going like this :

```<code>b.addEventListener( B.OnEventHappens, doThisInA ) ;
</code>```

So, my question is. If this sort of loosely coupled relationship throughout a project is a good thing to do? Would it make a robust project? Or is it not advisable to use it on the "Extreme" side?

答:
There are many kinds of coupling other than those you have described.  Anything that makes one piece of code change because another has changed is coupling.  All coupling can't be avoided because you will need to have different bits of code work together.

Coupling isn't the only concern you have anyway, so there are tradeoffs.  For example, using the Observer pattern makes the code hard to read or statically analyze, because there isn't a reasonable way to tell who is actually doing the observing.

If there were any practice that was clearly always the best choice in all circumstances you would basically never see it done any other way.


问:
How to implement a simulation pattern for a repository?
Let's say I have a repository of functions. These functions work with business objects within a database, CMS or other third party API. For example, my repository interacts with virtual files and documents in a document management system. I want to be able to implement a simulation mode in my repository such that when I execute commands, I want to see the result of it without it actually doing anything. This is to reduce the risk of someone executing a series of commands in my repository and doing something dangerous. I want them to first see the output and confirm before executing.

My question is, what are some good patterns to implement a simulation mode for a repository? I can think of a few off the top of my hat:

Wrap all business objects in another class, such that when you would call File.Delete, your actually calling the wrapper class and it checks in simulation mode is enabled. The problem is that many third party libraries and SDKs don't let you subclass their business objects. How would you pass in the the simulation mode (everytime an object is instantiated?).

Another option would be to implement a SimulatedRepository. However, I don't want to duplicate any existing code in the repository. Meaning, I don't want to simulate everything to the point that it does nothing, I only want to simulate create, update and delete commands, not the business logic. Perhaps I need to implement another layer in my application?

Suggestions would be appreciated. I also wonder if this design philosophy is popular in most enterprise environments and how its done. I would think that allowing administrators to run a simulation and measure results before actually executing them is vital in a mission critical scenario where you are working with another client's data.

答:
One method of achieving the results you're after (albeit it might be considered a little overkill) is by using an adapter pattern. You could feed whatever classes you're using an adapter implementation based on the state at execution time.

For example, you could have an adapter implementation that does nothing but print out what it's about to do. Another implementation could extend that adapter and add the functionality to actually execute the tasks.

OwnerDisplayName: szahn


答:
Can't you just use a good old fashioned k-ary tree? Load the entire tree into memory at start-up. Then implement some sort of event mechanism to update it if the DB changes after startup. You should be able to find it in any standard Data Structures and Algorithms book. I would use a linked list for the underlying storage mechanism, since you don't know how many children each node will have. Recursion should not be an issue for a linked list implementation, since you will essentially just have references to the first item in each list. If you are that worried about it, you can make sure you use tail recursion, or even better, implement your own stack to call the recursive functions on. However, without recursion, tree traversal will be too complicated to be good and maintainable code.

I am not sure how .NET's System.Text.Xml stuff stores the nodes. However, if it is array based, then that will not be as efficient (or fun?) as just implementing a tree yourself.

I would do something like (sorry for the C++ syntax, I don't remember generics for C# off of the top of my head).

```<code>template <typename E>
class TreeNode
{
public:
  E value();
  bool isLeaf();
  TreeNode* parent();
  TreeNode* lefmostChild();
  TreeNode* rightSibling();
  void insertFirst(TreeNode<E>*);
  void insertNext(TreeNode<E>*);
  void setValue(E&);
  ...

};

class FamilyMember
{
   //store all of your data for the family member in here.
};
</code>```

Then load up a Tree of FamilyMembers when the application starts. Then traversal will be a breeze (if you are good with recursion), and it will not be that bad on the stack. You can actually calculate this. Anyways, the important number is big-oh(n log* n) for the traversal. Memory is almost always irrelevant in this type of thing. If memory does become an issue, consider using a sequential tree implementation instead. Anyhow, n log*n is more than acceptable, and there are plenty of tree traversals that will do it that efficiently. Furthermore, you can improve this even more if you use the weighted union rule (though I think you will be fine). Once you have it in this structure, xml conversion will be trivial.

Body:
Can't you just use a good old fashioned k-ary tree? Load the entire tree into memory at start-up. Then implement some sort of event mechanism to update it if the DB changes after startup. You should be able to find it in any standard Data Structures and Algorithms book. I would use a linked list for the underlying storage mechanism, since you don't know how many children each node will have. Recursion should not be an issue for a linked list implementation, since you will essentially just have references to the first item in each list. If you are that worried about it, you can make sure you use tail recursion, or even better, implement your own stack to call the recursive functions on. However, without recursion, tree traversal will be too complicated to be good and maintainable code.

I am not sure how .NET's System.Text.Xml stuff stores the nodes. However, if it is array based, then that will not be as efficient (or fun?) as just implementing a tree yourself.

I would do something like (sorry for the C++ syntax, I don't remember generics for C# off of the top of my head).

template <typename E>
class TreeNode
{
public:
  E value();
  bool isLeaf();
  TreeNode* parent();
  TreeNode* lefmostChild();
  TreeNode* rightSibling();
  void insertFirst(TreeNode<E>*);
  void insertNext(TreeNode<E>*);
  void setValue(E&);
  ...

};

class FamilyMember
{
   //store all of your data for the family member in here.
};

Then load up a Tree of FamilyMembers when the application starts. Then traversal will be a breeze (if you are good with recursion), and it will not be that bad on the stack. You can actually calculate this. Anyways, the important number is big-oh(n log* n) for the traversal. Memory is almost always irrelevant in this type of thing. If memory does become an issue, consider using a sequential tree implementation instead. Anyhow, n log*n is more than acceptable, and there are plenty of tree traversals that will do it that efficiently. Furthermore, you can improve this even more if you use the weighted union rule (though I think you will be fine). Once you have it in this structure, xml conversion will be trivial.


问:
URL parameters in RESTful web services
I'm wondering about the appropriateness of URL parameters in RESTful resource creation.

First, here's some context. I'm working on an API that will remotely update the software on embedded devices connected to an online device cloud. The basic workflow is:

Discover available updates

Apply desired updates

Monitor update progress

The update discovery resource will allow users to POST a new update discovery.

```<code>POST /updateDiscovery?apikey=a1b2c3
</code>```

The above URL will trigger update discovery for all devices. It is also useful to restrict which devices are targeted for updates. There are two identifiers used to restrict target devices:

a device id

a group id (which may reference many devices)

This restriction can be communicated using either URL parameters or the request body.

Using URL parameters:

```<code>POST /updateDiscovery?deviceIds=1,2,3&groupIds=2,3
</code>```

Using the request body:

```<code>POST /updateDiscovery
Content-Type: application/json
{
    targets: {
         deviceIds: [1, 2, 3],
         groupIds: [3, 4]
     }
}
</code>```

Either way, a new resource will be created with the following representation:

```<code>{
   id: 1,
   targets: {
        deviceIds: [1, 2, 3],
        groupIds: [3, 4]
   },
   status: 'pending',
   ...
}
</code>```

Which of the above methods best follows the RESTful design pattern and why?

答: There is no problem with using parameters in RESTful API calls, however you want all the calls to be on resources. Right now you have \updateDiscovery which corresponds to an action, not a resource. An update is a resource though, so I would try designing it in terms of that (\updates)

Title: URL parameters in RESTful web services


问:
User Stories with design elements in Scrum
We're implementing a Scrum workflow and I'm trying to wrap my head around user stories, when they're completed, iterations, etc. One thing we often do is work on a story during an early iteration, get it fully working but "ugly". We use plain buttons, no images, just the text to show that it's working the way they should. We show our customer, make sure they are happy with how it's working, then we usually use images they provide to finish up the design of the feature and complete it.

In this instance, would we complete the user story when it's functionally complete, and make a second user story that says something to the effect of "as a user I want xyz to be visually appealing" to take care of the design phase? Or would we just move the user story from the first iteration to later on in the project once we get the design elements and can complete it? If that's the case, I can see us only completing maybe one or two stories in the first few iterations and completing a TON of stories in the final few iterations.

How do you all handle this scenario?

答:
A user story represents something that provides value to the business. Is it valuable to your business to provide a working feature to your design team? If so, create a user story that says that:

As a member of the design team, I want a working version of feature x
  so that I can create a final visual design that is appealing.

Is there business value in developing that final visual design? Make that a story:

As a customer, I want the visual design of feature X to be visually
  appealing and streamlined so that the use of the product is more
  enjoyable.

There needs to be more thought into the story than what I did, but hopefully that gives you the general idea.

Stories don't have to be fully finished features that are delivered to customer; stories represent something that provides value to the company. Sometimes the company is it's own customer. The point of the story is to get you to think about who benefits from your development efforts, and how they benefit.


问:
User stories as a contract definition?
I am often asked to write a requirements document for a new piece of work. I write requirements using user stories. The list of requirements is then used as a contract with the client denoting the functionality that will be delivered. The temptation them becomes to add more and more detail and more and more stories in an attempt to define a water-tight specification that rules out any expensive mistakes.

The problem is user stories just don't seem well suited to this task. Can anyone offer any clarification on the role of user stories? For example, is the same user story appropriate for  client, programmer and the author of a functional spec?

Regressing a little, perhaps I'm also asking what is the best way to define a contract of what will and will not be delivered in a software project?

答:
In my simplistic eyes, there are 2 general types of detailed 'artifacts' surrounding 'requirements' and 'scope' of a project, or a part of a project.

Requirements artifacts - what the customer needs / wants. Requirements are generally quite utopian, and will grow and change as the customer's business changes. User Stories, outputs of JAD sessions, Use Case Models, screen wireframes, and other documentation focused on the customer's point of view all fit here, IMO. The wording is typically in the domain of the customer or users of the system.

Contract Specification artifacts - watertight, itemized 'definitions' of all items which are to be delivered in scope of a contract. These include both functional and non functional 'specifications' (i.e. including qualities like performance, security, robustness, choice of technology, etc). A specification doesn't promise to meet all the customers requirements, and often a specification is limited to a partial piece of the system (e.g. a RUP 'generation' or iteration, but probably a bit more than an Agile Sprint). Specifications are much more technical in nature (e.g. will include interface definitions, performance commitments, and possibly 'signed off' screens). And as you've eluded, a contract is often best stated as what is NOT in scope of delivery. Any salesman knows that customers hate being told what they aren't going to get.

On a fixed price project, it is suicidal for the developer to agree at the requirements level, yet at the same time, it can be very difficult for a developer to recover the cost of a specification, and you will often scare away unsophisticated customers with specifications - they often view it with skepticism due to the technical jargon and legal angle of the document. But with sophisticated customers (e.g. those used to dealing with highly technical projects, e.g. NASA, ESA etc) this level of definition isn't a problem at all. But the additional formality comes at a cost - delays are often incurred while the documentation goes to and fro until it is finalized.

As a result, I believe the general idea is to move engagements with most customers away from fixed price entirely, and toward a paid-time project development basis, using tools like Agile and Scrum to ensure that the team is delivering at maximum efficiency and transparency, and the team is usually closely integrated with the customer, e.g. on the customer's premises and / or with customer resources in the team. This way, the customer can 'see' that everyone is pulling their weight, the customer has the ability to change direction of the project in between sprints, and tangible, testable software is delivered at regular intervals. This way both parties can evade the 'Contract Specification' entirely, and work on a mutual trust basis.

Title: User stories as a contract definition?


问:
What software models are appropriate for daily builds and continuous integration?
On reading the joel test and about daily builds, a discussion with a few tech-lead friends of mine in various companies revealed that they never did daily builds or continuous integration because according to them:

Daily builds were meant for projects following Agile practices. It does not work for the waterfall model.

Continuous integration required automated testing which their OpenGL/OGRE/OSG type-of graphics project couldn't use, because apparently automated testing is impractical for projects where the graphics part is under (re)development.

One of them believes that it's not necessary to have configuration management. It's just enough to follow the philosophy of it, by defining small 2-3 day tasks, perform all activities of the development cycle for each task (code, code-review, unit test, integration), deliver to integration stream and build and generate the setup.

Even if they created scripts for the entire build and burn-to-cd process, creating automated tests were a problem because in any program you create, you can't always know what tests you'd have to run and scripting a test case for it takes up too much time and automated testing tools may not always support the specific kind of tests you might want to make.

Is daily builds and continuous integration really practical for non-agile projects? Is it meant only for test driven development? And is it really sufficient to follow the point 3 (above) kind of philosophy? I was talking to them about the build-in-one-step kind of scripted automation that Joel talks about, but they weren't willing to buy the idea.

p.s: I've been through the questions on this site about daily builds etc, but I believe this question is different.

EDIT: Point 3 should've started with "One of them believes it isn't necessary to integrate configuration mangaement with development tools"

答:
Daily builds were meant for projects following Agile practices. It does not work for the waterfall model.

I would say: pure waterfall does not work for more than trivial projects with a lifetime so small that setting up a daily build would be oversized. But if your project lifetime is at least several months, and you mean "waterfall with recurring cycles", then of course daily builds can make a lot of sense. And even in a classical waterfall, where you have an analysis, a design and a development phase, in the development phase you have to do a lot of builds and code integration, so why not automate this and make sure the code changes integrate daily?

Continuous integration required automated testing

Nonsense, CI can integrate automated testing, but that's not a requirement. You can still test manually and use CI only for making sure you have a daily build ready for your testers.

One of them believes that it's not necessary to have configuration management.

If you have a project where the life cycle of your product ends after release 1.0, then this is true. In all other cases, you should have some kind of config management. But this is independently from CI. Furthermore, CI encourages you to keep your changes to your code base small and reintegrate daily - which exactly was your argument here against it.

Even if they created scripts for the entire build and burn-to-cd process, creating automated tests were a problem

See my comment, CI does not require automatic testing.

And to your other points:

you can't always know what tests you'd have to run

all of them, what else?

scripting a test case for it takes up too much time

You should script those test cases where applying them manually over and over again takes too much time, so having them automated will save you time.

automated testing tools may not always support the specific kind of tests you might want to make

Because there are some possible tests you have problems to automate, you don't automate anything? Does not sound very convincing to me. And who told you automated testing needs special tools? I would just start without any tools or only with some lighweight xUnit framework.


答:
I actually have a blog called "Struggles in Object Oriented Programming," that was born out of some of my struggles with learning it.  I think it was particularly difficult for me to understand because I spent so much time using procedural programming, and I had a tough time getting my head around the idea that an object could be represented by a collection of attributes and behaviors (I was used to simply a collection of variables and methods).

Also, there's a lot of concepts that make a language object oriented - inheritance, interfaces, polymorphism, composition, etc.  There really is a lot to learn about the theory of it before you can actually write code effectively, and in an object-oriented way, whereas with procedural programming, it's simply a matter of understanding things like memory allocation for variables, and entry point calls to other methods.

Title: Why is OOP difficult?

Body:
When I started using an object-oriented language (Java), I pretty much just went "Cool" and started coding. I've never really thought about it until only recently after having read lots of questions about OOP. The general impression I get is that people struggle with it. Since I haven't thought of it as hard, and I wouldn't say I'm any genius, I'm thinking that I must have missed something or misunderstood it.

Why is OOP difficult to understand? Is it difficult to understand?


答:
Your friends are being lazy and IMO unprofessional - the world will soon pass them by.

Daily builds were meant for projects following Agile practices. It
  does not work for the waterfall model.

I don't have a definitive reference handy, but daily builds were common at least as far back in the 90's, so they pre-date Agile, and the *Unified Process timeline. Any time you have more than a couple of devs, SOMEONE will check in something which can be tested, and at the same time can now automate checks for breaking the build.

automated testing is impractical for projects where the graphics part
  ...

Automated testing is a time and cost saving tool. Why would anyone want to make software more expensive than necessary?

not necessary to have configuration management

That is plain crazy. The dev's all use different versions of 3rd party libraries? No one tracks which features are to be deployed in each release? No branch capability in Version Control System?

Title: What software models are appropriate for daily builds and continuous integration?

Body:
On reading the joel test and about daily builds, a discussion with a few tech-lead friends of mine in various companies revealed that they never did daily builds or continuous integration because according to them:

Daily builds were meant for projects following Agile practices. It does not work for the waterfall model.

Continuous integration required automated testing which their OpenGL/OGRE/OSG type-of graphics project couldn't use, because apparently automated testing is impractical for projects where the graphics part is under (re)development.

One of them believes that it's not necessary to have configuration management. It's just enough to follow the philosophy of it, by defining small 2-3 day tasks, perform all activities of the development cycle for each task (code, code-review, unit test, integration), deliver to integration stream and build and generate the setup.

Even if they created scripts for the entire build and burn-to-cd process, creating automated tests were a problem because in any program you create, you can't always know what tests you'd have to run and scripting a test case for it takes up too much time and automated testing tools may not always support the specific kind of tests you might want to make.

Is daily builds and continuous integration really practical for non-agile projects? Is it meant only for test driven development? And is it really sufficient to follow the point 3 (above) kind of philosophy? I was talking to them about the build-in-one-step kind of scripted automation that Joel talks about, but they weren't willing to buy the idea.

p.s: I've been through the questions on this site about daily builds etc, but I believe this question is different.

EDIT: Point 3 should've started with "One of them believes it isn't necessary to integrate configuration mangaement with development tools"


答:
You can use memcached http://memcached.org/

there is a java client on memcached.

You can save the db object in memcached and achieve your purpose.

Ref: http://sacharya.com/using-memcached-with-java/

Title: Implementing cache system in Java Web Application

Body:
I worked with JPA (Eclipselink implementation) and Hibernate. As I understand these two have great caching systems.

I am interested in caching in a Web application and in order to better understand the process I'm trying to implement something on my own.

Sadly, I cannot find any in depth documentation about this subject. I'm interested in things like high scalability, sharing memory on different machines and other important theoretical matters. Is there any tutorial or open project I could check out?

Thank you!

*LE: * I want to cache DB information in POJOs just like JPA or Eclipselink


问:
Preferring Python over C for Algorithmic Programming
I've been studying a bit of algorithms and have been looking at sites like SPOJ.pl TopCoder etc. I've seen that programmers prefer C or C++ usually for most algorithmic programming contests.

Now I've been having some trouble lately. I know both a bit of C and Python and when trying to write a code I seem to prefer Python over C for most algorithms. Everytime I sit down to write a code in C I give up after about 15 minutes because I find it too cumbersome and tend to move over to python. Passing matrices Pointers and so on seem to be useless time wasted that I could actually be utilizing to think about the algorithm itself.

Now I know and have heard from a lot of people that C is a very important language and is the bread and butter of a lot of programmers out there.

What I wanted to know was whether this approach of mine has any drawbacks/consequences/Disadvantages etc.

This is not a Python vs C debate; This a question about how this specific practice of preferring python over C because of the ease of use will affect me or any other programmer/computer Scientist in the long run.

I'd love to hear from people who've used these languages in the industry/and or to develop large software/libraries etc.

答:
What you will be missing out when programming in "higher" level languages than C/C++ is learning how computers work. You will not be able to develop things like embedded systems, operative systems and hardware drivers. Knowing C also helps when learning assembler.

Also, the vast majority of all mission critical systems are still developed in C, so you may not be able to work in several software software branches (aerospace/automotive/med-tech etc) without knowing it.


答:
To be fair to your discussion partners, if what they have works, then, well, it works. I'd still probably sell them CI in some form, but I can understand the resistance.

There is an overhead to getting CI set up in the first place, and an overhead for managing it. Not a huge over head, but I point blank refuse to be "The CI guy" ever because I know at some point it will become an unwanted chore.

However, once I've nominated someone else to get it configured, at the very least it is beneficial to know that the code checked in is compiling. That one benefit alone is significant.

The testing side of it is kind of irrelevant here. The CI build should run tests, but those tests shouldn't exist if they serve no useful purpose. There are always test cases that do make sense though. This is also a point of resistance for many developers.

Some people still see code test coverage as a golden statistic of project health. It isn't. I'd still rather have 1pc coverage with that 1pc being appropriate, quality tests, rather than 80pc coverage of "Tests I wrote because we needed to get to 80pc coverage".

And that's the final issue. Once you've got CI, someone is going to ask you for coverage statistics, then they will ask why your coverage isn't higher, then someone will send you a link to a great UI testing package that automates... In their mind they've gone from a process which demonstrably works, to a process which requires more effort to get to the same end result, the same working code they were delivering previously.


问:
Do you consider mainframe as part of large application deployments?
When you are setting up your system landscape for large and/or multiple application deployments, do you consider mainframe?  If not, why not?  If so, what factors are you considering.

If you take a real TCO look at large ERP and/or consolidated application landscapes, mainframe is actually quite cost-effective.

My own consultations have included recommendations for scale-up/mainframe/mid-size systems on some specific needs.  Honestly, I've never had a customer take said recommendation, rather defaulting to countless scale-out VMs on Intel boxen (in non-trivial cost) and yet still to this day have system management and performance issues.

Curious your take on this.  We need to remember that the virtual machines we manage (and apparently love in IT departments) today have been done for decades on mainframe.  Most mid-size and mainframe shops have small fractions of support persons managing larger and more complex applications.

Your thoughts appreciated.

答:
If the client already owns and operates a mainframe then deploying a new application on said mainframe often makes sense.

However if the client does not already own a mainframe than you would need a really compelling case to overcome the disadvantages:

New operations staff and procedures.

Specialist sysadmin staff ("Systems Programmers" - even the job titles are different).

Specialist programming staff -- the awful JCL and even worse VTAM are still undead!

A massive software bill before you can run your first app.

An even bigger software bill for the third party software to run your apps efficiently.


答:
I would advice you looking at Scala or Clojure (but use type annotations). In some cases they can be as fast as C, in other cases they are still much more faster then Ruby/Python, while having very consice and clear notation unlike C (IMHO). Consider this vs C code:

```<code>for (i <- 1 to 100; j <- 2 until 100;
     k <- 1 to 2; if i != j) {
     //...
}
</code>```

Also they have function programming arsenal similar to Ruby's/Python's map, filter, reduce etc which is not as fast as iterating or tail call recursion, however it is still much faster then the fully dynamic scripting languages.

Title: Preferring Python over C for Algorithmic Programming

Body:
I've been studying a bit of algorithms and have been looking at sites like SPOJ.pl TopCoder etc. I've seen that programmers prefer C or C++ usually for most algorithmic programming contests.

Now I've been having some trouble lately. I know both a bit of C and Python and when trying to write a code I seem to prefer Python over C for most algorithms. Everytime I sit down to write a code in C I give up after about 15 minutes because I find it too cumbersome and tend to move over to python. Passing matrices Pointers and so on seem to be useless time wasted that I could actually be utilizing to think about the algorithm itself.

Now I know and have heard from a lot of people that C is a very important language and is the bread and butter of a lot of programmers out there.

What I wanted to know was whether this approach of mine has any drawbacks/consequences/Disadvantages etc.

This is not a Python vs C debate; This a question about how this specific practice of preferring python over C because of the ease of use will affect me or any other programmer/computer Scientist in the long run.

I'd love to hear from people who've used these languages in the industry/and or to develop large software/libraries etc.

Body:
I would advice you looking at Scala or Clojure (but use type annotations). In some cases they can be as fast as C, in other cases they are still much more faster then Ruby/Python, while having very consice and clear notation unlike C (IMHO). Consider this vs C code:

for (i <- 1 to 100; j <- 2 until 100;
     k <- 1 to 2; if i != j) {
     //...
}

Also they have function programming arsenal similar to Ruby's/Python's map, filter, reduce etc which is not as fast as iterating or tail call recursion, however it is still much faster then the fully dynamic scripting languages.


问:
Is it bad to use Unicode characters in variable names?
I recently tried to implement a ranking algorithm, AllegSkill, to Python 3.

Here's what the maths looks like:

No, really.

This is then what I wrote:

```<code>t = (µw-µl)/c  # those are used in
e = ε/c        # multiple places.
σw_new = (σw**2 * (1 - (σw**2)/(c**2)*Wwin(t, e)) + γ**2)**.5
</code>```

I actually thought it is unfortunate of Python 3 to not accept √ or ² as variable names.

```<code>>>> √ = lambda x: x**.5
  File "<stdin>", line 1
    √ = lambda x: x**.5
      ^
SyntaxError: invalid character in identifier
</code>```

Am I out of my mind? Should I have resorted for a ASCII only version? Why? Wouldn't an ASCII only version of the above be harder to validate for equivalence with the formulas?

Mind you, I understand some Unicode glyphs look very much like each other and some like     ▄ (or is that ▗▖ ) or ╦  just can't make any sense in written code. However, this is hardly the case for Maths or arrow glyphs.

Per request, the ASCII only version would be something along the lines of:

```<code>winner_sigma_new = ( winner_sigma ** 2 *
                    ( 1 -
                     ( winner_sigma ** 2 -
                       general_uncertainty ** 2
                     ) * Wwin(t,e)
                    ) + dynamics ** 2
                   )**.5
</code>```

...per each step of the algorithm.

答:
I would say using Unicode variable names is a bad idea for two reasons:

They're a PITA to type.

They often look almost the same as English letters.  This is the same reason why I hate seeing Greek letters in math notation.  Try telling rho apart from p.  It's not easy.


问:
How can we handle multiple instances of a method through a single class instance
How can we handle multiple instances of a method through a single class instance(Single constructor call)?

To elaborate, I have a handler class which has two methods lets say verifyUser(String JSON) and getUserInfo(String JSON). Assuming that there are many users accessing this methods, there will be multiple instances of these methods. The handler class should be initialized once. I.e. multiple objects of this class are not permitted, rather multiple method instances are allowed.

What will be the ideal solution for enabling concurrent method calls without corrupting data while executing?

答:
In Java, methods do not have instances. The correct terminology is that there will be multiple threads executing methods on the same object.

There are basically three ways to do this without risking data corruption:

Share no mutable data between the threads, i.e. have no mutable fields in the class.

Protect all mutable shared data by using synchronization so that only one thread at a time can access it.

Use special lock-free algorithms or data structures, like those found in the java.util.concurrent package.

In any case, doing this correctly is hard in any but the most trivial cases. You really need to understand what can go wrong in order to avoid it. Java Concurrency in Practice is an excellent book you could use to achieve that understanding.


答: As long as you don't create any member variables in this class that would be modified by these methods, you should be safe. But in this case can also consider declaring these methods as static.</p>

Body:
How can we handle multiple instances of a method through a single class instance(Single constructor call)?

To elaborate, I have a handler class which has two methods lets say verifyUser(String JSON) and getUserInfo(String JSON). Assuming that there are many users accessing this methods, there will be multiple instances of these methods. The handler class should be initialized once. I.e. multiple objects of this class are not permitted, rather multiple method instances are allowed.

What will be the ideal solution for enabling concurrent method calls without corrupting data while executing?


问:
Changing frontend cache
Our architecture consists of a front-end cache that most read only users obtain their data from directly. The front-end cache sits in front of a farm of webservers that serve pages written in PHP. We need to be able to detect certain conditions at the front-end cache level and pass those values through to the back-end via HTTP headers. For example we would like to manually tag the carrier network based on the IP address. So, for incoming traffic if the user is say coming from an IP address in the range of "41.202.192.0"/19 we would tag them as being a Orange Cameroon user by setting the appropriate HTTP request header, e.g., X-Carrier = "Orange Cameroon".

Based on the setting of this header we would like to vary the cache and serve a different banner to the end user. How would you go about doing this? Keep in mind that we don't want to pollute the cache and we also don't want to create too many small cache segments.

Assumptions: You can assume that the X-Carrier has already been detected in our cache. So, for the purposes of your test you can just set this value manually in your example script.

答:
Varnish as a front end cache sounds like a good fit here https://www.varnish-cache.org/

It is incredibly fast and can easily handle thousands of page requests per second on fairly modest hardware running Linux.

To add headers, select appropriate backends, determine cache life e.t.c. there is a scripting language built into Varnish that compiles to C when Varnish starts. Look at the VCL page for details of what you can do https://www.varnish-cache.org/docs/3.0/reference/vcl.html

Also have a look at https://www.varnish-cache.org/trac/wiki/VCLExamples for real world examples of how people have deployed VCL within Varnish to solve similar problems to yours https://www.varnish-cache.org/trac/wiki/VCLExamples

Title: Changing frontend cache


问:
Are there any theories or books about how to debug "in general"?
I read and studied a lot of computer science and engineering and I rarely or never seen a book about debugging or a theory how to debug (though I surely developed some debugging theories of my own).

Are there any debugging theories and/or books? Why / why not? I can read how to debug using gdb and some of the most useful info about development I got from reading how to use gdb.

答: I read the Debug IT from Pragmatic programmers. As almost all books from pragmatic programmers, it's pretty hands-on but not so deep, but was nice to help me to teach new developers how to set their "debug mindset". There are no black magic, but more common sense and almost everything looks really intuitive for experienced programmers. </p>


答: This "updateDiscovery" entity seems a bit too abstract to me. I would rather have a clear separation between "devices" and "updates". This way I could call GET on "/devices/{deviceId}/updates", to get a list of all updates which have been applied to a device. Or GET on "/updates?deviceIds=..." to get a list of updates that should be applied to specified devices.</p>

Title: URL parameters in RESTful web services

Body:
I'm wondering about the appropriateness of URL parameters in RESTful resource creation.

First, here's some context. I'm working on an API that will remotely update the software on embedded devices connected to an online device cloud. The basic workflow is:

Discover available updates

Apply desired updates

Monitor update progress

The update discovery resource will allow users to POST a new update discovery.

```<code>POST /updateDiscovery?apikey=a1b2c3
</code>```

The above URL will trigger update discovery for all devices. It is also useful to restrict which devices are targeted for updates. There are two identifiers used to restrict target devices:

a device id

a group id (which may reference many devices)

This restriction can be communicated using either URL parameters or the request body.

Using URL parameters:

```<code>POST /updateDiscovery?deviceIds=1,2,3&groupIds=2,3
</code>```

Using the request body:

```<code>POST /updateDiscovery
Content-Type: application/json
{
    targets: {
         deviceIds: [1, 2, 3],
         groupIds: [3, 4]
     }
}
</code>```

Either way, a new resource will be created with the following representation:

```<code>{
   id: 1,
   targets: {
        deviceIds: [1, 2, 3],
        groupIds: [3, 4]
   },
   status: 'pending',
   ...
}
</code>```

Which of the above methods best follows the RESTful design pattern and why?


答:
I don't think it is difficult to understand but it may be that a lot of the programmers querying are new to the concept, coming from procedural languages.

From what I have seen/read lots of people (in forums at least) look for a 'result' from OOP. If you are a procedural programmer who doesn't go back and modify extend their code it can probably be hard to understand the benefits.

Also, there is a lot of bad OOP out there, if people are reading/seeing that then it is easy to see why they might find it difficult.

IMO you need to wait until it 'clicks' or be taught by someone with real knowledge, I don't think you can rush.

Title: Why is OOP difficult?


问:
Mixing languages in .Net
I know that .Net provides the feature to mix several languages within the same application (there are some constraints of course, but this is not essential). Theoretically, this might be done because the languages supported by .Net do not fully expose all the features it can provide. IL does of course. So when you need a feature that the current language doesn't provide, you could write it in another .Net language. The whole code would be translated into IL, and so you would gain more features.

From my personal experience, I was writing a project in C# and needed to integrate a small project written in C++ under .Net. When I consulted with some more experienced programmers, they said that it would be much easier to "translate" the C++ code into C# than integrate it. Since I had little time, it was what I did, and it was quite easy (the project was quite small).

So my question is, has anyone experienced a real-life situation when mixing languages is an absolute necessity?

答:
The best real-world scenario I've encountered is when you want to access C++ classes from a managed environment, say from a C#-based application.

C# can access unmanaged COM classes using COM Interop, or unmanaged C-style APIs like the Win32 API using P/Invoke/DllImport, but it can't access normal non-COM C++ classes and APIs. If you've got a need to do that, easiest way is to write a component in C++/CLI.

Since the component is a managed, .NET component, it can be easily called by your C# code. Since it's C++, it can instantiate C++ objects and call unmanaged APIs. Everyone is happy.

Title: Mixing languages in .Net


问:
Best practices / Design patterns for code generation
I'm working on a ground up code generator project, but I feel I might be reinventing the wheel.

Does anyone know where I can find some best practices guidelines or design patterns for code generation?

答:
Real best practices are hard to find because there is still a lot discussion on good code generation. What level of abstraction do you model, what is a model, do you use a graphical or a textual model, internal or external DSL on what level do you want to use code generation (from simple developer help to complete software factory)

One of the best books out there is "Domain specific modeling" Although if you are in the microsoft space it might be a bit difficult to map on your own projects.

Also the DSL book by Martin Fowler can give you some good ideas on the terminology and idea's behind DSL's and how to use the for code generation.

If you are looking for language workbenches the language workbench challenge is a good place to see what is out there and what other people are doing.

Hope this helps.

extra: I also read "code generation in .net" the technology described is old and also just a "how to" definitely no help in best practice or design patterns

25-1-2013 EDIT : A new book was just released that might be very helpful : "DSL Engineering - Designing, Implementing and Using Domain-Specific Languages"


问:
Why is OOP difficult?
When I started using an object-oriented language (Java), I pretty much just went "Cool" and started coding. I've never really thought about it until only recently after having read lots of questions about OOP. The general impression I get is that people struggle with it. Since I haven't thought of it as hard, and I wouldn't say I'm any genius, I'm thinking that I must have missed something or misunderstood it.

Why is OOP difficult to understand? Is it difficult to understand?

答:
Any paradigm requires a certain push "over the edge" to grasp, for most people.  By definition, it's a new mode of thought and so it requires a certain amount of letting go of old notions and a certain amount of fully grasping why the new notions are useful.

I think a lot of the problem is that the methods used to teach computer programming are pretty poor in general.  OOP is so common now that it's not as noticeable, but you still see it often in functional programming:

important concepts are hidden behind odd names (FP: What's a monad?  OOP: Why do they call them functions sometimes and methods other times?)

odd concepts are explained in metaphor instead of in terms of what they actually do, or why you'd use them, or why anyone ever thought to use them (FP: A monad is a spacesuit, it wraps up some code.  OOP: An object is like a duck, it can make noise, walk and inherits from Animal)

the good stuff varies from person to person, so it's not quite clear what will be the tipping point for any student, and often the teacher can't even remember. (FP: Oh, monads let you hide something in the type itself and carry it on without having to explicitly write out what's happening each time.  OOP: Oh, objects let you keep the functions for a kind of data with that data.)

The worst of it is that, as the question indicates, some people will immediately snap to understanding why the concept is good, and some won't.  It really depends on what the tipping point is.  For me, grasping that objects store data and methods for that data was the key, after that everything else just fit as a natural extension.  Then I had later jumps like realizing that a method call from an object is very similar to making a static call with that that object as the first parameter.

The little jumps later on help refine understanding, but it's the initial one that takes a person from "OOP doesn't make sense, why do people do this?" to "OOP is the best, why do people do anything else?"

Title: Why is OOP difficult?


答: For making generated code more maintainable, you may be interested in the Generation Gap pattern. This is one pattern that didn't make it into the GoF book, but that John always liked and later described separately in the same format.</p>

Title: Best practices / Design patterns for code generation

Body:
I'm working on a ground up code generator project, but I feel I might be reinventing the wheel.

Does anyone know where I can find some best practices guidelines or design patterns for code generation?

ContentLicense: CC BY-SA 4.0


答:
It depends on project

Your tools and practices will vary depending on what specifically you have to do for the project. For example: in ASP.NET MVC and .NET development you may consider T4 Text Templates. Basically, what it does is usage of the pre-build and custom templates to scaffold a model for generation of the related files (like add Controller and views).

Nice blog has a quick intro T4 Templates: A Quick-Start Guide for ASP.NET MVC Developers

However, you may also use T4 in different code generation processes as well.


答:
I'd love to hear from people who've used these languages in the industry/and or to develop large software/libraries etc.

I’ve worked on a small part of a big C++ library for some years, and have written both my bachelor and master thesis in the context of this library. The library, incidentally, is a library for bioinformatics algorithms and data structures.

The library is built in C++ because C++ is almost perfect for the specific requirements of this library, and for algorithms libraries in general. If I were to develop another algorithms library and the choice of language were mine, I would almost certainly choose C++ again.

The reason is not only performance but also the strong type system which first of all gives you more type safety and second of all gives you the ability to let your types document the algorithm used. This can (in my experience) greatly enhance readability and maintainability.

That said, for simple algorithmic doodles and puzzles, I almost always use Python (mainly because yes, it reads almost like pseudo code), unless I specifically want to try out how to best formulate a problem in C++. So far, I haven’t solved many of the SPOJ or TopCoder problems so I don’t know whether performance there is really so critical that using a fast language is crucial.

But normally what counts is to get the algorithm right in order to pass. In those cases, Python works just fine. For instance, for the Project Euler problems (which aren’t timed, only the correct solution counts), Python is perfectly well suited.


问:
Using a openid in a "closed system"
I would like to publish a website for certain family members only. Simply put, like a mishmash of family photos and videos. I want it to remain private, however.

I was considering using openid for the login process because I really wanted to avoid:

Storing Usernames and Passwords
(Too much maintainance)

Making a obfuscated url that can be picked up by toolbar
(Not private enough)

Making a password to access the page
(I've had users unable to manage this)

So I was hoping to use openid to have say my brother log in using his google account.

But from what I've seen openid used for, it wouldn't prevent others from logging in to the website. I was thinking maybe I could limit it manually however this paragraph from Google App Platform best practices has me double thinking:

From a protocol perspective, both logins to the two IDPs are legitimate and the attributes returned by the 2nd IDP appear identical — the same email address, name, and so on. The only thing that differs between the two requests is the user's claimed identity. In fact, relying parties are required to verify that IDPs only return identities that they're authoritative to prevent a rogue IDP from asserting identities from other providers. But nothing prevents a rogue IDP from asserting attributes like names and email address that may not be truthful.

Is openid the "right" tool for what I wish to do? (Have a private web interface that requires logins but no user management beyond identifying family members)

答: Totally agree with Matt here. You can use social login/Open Id plugin along with some sort of private beta functionality which can help you in defining access for the user. LR Social login provides this functionality though at premium :)</p>

Title: Using a openid in a "closed system"


答:
This feature can be used in ASP.NET website development.

I had an occasion where project was initially developed in VB.NET and required some new additions (new web-forms). After analyzing pros and cons as well as timeline,  i have decided to add new forms in C#, as it was my primary language of development. Everything went pretty well for that small project.

However, there might be some disadvantages/side-effects for relatively big projects, where languages are mixed.

Note: you can use only one .NET language in ASP.NET web application

Title: Mixing languages in .Net

Body:
I know that .Net provides the feature to mix several languages within the same application (there are some constraints of course, but this is not essential). Theoretically, this might be done because the languages supported by .Net do not fully expose all the features it can provide. IL does of course. So when you need a feature that the current language doesn't provide, you could write it in another .Net language. The whole code would be translated into IL, and so you would gain more features.

From my personal experience, I was writing a project in C# and needed to integrate a small project written in C++ under .Net. When I consulted with some more experienced programmers, they said that it would be much easier to "translate" the C++ code into C# than integrate it. Since I had little time, it was what I did, and it was quite easy (the project was quite small).

So my question is, has anyone experienced a real-life situation when mixing languages is an absolute necessity?


答:
The Saff Squeeze is a technique described by Kent Beck which uses tests and refactoring for debugging:

Hit 'em High, Hit 'em Low:

Regression Testing and the Saff Squeeze

Kent Beck, Three Rivers Institute

Abstract: To effectively isolate a defect, start with a system-level test and progressively inline and prune until you have the smallest possible test that demonstrates the defect.

Title: Are there any theories or books about how to debug "in general"?

Body:
I read and studied a lot of computer science and engineering and I rarely or never seen a book about debugging or a theory how to debug (though I surely developed some debugging theories of my own).

Are there any debugging theories and/or books? Why / why not? I can read how to debug using gdb and some of the most useful info about development I got from reading how to use gdb.


问:
Should I use events in this case?
I'm creating a video player, like a custom YouTube player.

All of the GUI elements (progress bar, video player, play button, ...) are different classes, but I obviously need them to communicate. When the progress bar is clicked, or the slider is moved, it needs to send a "seek(x)" command to the video player. Similarly, the video player needs to update the progressbar every frame.

Currently I'm doing this by having almost all elements have a link to each other.
So when I create the progress bar, I'm telling it where the video player is.

But after a while this becomes more and more complicated, and I'm wondering if events would be a better way to do this. Or a main controller class that has all the connections.
What should I do?

答:
Every GUI framework uses some kind of event publishing/handling, so you are forced to use them.

When designing a GUI application, you should use MVP design pattern (or one of it's variation, like Presenter first, or model-view). This way, you can easily unit test the code and logic. When the code is unit tested, it is usually simpler to understand (off course, there are exceptions).

Also, do not put everything in one MVP triad, but try to break your application as much as possible. Smaller chunks of code are easier to understand.

Title: Should I use events in this case?


答:
I think it depends on age (age as a proxy for experience) and, more importantly, interest. If you're "young" (i.e., green, perhaps) and you've never thought any other way, it seems quite straightforward. On the other hand, if you think it's the coolest thing you've ever seen -- happened to me at age 28 or something -- it's easy to grok.

On the other hand, if you think, as many of my Java students did, "why are we learning this, it's just a fad," it's practically impossible to learn. This is true with most technologies.

Title: Why is OOP difficult?


答:
My rules of thumb for using events:

can you imagine these components existing separately, used not only in conjunction with each other? If yes, most likely go with events.

do you need from this component some information in response to the event sent? If you don't, then, once again, most likely, you've made right decision about sending events.

This does not free you from good and well-thought-out OOP-architecture, since even event handlers shouldn't be spagetti code.

This does not free you from difficulties of debugging such code, which by its nature tends to be asynchronous.

But, nevertheless, you can sum it up as follows:
If you think of your system like of a set of autonomous components that should be easily interchangeable/used with any other (sub)set of components, use events.

Title: Should I use events in this case?

Body:
I'm creating a video player, like a custom YouTube player.

All of the GUI elements (progress bar, video player, play button, ...) are different classes, but I obviously need them to communicate. When the progress bar is clicked, or the slider is moved, it needs to send a "seek(x)" command to the video player. Similarly, the video player needs to update the progressbar every frame.

Currently I'm doing this by having almost all elements have a link to each other.
So when I create the progress bar, I'm telling it where the video player is.

But after a while this becomes more and more complicated, and I'm wondering if events would be a better way to do this. Or a main controller class that has all the connections.
What should I do?


答:
You should combine events, states and methods.

Events should only inform that the event happened, not more.
States of the application should make you decide what can and cannot be done at that moment.
Methods should do the job like starting/stopping playing the video etc.

Events should not be used instead of methods, because it becomes harder to read and understand the code. Just change states and call some methods from your event.

Title: Should I use events in this case?


问:
Pair programming remotely with Visual Studio?
What tools exist to facilitate pair programming with Visual Studio when the programmers are not in the same physical location? At the moment we are thinking voice (Skype?) plus remote desktop (VNC? TeamViewer?), but it would be good to know of other suggestions and experiences. Also, is there anything more integrated with Visual Studio?

A bit more background: we are two experienced developers with who have collaborated well for a long time on a large mature project (ASP.NET, Windows Forms and SQL Server). However we are not usually working on the same part of the code base at the same time. We intend to spend some weeks doing substantial refactoring and it would be ideal if we were able to do this work with a pair-programming approach.

答:
You're on the right track when you say you need voice and remote desktop software, irrespective of whether you're going to be using Visual Studio or other tools to collaborate. I don't use Visual Studio myself, so I can't answer the part of your question about any tools integrated with it, but I do work as part of a distributed team and there are a whole heap of choices out there for you to pick from.

For VoIP, Skype is a common choice and one I've used a lot in the past, but I have to say I'm not a great fan of what it's become (ads and the beautiful simple interface has been replaced with a rather counter-intuitive one), so I tend to use either Trillian to talk to my Skype contacts, or C3 (which is actually intended for online gamers but is also great for general VoIP communication, is much less of a resource and bandwidth hog and is completely free). I found Google Talk's "feature" of asking you "Are you still there?" after a couple of hours while you're clearly still talking a bit annoying, as there's usually no point in keeping the tab in the foreground, so often we missed the question and got thrown out. Quality-wise, there wasn't much between the three on a broadband connection; if anything, I'd give the edge to C3.

As for web conferencing (or desktop sharing) software, which you'll need in order to view each other's desktops and control each other's mouse/keyboard for paired programming, I've used Netviewer commercially (my client had a license) in the past (before they were bought up by Citrix) and more recently TeamViewer, which is similar from a pure desktop sharing point of view but seems to have a few less features (or maybe I just haven't discovered them yet). We are also considering OpenMeetings but I haven't used it much yet so can't make an informed recommendation on that one.

Wikipedia's comparison pages seem to be kept quite up-to-date if you'd like more options to pick from:

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

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

Most of the commercial ones tend to have at least free trials, so make sure you try before you buy.

Once you've got the right tools set up, there's not that much difference between doing XP while sitting next to each other and while sitting in different parts of the world. (And there are actually benefits, e.g. you can't knock over the other guy's coffee cup and you can keep your own favourite keyboard and mouse settings.)


问:
How do you organize highly customized software?
I'm working on a large software project which is highly customized for various customers arround the world. This means that we have maybe 80% code which is common between the various customers, but also a lot of code which has to change from one customer to the other. In the past we did our development in separate repositories (SVN) and when a new project started (we have few, but large customers) created another repository based on whatever past project has the best code basis for our needs. This has worked in the past, but we ran into several problems:

Bugs which are fixed in one repository are not patched in other repositories. This might be a problem of organization, but I find it difficult to fix and patch a bug in 5 different repositories, keeping in mind that the team maintaining this repository might be in another part of the world and we don't have their test environment, neither know their schedule or what requirements they have (a "bug" in one country might be a "feature" in another).

Features and improvements made for one project, which might also be useful for another project are lost or if they are used in another project often cause big headaches merging them from one code base to another (since both branches might have been developed independently for a year).

Refactorings and code improvements made in one development branch are either lost or cause more harm than good if you have to merge all these changes between the branches.

We are now discussing how to solve these problems and so far came up with the following ideas on how to solve this:

Keep development in separate branches but organizing better by having a central repository where general bug fixes are merged into and having all projects merge changes from this central repository into their own on a regular (e.g. daily) basis. This requires huge discipline and a lot of effort for merging between the branches. So I'm not convinced that it will work and we can keep this discipline, especially when time pressure puts in.

Abandon the separate development branches and have a central code repository where all our code lives and do our customization by having pluggable modules and configuration options. We are already using Dependency Injection containers to resolve dependencies in our code and we are following the MVVM pattern in most of our code to cleanly separate business logic from our UI.

The second approach seems to be more elegant, but we have many unsolved problems in this approach. For example: how do handle changes/additions in your model/database. We are using .NET with Entity Framework to have strongly typed entities. I don't see how we can handle properties which are required for one customer but useless for another customer without cluttering our data model. We are thinking of solving this in the database by using satellite tables (having a separate tables where our extra columns for a specifiy entity live with a 1:1 mapping to the original entity), but this is only the database. How do you handle this in code? Our data model lives in a central library which we would not be able to extend for each customer using this approach.

I'm sure that we are not the only team struggling with this problem and I'm shocked to find so little material on the topic.

So my questions are the following:

What experience do you have with highly customized software, what approach did you choose and how did it work for you?

What approach do you recommend and why? Is there a better approach?

Are there any good books or articles on the topic that you can recommend?

Do you have specific recommendations for our technical environment (.NET, Entity Framework, WPF, DI)?

Edit:

Thanks for all the suggestions. Most of the ideas match those that we already had in our team, but it is really helpful to see the experience you had with them and tips to better implement them.

I'm still not sure which way we will go and I'm not making the decision (alone), but I will pass this along in my team and I'm sure it will be helpful.

At the moment the tenor seems to be a single repository using various customer specific modules. I'm not sure our architecture is up to this or how much we have to invest to make it fit, so some things might live in separate repositories for a while, but I think it's the only longterm solution that will work.

So, thanks again for all responses!

答:
One company I've worked for had the same problem, and the approach to tackle the problem was this: A common framework for all new projects was created; this includes all stuff that has to be the same in every project. E.g. form generating tools, export to Excel, logging. Effort was taken to make sure that this common framework is only improved (when a new project needs new features), but never forked.

Based on that framework, customer-specific code was maintained in seperate repositories. When useful or necessary, bug fixes and improvements are copy-pasted between projects (with all the caveats described in the question). Globally useful improvements go into the common framework, though.

Having everything in a common codebase for all customers has some advantages, but on the other hand, reading the code becomes difficult when there are countless ifs to make the program behave differently for each customer.

EDIT: One anecdote to make this more understandable:

The domain of that company is warehouse management, and one task of a
  warehouse management system is to find a free storage location for
  incoming goods. Sounds easy, but in practice, a lot of constraints and
  strategies have to be observed.

At one point in time, management asked a programmer to make a
  flexible, parameterisable module to find storage locations, which
  implemented several different strategies and should have been used in
  all subsequent projects. The noble effort resulted in a complex module, which
  was very difficult to understand and maintain. In the next project,
  the project lead couldn't figure out how to make it work in that
  warehouse, and the developer of said module was gone, so he eventually
  ignored it and wrote a custom algorithm for that task.

A few years later, the layout of the warehouse where
  this module was originally used changed, and the module with all its
  flexibility didn't match the new requirements; so I replaced it with a
  custom algorithm there, too.

I know LOC is not a good measurement, but
  anyway: the size of "flexible" module was ~3000 LOC (PL/SQL), while a custom
  module for the same task takes ~100..250 LOC. Therefore, trying to be flexible
  extremely increased the size of the code base, without gaining the reusability
  we had hoped for.


答:
I've never tried it, but GoToMeeting is probably a perfect fit here -- it natively handles voice, video and screen sharing so you don't have to have two separate solutions. I haven't used it for coding, but I've used it for collaborating remotely on documents where we pass control back and forth and it has worked pretty seamlessly.

This probably doesn't apply in your case but it does not handle areo or glass effects at all.

Title: Pair programming remotely with Visual Studio?

Body:
What tools exist to facilitate pair programming with Visual Studio when the programmers are not in the same physical location? At the moment we are thinking voice (Skype?) plus remote desktop (VNC? TeamViewer?), but it would be good to know of other suggestions and experiences. Also, is there anything more integrated with Visual Studio?

A bit more background: we are two experienced developers with who have collaborated well for a long time on a large mature project (ASP.NET, Windows Forms and SQL Server). However we are not usually working on the same part of the code base at the same time. We intend to spend some weeks doing substantial refactoring and it would be ideal if we were able to do this work with a pair-programming approach.


问:
What are the Top Developer Productivity Tools/Plugins for Java in Eclipse?
I personally use CodeRush in Visual Studio 2010 to do refactoring, write code faster with templates and generally navigate my code 10 times faster than stock VS.  Recently, I've been working on another Android app and got to thinking...What are the top productivity plugins for Eclipse?

Preferably free. I'm looking for plugins that help write in Java, not PHP or Rails or any of the other languages Eclipse supports.

答:
Clover - A test coverage tool, but outputs the most lovely reports in the world (costs a pretty penny thou.)

Crap4J - Same general data as Clover (that is to say it is a code coverage tool) but simplified and less pretty (free).

Findbugs - Reports on common coding errors (free).

All can be used as either an Eclipse plugin or a stand alone application.


问:
Should a github maintainer rewrite author's in pull requests?
I'm not a programmer by profession, but I do some coding and have used github some.  I've run across what I find to be a surprising situation.  I'm very familiar with git.

There is a project which I found a (small) bug in that was affecting me.  I spent an afternoon finding and fixing it.  I forked the repository, commit the change, and issued a pull request.   After seeing that it was closed as "Merged into development branch" I figured all was well.

I was browsing the repo today getting ready to remove my branch, and I can't find where the commit was merged into the maintainer's repo at all.  After some time I realize it's been added as a commit, but the author is no longer me.

As far as I can tell the only way to do that would be to specifically use a rebase, amend, or other history rewrite to remove the original author.

This seems very wrong to me.  At best it's confusing, at worst the author of this repo is taking credit for everyone's commits and then the history of the original contributor is lost.  Again it's a small bug, I don't use this for my professional resume, it just seems dishonest.

Is this normal?
Should I say something about it?

Edit: The general feeling seems to be that I should go ask, so I'll do just that this morning.

As per the request below.  I've checked and my code exists and was applied exactaly as I wrote it (including the comment).  I verified that both the committer and author have been changed.  There was one additional change also added at the same time as my changes.  It's a single line, which would affect the patch as well as other code before it.  IE the one line addition is not related to the bug I was fixing.

Update
It seems the answer was that the author maintains a development branch and does not want to merge from his master branch into it.  He re-authored my commit to avoid a merge.  I wasn't concerned with the original branch b/c git's plenty powerful to cherry-pick, rebase, and merge commits around as needed.

Is this typical on github?

Should I be contacting the maintainer of a project to ask which branch to apply patches to?

答: It seems the answer was that the author maintains a development branch and does not want to merge from his master branch into it. He re-authored my commit to avoid a merge.</p>


答:
Looks like what you've got is the best bet for now.  You want to keep your links to a minimum, but there needs to be a connection between the progress bar and the video player, so at least one needs a reference to the other.  Having all the connections in one controller means more work when one element wants to talk to another.

Events won't save you.  If a dozen (or even two) different elements, unknown to the player, needed regular updates on progress, an event would be just the thing.  Note that the player would now be setting off the event rather than calling a progress bar method, so you're pretty much breaking even in complexity.  (But now it's harder to figure out who's being informed.)  Here, I think a simple method call is better.

The elegant solution--the one probably floating around in the back of your head that led you to ask this question--would be to reverse the responsibilty and have the progress bar ask the player what the progress is.  This takes a load off the player--it doesn't have to worry about when to make the calls--though it does have to have progress information always ready.  There are no fancy events, just a simple method that someone else calls.  And the player doesn't care how many other elements call the method, or when, or why.

The down side is the progress bar needs to run a timer to keep things going.  But the player would have needed to do something similar:  the work and the responsibility are now concentrated where they belong.

I'm not sure you need this "elegant" solution quite yet, but I think that's the direction you'll want to move in later.

(If you use it, be sure to run everything on the EventQueue, or UI queue, or whatever your language calls it--at any rate, keep everything on one thread.  Multithreading is very tricky, and in most cases UI's only work on their own thread anyway.)

Title: Should I use events in this case?


问:
Being a team manager and a developer in a Scrum team
I am managing a team of 6 people that recently moved to Scrum.

We have a Scrum Master (one of the developers in the team) and a Product Owner.

Since I have quite a lot of free time (because a lot of management work that I used to do is now done by the Scrum Master and Product Owner), and since I want to remain technically relevant, I am doing some technical development work.

I act as a part of the development team, commit to some of the stories in each sprint, and participate in all the meetings as a part of the team.

Do you think it is a good idea? Can it contradict the "self-organization" of the team?

答:
pdr's comments are valid, and I agree with them.  But I don't believe them to be universal for all cases.

Your management style will dictate how well or if you even should consider working in two roles.

As the team manager, you hold authority over performance and career type decisions for your employees.  Wielded incorrectly, the power disparity between you and your employers can ruin your attempts at being part of the development team.

So long as you are aware of that disparity, and you clearly delineate between your roles, I think that you can be both a manager and a developer.  I've seen it done successfully a number of times, and I'm currently working on a team in that same situation.

It's worth noting that you can't eliminate all of the effects of the disparity.  There will be times when you need to bite your tongue and hold back from a spirited debate.  There will be others when you need to pull the trump card and point out that ultimate responsibility for the team lies with you, so you're making a diktat.

You'll need at least two strong, experienced developers on your team who are politically secure.  Their role is to keep the power disparity in check and to call you out if things are getting out of balance.  You could get by with just one other strong developer, but having a second provides objectivity in case the two of you get deadlocked on an issue.

I honestly like it when my immediate supervisor keeps himself technically relevant.  It facilitates their understanding of my difficulties, and I think we end up with a better performing team.


答:
I went through a similar experience before, leading a team of 6 developers in a Scrum team. Besides what pdr and GlenH7 have mentioned, things that helped:

The best tester on the QA team was really good at keeping us accountable for the quality of our work, including the work I did. When I wrote buggy code, she called me out on it in a way that would be hard for another developer to do.

I usually did the Sprint Demos, especially when we had bad sprints. Since I was demoing to the CEO, it was embarrassing when stuff didn't work. Aside from ensuring that I understood features that others developed, it also meant that my stuff had to be as solid as anyone else's.

I let others make decisions. My experience is different from that of GlenH7, I always found it to be a mistake to pull the trump card. Instead, I talked through the different consequences of decisions, and made clear to which ever developer was working on something what the consequences were for the thing I thought was the "wrong" way of doing something. There are many reasons for doing this, but the biggest one is that as team lead, you don't have time to make all the decisions.

Using a product like Sonar can make things like code quality more objective.

Title: Being a team manager and a developer in a Scrum team

Body:
I am managing a team of 6 people that recently moved to Scrum.

We have a Scrum Master (one of the developers in the team) and a Product Owner.

Since I have quite a lot of free time (because a lot of management work that I used to do is now done by the Scrum Master and Product Owner), and since I want to remain technically relevant, I am doing some technical development work.

I act as a part of the development team, commit to some of the stories in each sprint, and participate in all the meetings as a part of the team.

Do you think it is a good idea? Can it contradict the "self-organization" of the team?