问:
How to properly distinguish between MVC and three-tier?
Many webapp frameworks, e.g. Spring,call themselves MVC frameworks, but how is the distinction done between MVC and three-tier? It seems that some frameworks call themselves MVC frameworks but they are really three-tier frameworks, or how do we properly label which is which?</p>

答:
Both frameworks separate presentation logic from Business Logic, however the difference is in how that separation is achieved. With 3 tier I tend to think of the layers sitting on top of each other. With MVC, the components sit side-by-side.

With MVC, the controller is the keystone to the architecture, whilst with n-tier it is the view/UI. With an MVC app you call an Action in the Controller, that may or may not render a view. With a 3-tier app you have to go through the UI.

One of the disadvantages of the n-tier system is that business logic may bleed into the data-layer or into the presentation layer, with MVC, I think, it is much easier to keep proper separation of concerns. That though is my experience and preference.

As others have stated MVC and n-tier are not mutually exclusive. The back-end of most MVC websites I've worked on are n-tier. The controllers call a service, that in turn calls a repository.


问:
Potentially shippable product requires automating tests
To always have a potentially shippable product at the end of each 2-week Sprint, we need to rerun a lot of regression tests at the end of each Sprint. This is very repetitive and time consuming, so eventually it will probably be cost-effective to automate these tests.

However if we don't require a potentially shippable product, but plan for a few stabilization/hardening Sprints, we don't need to rerun all our manual tests each Sprint. In such case automating our tests will not be cost-effective.

So which approach do you prefer, to automate tests, to forgo the shippability advantage, or do you think that this trade-off doesn't actually exist?

答:
At the end of a sprint, whatever you deliver should be of production quality, that's one of the pillars of scrum. If it's not done at the end of the sprint, it could drag on for ages as you find new stuff to add and new stuff to fix. Get it done and get it out the door.
If you need a reason: because you want that feedback only customer usage can get you.

If I dissect your post, what I'm reading is that you're having problems with bugs either way. It's not by running the tests that those bugs will fix themselves, so you're going to wind up with "hardening" sprints regardless.

My advice:

1)Invest in building quality in. If you're having problems with bugs, get the team together and find out why. Don't lay blame, just pose the problem and search for solutions.

2)Are your tests actually in code? Because coded tests are usually trivial to automate.
 If your idea of a regression tests is going through some screens manually, you're going to have to brush up on different levels of testing. UI tests can be automated, but they are the most difficult, so you should try to test as much as you can deeper towards the unit level.

ContentLicense: CC BY-SA 3.0


问:
Could one sample be enough for a perceptron training?
I need to compare a picture and decide whether or not it is similar to another one. In this case, I would like to use a simple perceptron that compares pixelmaps of both pictures. But I have only very basic understanding of neural networks and I am not sure whether this approach will work if there is only one source picture (to train it with). Anything I could do in this case? </p>

答:
When you train a neural network, you need both positive and negative inputs.  If you were to say, only indicate to a neural network that when given an image that it should return 1, when given an image which is not similar, it may return 1 all the same.

And in this circumstance, while there is only 1 image you'd like other images to be similar to, there are many many many images which are not similar that should return 0 or close to 0.  Before the neural network will return results similar to what you'd expect, you must be the one to show it what you expect.

Supposing you wanted to have it match photos containing the same person's face.  You would train your neural network to return 1 in these with precisely that person's face inside the photo.  You would then show it photos of other people's faces and return 0.5.  Then you would show it photos of bridges, buildings, people without closeups and have it return 0.  At this point, you have what would be a very crude face recognition neural network.  I doubt if you would be able to have a neural network provide any value of meaning with just one photo.


答:
As always with neural networks, it's difficult to say anything for sure without actually trying it out. But I think the fact that you've only got one "source" is unlikely to cause problems. In fact, it might simplify things. The important thing is to have lots of images to compare it to for training.

For the structure of the network, I don't think you'd need to supply the source as an input: as it would be the same for all of the training data, it wouldn't actually be doing anything! Instead, the perceptron should learn it from how similar each of the other images are.

Just bear in mind that the perceptron would become trained to that one source, i.e. you wouldn't be able to change the source picture without completely re-training. Also as I said above, make sure you've got a large training set (i.e. the comparison images).

Note: I haven't done much at all with images in neural networks, so I can't comment on some of the other points such as whether pixelmaps would be suitable.

Title: Could one sample be enough for a perceptron training?

Body: I need to compare a picture and decide whether or not it is similar to another one. In this case, I would like to use a simple perceptron that compares pixelmaps of both pictures. But I have only very basic understanding of neural networks and I am not sure whether this approach will work if there is only one source picture (to train it with). Anything I could do in this case? </p>


答:
I think you need to approach this solution in a sprint fashion.

You want to compare the time spent creating automated tests to running them manually. We'll assume you know the cost of doing your manual regression tests or this whole exercise is moot. The key is how effective your team is at creating and maintaining automated regression tests. If you have no experience in this area, this project may not be the time to start learning because you're not going to be very efficient and probably are unable to estimate the amount of time they will take. Still, you can try automating one or two of your tests and see how much time savings you can get along with being able to estimate the time to automate the rest (automation doesn't have to be all or none. Some tests may be easier to just do manually).

Do you know how many sprints are left? Very difficult to do an ROI on comparing savings on two approaches to a repeated task when you don't know how many times you'll repeat it. Maybe you are fairly confident you can come close, but if you feel there may be more sprints involved in this project than you think, even the slightest amount of time savings with automated tests may be a morale booster. If team members find themselves hating doing the tests and would rather tweak pixels in the GUI, automation may save your sanity.

History of projects with and without any integration testing.  Did your team choose to do testing because they dreaded the projects that didn't have it or are you just following the fashion trends? This can be another sanity check. It also is dependent on the number of sprints left. Having a lot of sprints left may not be a sign of "just think how much time we'd save by not doing any regression tests" but "there are a lot of sprints left because this is a very complicated project, so having tests may be more beneficial than we think".

I don't think there is a universal answer for any team to test or not to test and how much should you automate them. Experience has a lot to do with it. Some projects are more conducive to implementing new things more than others. If the though of automating tests is going to throw your team in a panic that this will put the project too far behind, don't do it. On the other hand if they feel like they'd rather spend their weekend writing automated tests if it means they no longer have to keep doing it manually (Isn't this why we wanted to learn how to program?), that may be the route to go. What's the price of a happy team?

Title: Potentially shippable product requires automating tests

Body:
To always have a potentially shippable product at the end of each 2-week Sprint, we need to rerun a lot of regression tests at the end of each Sprint. This is very repetitive and time consuming, so eventually it will probably be cost-effective to automate these tests.

However if we don't require a potentially shippable product, but plan for a few stabilization/hardening Sprints, we don't need to rerun all our manual tests each Sprint. In such case automating our tests will not be cost-effective.

So which approach do you prefer, to automate tests, to forgo the shippability advantage, or do you think that this trade-off doesn't actually exist?


问:
Fixing bugs may lead to delayed feedback
I worked in a group in Microsoft that developed the upgrade to the Microsoft Security Essentials antivirus. For a year we worked on the next version of the product. We had 6 milestones (milestone each two months). Most of the features were developed in the first few milestones, and for the second part of the year these features were refined and bugs were fixed. Each milestone a larger portion of users (subscribed to the various alpha/beta programs) would get the product and provide feedback.

I was told by the program managers in the project that the advantage of this approach is that there is more time for potential users to give feedback on the features, so it is preferable to ship all the features as soon as possible.

However Scrum doesn't advocate this approach. In Scrum are you advised to deliver completely tested and functional piece of software and not half baked and brittle features. This approach has various benefits, but it also has some drawbacks. One of them is that feedback is delayed.

So which approach do you prefer and why?

答:
You may be making an argument to over-engineer this project based on your comments to Julia Hayward's answer. (I think a lot of this should be in the question.).

Well, when I said "ship" I meant ship to alpha/beta users or not even
  ship at all but simply deliver the software for usability tests.

In this case, it seems like your program manager is more the product owner and he is allowed to accept half-baked features.

So yes, it will be only partially functional, not pretty, with some
  bugs, but at least an important feedback can be generated so the team
  will know if its in the right direction.

So now you can take that half-baked "Feature A" and turn it into another request that requires: input checking, error testing, use the new GUI design, etc.

When you go through this alpha/beta route, it's not your code that is half-baked, it's the user stories. Only fulfill the user story so it passes the project owner's approval.


答:
I work in both styles simultaneously, with legacy code thoroughly regression tested only just before an actual release, and more current code tested with automation.

If I had the ability to make a choice to work in only one style, there is no contest - automate the tests and run them as often as feasible.  The code quality is better and issues are discovered while developers still remember what they were thinking about.  They're a lot quicker and easier to fix that way.


问:
Should cucumber step definitions in Java be static methods or instance methods?
We are new to using cucumber with selenium to write automated test suites.

Our initial approach was to have one java class per feature file.

Now we added instance methods in each class for corresponding step definitions.

Now if we need to re-use a step definition in some other feature file we are facing problems as we can't re-use same annotation with same regex pattern with any other method of other class and neither can we use the existing step definition which is in some other class.

These methods are sharing instance variables like the reference to the driver.

Now to re-use an instance method as a step definition is also a problem because these methods are not re-usable outside the class and I can't put all step definitions inside one class.

I looked at some samples of ruby, I found that they write some sort of blocks that don't have access to shared state.
They just execute steps.

So in Java should I always make static methods that will just execute steps one by one and share no state ?

答: I had a similar issue with a shared Selenium web driver. I configure the driver as a Spring bean with singleton scope (this is the default scope), so if you need this bean in many places just access it as a Spring bean.</p>


问:
Highly scalable and dynamic "rule-based" applications?
For a large enterprise app, everyone knows that being able to adjust to change is one of the most important aspects of design. I use a rule-based approach a lot of the time to deal with changing business logic, with each rule being stored in a DB. This allows for easy changes to be made without diving into nasty details. Now since C# cannot Eval("foo(bar);") this is accomplished by using formatted strings stored in rows that are then processed in JavaScript at runtime. This works fine, however, it is less than elegant, and would not be the most enjoyable for anyone else to pick up on once it becomes legacy.

Is there a more elegant solution to this? When you get into thousands of rules that change fairly frequently it becomes a real bear, but this cannot be that uncommon of a problem that someone has not thought of a better way to do this. Any suggestions? Is this current method defensible? What are the alternatives?

Edit: Just to clarify, this is a large enterprise app, so no matter which solution works, there will be plenty of people constantly maintaining its rules and data (around 10).  Also, The data changes frequently enough to say that some sort of centralized server system is basically a must.

答:
I would use WF or Drools if you're trying to create an abstraction that non-programmers could work with to develop business rules.  However, if you're dealing with programmers than the abstraction of WF isn't worth the time it takes to develop a solution, I fail to see the added value for your investment.

A database is a good way to maintain rules that might change a lot, but let me suggest a possible alternative (not necessarily better, but an alternative).

1) Separate out the business logic into its own layer (dll) -- abstracting how you're calling it with some interfaces (look at the strategy and observer patterns) i.e IRuleEvaluator.Evaluate(string myParams).

2) Now you can create discrete classes for each rule (if necessary) and accompanying unit tests.

3) Now for the Pièce de résistance, wire up everything behind the scenes in an IOC container -- the dll and the rule evaluator instance itself.  This way your rule evaluator is constructed through the configuration at runtime -- nothing is hard-coded together.

This approach is very dynamic (maybe too dynamic for some tastes) -- it will allow you to have actual discrete unit tests for your all of your rules.  If you need to re-deploy or change a rule, you can drop a new DLL, change your IOC configuration file, restart and verify -- or roll back the change if something is wrong -- without modifying your core code (just like a database).  And unlike a database, it will keep the logic and application code under one umbrella, instead of half written in C# and half in SQL.

ContentLicense: CC BY-SA 2.5


问:
Corporate website design
We are redesigning our corporate website with the following functions:

we want to give the marketing users flexibility and freedom to add new static pages, change the static pages or contents of static pages without the developer(s)/deployment team getting involved.

we want developers to work on the dynamic portion of the website.

How to architect the website to make sure that the layout/look and feel of the website stays same across all the pages and achieve the above mentioned work?

Any experience? Suggestions?

答: Well, it sounds like you're looking for a Content Management System or CMS. There are dozens of free ones out there on the internet that are pretty easy to setup and use. Although, it seems like you're talking about building this CMS yourself. My suggestion would be to look at some open source CMSs on Google and after you've browsed through a few you can take what you like and don't like from each and build your own.</p>

Title: Corporate website design


答:
MVC is a three-layer (as oppossed to three-tier) approach, in which presentation logic, business logic and persistence logic are logically separated to achieve simplicity and low coupling.

Three-tier goes a step beyond because each tier is also put appart in specialized servers ( phisical layer ).

MVC and three-tier archivtecture are not mutually exclusive.

Title: How to properly distinguish between MVC and three-tier?

Body: Many webapp frameworks, e.g. Spring,call themselves MVC frameworks, but how is the distinction done between MVC and three-tier? It seems that some frameworks call themselves MVC frameworks but they are really three-tier frameworks, or how do we properly label which is which?</p>


问:
How do you manage config with dependency injection?
I am a big fan of DI/IOC. It is great for handling/abstracting away hard dependencies, and makes life a little easier.

However I have a small gripe with it, which I am not sure how to solve.

The basic idea in DI/IOC is that when an object is instantiated, all of its dependencies are pre-filled within the constructor.

However IMHO there are several types of parameters for constructors (especially when your objects are immutable).

Dependencies (Objects required for your object to do work)

Configuration (information about the environment required to do work)

Parameters (Data that work is done on)

I find that IOC works well with dependencies. But I am still trying to work out the best way to deal with the other two. However, since the constructor is run meant to be run by the IOC container, it seems I need to place these items into the IOC container.

I'd like to know what strategies/patterns people employ and what advantages and disadvantages people have found.

NB. I am aware this is a highly subjective question, and have tried to make it a "good" subjective question as per SE guidelines.

答:
What I do is a factory pattern for these cases.

I do not use the object itself as a dependency but create a factory object with a Get method that accepts parameters that can't be bound automatically by the container.

Ex.:

```<code> interface IDependencyObject {
       ....
 }

 class DependencyObject {

      public DependencyObject(int primitive, IAnotherDependency anotherDependency) {
      ...
      }

 }

 class DependencyObjectFactory {

      private readonly IAnotherDependency anotherDependency;

      public DependencyObjectFactory(IAnotherDependency anotherDependency) {
           this.anotherDependency = anotherDependency;
      }

      public IDependencyObject Get(int primitive) {
           return new DependencyObject(primitive, anotherDependency);
      }
 }

 interface IDependencyObjectFactory {
       IDependencyObject Get(int primitive);
 }
</code>```

Body:
What I do is a factory pattern for these cases.

I do not use the object itself as a dependency but create a factory object with a Get method that accepts parameters that can't be bound automatically by the container.

Ex.:

 interface IDependencyObject {
       ....
 }

 class DependencyObject {

      public DependencyObject(int primitive, IAnotherDependency anotherDependency) {
      ...
      }

 }

 class DependencyObjectFactory {

      private readonly IAnotherDependency anotherDependency;

      public DependencyObjectFactory(IAnotherDependency anotherDependency) {
           this.anotherDependency = anotherDependency;
      }

      public IDependencyObject Get(int primitive) {
           return new DependencyObject(primitive, anotherDependency);
      }
 }

 interface IDependencyObjectFactory {
       IDependencyObject Get(int primitive);
 }


问:
Difficulties for functional managers in Scrum
I am a Test/QA manager in an organization that gradually moves to Scrum. I don't appear in daily Scrum meetings because I don't want to interfere with the self-organization of the team. The problem with this is that I am becoming too disconnected with what the 5 testers who report to me do in the day to day. How can I coach and evaluate these testers? What if they don't do good work, or do too little work, how can I know this in a timely basis and act on it?</p>

答:
Have you considered attending the scrums but not talking or participating?

If you state that you are there as a passive participant only, then you will get the information you need.

In the cases when you need follow-up information from a particular tester, you can make a mental note of the item and go ask for more details after the scrum is over.


问:
Why develop free, open source programs?
Why would someone use his own time to develop an open-source project for free and without compensation?</p>

答:
It's not only for making money but more often for saving money.  The vast library of good OSS libraries and tools make it a natural choice.

In same cases (GPL and friends) that means you're legally bound to make the resultant code OSS too.  In other cases, it's just a personal choice, but you still get to receive other rewards (mostly some recognition, sometimes the chance of selling support, sometimes (happened to me) a good reference to show to potential employers)

Title: Why develop free, open source programs?


答:
I have seen two approaches work:

Go to Scrum - I've seen scrums where the manager attends as a "chicken". No talking, no criticizing, no dour face. You're there to gather information. Once everyone is comfortable with this, you can maybe ask short clarifying questions. This may not work well if your team defers to you too much.

Meet independently with PM/Team Lead - Even in self-organized teams someone is the project manager or team lead. They (which one depends on the organization) then become responsible for people doing good work on a day to day basis. You exist to help them raise the skill of the team as a whole, hold them accountable, and to step in when they want/need help with problems that "the boss" needs to deal with. This may not work well if you micromanage too much, or lack a person on the team to fill that role.

Title: Difficulties for functional managers in Scrum

Body: I am a Test/QA manager in an organization that gradually moves to Scrum. I don't appear in daily Scrum meetings because I don't want to interfere with the self-organization of the team. The problem with this is that I am becoming too disconnected with what the 5 testers who report to me do in the day to day. How can I coach and evaluate these testers? What if they don't do good work, or do too little work, how can I know this in a timely basis and act on it?</p>


答:
What are the responsibilities of a Functional Manager to the project teams? This varies a lot from company to company. Therefore, you've got to exploit the opportunities you get to interact with the project team to improve your awareness of team members performance.

Go and see for yourself (in Kanban the principle of "Genchi Genbutsu"
applies). This includes:

Go to Stand Ups. You probably don't need to go every day, but you should probably be going more than once a week. You're a chicken, so don't get too involved. Don't be afraid not to ask difficult questions - or if you feel it would be too disruptive, you should ask the Scrum Master.

Go to Demos. If your guys are part of a functioning Scrum team they will be running a demo every sprint. Some QA teams adopt an unhealthy attitude that they're there to  block releasing. You need to see that your testers are part of teams that always produce potentially shippable software.

Walk around, speak to the whole team, see how they're getting on. Don't do it for the explicit purpose of assessing performance but do it to increase your understanding of project the team works on and how they function. As a Senior member of the QA team, you probably have expertise to offer. You should be helping to coach the team (not just your direct reports).

Speak to your testers on a regular basis. I've got a preference for informal chats, preferably over a coffee out of the office. Build a rapport with your team members and they'll let you know the areas in which they're having difficulties which you can follow up on.

Succeeding with Agile by Mike Cohn has a section in chapter 8 about the role of Functional Manager. Well worth a read, and the part that seems most relevant:

A functional manager is responsible for providing guidance and
  coaching to members of the group. ScrumMasters and product owners also
  provide guidance and coaching, but their views are limited to a single
  project or product. A functional manager will have a broader
  perspective, including the ability to establish cross-project
  standards and set expectations for quality, maintainability,
  reusability, and many of the other -ilities or nonfunctional
  requirements.

Functional managers also retain responsibility for developing the
  people in their groups. Securing the budget and time to send them to
  conferences, challenging them with appropriate projects, and
  encouraging them to join or form communities of practice are all part
  of the functional manager’s role.

Personnel Responsibilities

In most organizations, functional managers will retain responsibility
  for writing periodic reviews of the personnel in their departments.
  Although the functional manager has hopefully always incorporated
  input from each employee’s coworkers and customers into the review,
  the need to do so is greater in a Scrum environment because the
  employee will likely be working less closely with the functional
  manager on a day-to-day basis.

In many organizations, functional managers also retain responsibility
  for making hiring and firing decisions. Neither the ScrumMaster nor
  the product owner has this level of authority over individuals on the
  product development teams.

After the organization adopts Scrum, most functional managers find
  themselves with more time available than they had before. This time is
  most often used to stay in closer touch with their direct reports, to
  know more about each project the group’s employees are working on (by
  attending various sprint reviews and so on), and to pay more attention
  to cross-project standards and future directions.


问:
Am I allowed to use text(snippets) from the iOS Developer Lib for my documentation?
At the moment, I create a Java-Wrapper for Apples *.pkpass-Files (Passbook).
Since I need to parse a JSon-File, I planned to add java doc to every field, so one know what exactly this field is in the pkpass and how it should be displayed. (There are some other meta data which are interesting).

At https://developer.apple.com/library/ios/documentation/UserExperience/Reference/PassKit_Bundle/Chapters/TopLevel.html#//apple_ref/doc/uid/TP40012026-CH2-SW1 you can see a description of this file format.

So, my question is: am I allowed to use text snippets (or the whole text) from the description column when I add also the link to the page into the java doc?

答:
At the following link: Rights and Permissions from Apple's legal page on intellectual property

It says the following:

If you have any questions concerning the usage or licensing of Apple copyrighted materials, for example, photographs, video footage, Apple advertisements or other Apple materials, please submit your detailed request in writing. Please be sure to include any surrounding copy or text to the Apple material.

A couple of years ago I would've said just use the text, especially if this is just some small project.....but with people giving out lawsuits over nothing I think you might wanna ping them and ask.


问:
Android Data persistence question
I have an android app in which users have sets of items, and each item has about 10 properties.

What I do at the moment:

items are stored in the server database

when the user logs in, I get all the items (say 37) via the API and put them in a LinkedHashSet< UserItem > (UserItem is a POJO with setters and getters)

then I get the 37 items from the set and put them in the local SQLite database

when the user opens "My Items" screen in the app, i get the 37 items from the local SQLite DB

I was thinking, is this a good practice? Could I circumvent Step 3(storing items in the local database), but instead maintain the life of that LinkedHashSet object and get the items directly from there. If Im right with this suggestion, how do I do that?

I asked a similar question at Stack Overflow but I was told that I should come here and ask it.

答:
As it's been said in the other answer, you could maintain your LinkedHashSet POJO. In this post, it's explained how to persist a global variable for all the life cycle of the application (it involves extending android.app.Application). This is the fastest way to read and write your data. You can expose it again to local storage or your server DB if you want to. The disadvantage is that if you somehow were to lose that memory, then the changes the user made will be lost.

If you need to sync the data with your sever, then see here for some suggestions on how to update both the data in the device and your server. This will be slower, as you have mentioned yourself.

From here, you can mix both strategies and find a very good solution for your app. Maybe you can program sync routines that are not as aggressive as to impact user experience, maybe you  persist in local storage only when the data changes. You'd have three places to store data, with trade-offs of speed vs data safety.

Good luck!

Title: Android Data persistence question


问:
License for my Software
I am nowhere near good at coming up with what type of license to use and I don't want to be sued or have my work stolen so I am going to ask. Here is my situation: I am creating a software for my boss and the YMCA which helps keep track of our employees, their students, and the amount of lessons they have remaining (In a nutshell but the program is much more extensive then that), I am spent almost 100 hours creating it and its not completely done. Some of the hours spent were at work while being paid (Not sure if that plays a factor). Here is a list of conditions that I desire:

My software to not be redistributed in any way without my knowledge and written consent.

To not be liable for any damage it causes, for maintaining the software, or for its success.

I do not want the software to be sold without my knowledge and consent either.

I want the software to be closed sourced.

If there is a way I can have all of these in my software licensed I would be grateful, also if someone could explain to me where I need the license displayed and if it needs to be in the source code (since I am having it closed sourced).

答:
I assume you are in the USA and a regular non-contract employee of the YMCA.

As an employee, things you produce for your employer as part of your job are a "Work-for-hire." See U.S. Copyright office Circular 9.

As an added complication, it sounds like you are doing some of the work on your own time which potentially runs into labor and wage law.

If you are a non-exempt employee then your employer must pay you for all of the time you are working for them and thus they may technically have pay you for the off-the-clock work you are doing. You are not allowed to "volunteer" to work off the clock -- the law does not allow that and your employer can get into trouble.  To cover themselves legally they may tell you to stop working on this off the clock so they are not at risk.

The moral is: get contracts and agreements in writing before you start work.

I suppose I must add all of the standard notices that I am not a lawyer, etc.

Title: License for my Software


答:
Step 1) Research the content management systems out in the world, as Mickey Sly says.

Step 2) Select one that nearly fits. Implement it as a trial. Present it as a prototype to a pilot team. Re-implement a couple of times.

Step 3) Decide if you need to implement your own CMS. I would be willing to bet a dollar that you don't.

By all means, DO NOT implement a CMS before you have experience with successful implementations. There are far too many poor implementations in the world because the developers didn't understand security, maintainability, flexibility or user experience.

Title: Corporate website design

Body:
We are redesigning our corporate website with the following functions:

we want to give the marketing users flexibility and freedom to add new static pages, change the static pages or contents of static pages without the developer(s)/deployment team getting involved.

we want developers to work on the dynamic portion of the website.

How to architect the website to make sure that the layout/look and feel of the website stays same across all the pages and achieve the above mentioned work?

Any experience? Suggestions?


问:
How to improve upon Bloch's Builder Pattern, to make it more appropriate for use in highly-extendable classes
I have been greatly influenced by Joshua Bloch's Effective Java book (2nd edition), probably more so than with any programming book I've read. In particular, his Builder Pattern (item 2) has had the greatest effect.

Despite Bloch's builder getting me much farther in the couple of months than in my past ten years of programming, I am still finding myself hitting the same wall: Extending classes with self-returning method-chains is at best discouraging, and at worst a nightmare--especially when generics come into play, and especially with self-referential generics (such as Comparable<T extends Comparable<T>>).

There are two primary needs that I have, only the second of which I'd like to focus on in this question:

The first problem is "how to share self-returning method chains, without having to re-implement them in every...single...class?" For those who may be curious, I've addressed this part at the bottom of this answer-post, but it's not what I want to focus on here.

The second problem, which I am asking for comment on, is "how can I implement a builder in classes that are themselves intended to be extended by many other classes?" Extending a class with a builder is naturally more difficult than extending one without. Extending a class that has a builder that also implements Needable, and therefore has significant generics associated to it, is unwieldy.

So that is my question: How can I improve upon (what I call) the Bloch Builder, so I can feel free to attach a builder to any class--even when that class is meant to be a "base class" that may be extended and sub-extended many times over--without discouraging my future-self, or users of my library, because of the extra baggage the builder (and its potential generics) impose on them?

Addendum

My question focuses on part 2 above, but I wanted to elaborate a bit on problem one, including how I've dealt with it:

The first problem is "how to share self-returning method chains, without having to re-implement them in every...single...class?" This is not to prevent extending classes from having to re-implement these chains, which, of course, they must--rather, how to prevent non-sub-classes, that want to take advantage of these method chains, from having to re-implement every self-returning function in order for their users to be able to take advantage of them? For this I've come up with a needer-needable design that I'll print the interface skeletons for here, and leave it at that for now. It has worked well for me (this design was years in the making...the hardest part was avoiding circular dependencies):

```<code>public interface Chainable  {
    Chainable chainID(boolean b_setStatic, Object o_id);
    Object getChainID();
    Object getStaticChainID();
}
public interface Needable<O,R extends Needer> extends Chainable  {
    boolean isAvailableToNeeder();
    Needable<O,R> startConfigReturnNeedable(R n_eeder);
    R getActiveNeeder();
    boolean isNeededUsable();
    R endCfg();
}
public interface Needer  {
    void startConfig(Class<?> cls_needed);
    boolean isConfigActive();
    Class getNeededType();
    void neeadableSetsNeeded(Object o_fullyConfigured);
}
</code>```

答:
I think the question here assumes something from the outset without attempting to prove it, that the builder pattern is inherently good.

tl;dr I think the builder pattern is rarely if ever a good idea.

Builder pattern purpose

The purpose of the builder pattern is to maintain two rules that will make consuming your class easier:

Objects should not be able to be constructed in inconsistant/unusable/invalid states.

This refers to scenarios where for instance a Person object may be constructed without having it's Id filled in, while all pieces of code that use that object may require the Id just to properly work with the Person.

Object constructors should not require too many parameters.

So the purpose of the builder pattern is non-controversially good. I think much of the desire and usage of it is based on analysis that has gone basically this far: We want these two rules, this gives these two rules - though I think it's worth investigating other ways to accomplish those two rules.

Why bother looking at other approaches?

I think the reason is well shown by the fact of this question itself; there is complexity and a lot of ceremony added to structures in applying the builder pattern to them. This question is asking how to resolve some of that complexity because as complexity oft does, it makes for a scenario that behaves strangely (inheriting). This complexity also increases maintenance overhead (adding, changing, or removing properties is far more complex than otherwise).

Other approaches

So for rule number one above, what approaches are there? The key this rule is referring to is that upon construction, an object has all the information it needs to function properly - and after construction that information cannot be changed externally (so it's immutable information).

One way to give all necessary information to an object at construction is simply add parameters to the constructor. If that information is demanded by the constructor, you won't be able to construct this object without all that information, therefore it will be constructed into a valid state. But what if the object requires a lot of information to be valid? Oh dang, if that's the case this approach would break rule #2 above.

Ok what else is there? Well you could simply take all that information that's necessary for your object to be in a consistent state, and bundle it up into another object which is taken at construction time. Your code above instead of having a builder pattern would then be:

```<code>//DTO...START
public class Cfg  {
   public String sName    ;
   public int    iAge     ;
   public String sFavColor;
}
//DTO...END

public class UserConfig  {
   private final String sName    ;
   private final int    iAge     ;
   private final String sFavColor;
   public UserConfig(Cfg uc_c)  {
      ...
   }

   public String toString()  {
      return  "name=" + sName + ", age=" + iAge + ", sFavColor=" + sFavColor;
   }
}
</code>```

This isn't a great deal different from the builder pattern, though it is slightly simpler, and most importantly we're satisfying rule #1 and rule #2 now.

So why not go the bit extra and make it a full on builder? It's simply unnecessary. I satisfied both purposes of the builder pattern in this approach, with something slightly simpler, easier to maintain, and reusable. That last bit is key, this example being used is imaginary and doesn't lend itself to real-world semantic purpose, so let's show how this approach results in a reusable DTO rather than a single purpose class.

```<code>public class NetworkAddress {
   public String Ip;
   public int Port;
   public NetworkAddress Proxy;
}

public class SocketConnection {
   public SocketConnection(NetworkAddress address) {
      ...
   }
}

public class FtpClient {
   public FtpClient(NetworkAddress address) {
      ...
   }
}
</code>```

So when you build cohesive DTOs like this, they can both satisfy the purpose of the builder pattern, more simply, and with broader value/usefulness. Furthermore this approach solves the inheritance complexity the builder pattern results in:

```<code>public class SslCert {
   public NetworkAddress Authority;
   public byte[] PrivateKey;
   public byte[] PublicKey;
}

public class FtpsClient extends FtpClient {
   public FtpsClient(NetworkAddress address, SslCert cert) {
      super(address);
      ...
   }
}
</code>```

You may find the DTO isn't always cohesive, or to make the groupings of properties cohesive they need to be broken across multiple DTOs - this isn't really a problem. If your object requires 18 properties and you can make 3 cohesive DTOs with those properties, you've got a simple construction that meets the builders purposes, and then some. If you can't come up with cohesive groupings, this may be a sign your objects are not cohesive if they have properties that are so completely unrelated - but even then making a single non-cohesive DTO is still preferable due to the simpler implementation plus resolving your inheritance problem.

How to improve the builder pattern

Ok so all of the rimble ramble aside, you have an issue and are looking for a design approach to solve it. My suggestion: inheriting classes can simply have a nested class that inherits from the builder class of the super class, so the inheriting class has basically the same structure as the super class and has a builder pattern that should function precisely the same with the additional functions for the additional properties of the sub-class..

When it is a good idea

Ranting aside, the builder pattern has a niche. We all know it because we all learned this particular builder at one point or another: StringBuilder - here the purpose is not simple construction, because strings couldn't be easier to construct and concatenate etc. This is a great builder because it has a performance benefit.

The performance benefit is thusly: You have a bunch of objects, they're of an immutable type, you need to collapse them down to one object of an immutable type. If you do it incrementally you will here many intermediary objects created, so doing it all at once is far more performant and ideal.

So I think the key of when it is a good idea is in the problem domain of the StringBuilder: Needing to turn multiple instances of immutable types into a single instance of an immutable type.

Body:
I think the question here assumes something from the outset without attempting to prove it, that the builder pattern is inherently good.

tl;dr I think the builder pattern is rarely if ever a good idea.

Builder pattern purpose

The purpose of the builder pattern is to maintain two rules that will make consuming your class easier:

Objects should not be able to be constructed in inconsistant/unusable/invalid states.

This refers to scenarios where for instance a Person object may be constructed without having it's Id filled in, while all pieces of code that use that object may require the Id just to properly work with the Person.

Object constructors should not require too many parameters.

So the purpose of the builder pattern is non-controversially good. I think much of the desire and usage of it is based on analysis that has gone basically this far: We want these two rules, this gives these two rules - though I think it's worth investigating other ways to accomplish those two rules.

Why bother looking at other approaches?

I think the reason is well shown by the fact of this question itself; there is complexity and a lot of ceremony added to structures in applying the builder pattern to them. This question is asking how to resolve some of that complexity because as complexity oft does, it makes for a scenario that behaves strangely (inheriting). This complexity also increases maintenance overhead (adding, changing, or removing properties is far more complex than otherwise).

Other approaches

So for rule number one above, what approaches are there? The key this rule is referring to is that upon construction, an object has all the information it needs to function properly - and after construction that information cannot be changed externally (so it's immutable information).

One way to give all necessary information to an object at construction is simply add parameters to the constructor. If that information is demanded by the constructor, you won't be able to construct this object without all that information, therefore it will be constructed into a valid state. But what if the object requires a lot of information to be valid? Oh dang, if that's the case this approach would break rule #2 above.

Ok what else is there? Well you could simply take all that information that's necessary for your object to be in a consistent state, and bundle it up into another object which is taken at construction time. Your code above instead of having a builder pattern would then be:

//DTO...START
public class Cfg  {
   public String sName    ;
   public int    iAge     ;
   public String sFavColor;
}
//DTO...END

public class UserConfig  {
   private final String sName    ;
   private final int    iAge     ;
   private final String sFavColor;
   public UserConfig(Cfg uc_c)  {
      ...
   }

   public String toString()  {
      return  "name=" + sName + ", age=" + iAge + ", sFavColor=" + sFavColor;
   }
}

This isn't a great deal different from the builder pattern, though it is slightly simpler, and most importantly we're satisfying rule #1 and rule #2 now.

So why not go the bit extra and make it a full on builder? It's simply unnecessary. I satisfied both purposes of the builder pattern in this approach, with something slightly simpler, easier to maintain, and reusable. That last bit is key, this example being used is imaginary and doesn't lend itself to real-world semantic purpose, so let's show how this approach results in a reusable DTO rather than a single purpose class.

public class NetworkAddress {
   public String Ip;
   public int Port;
   public NetworkAddress Proxy;
}

public class SocketConnection {
   public SocketConnection(NetworkAddress address) {
      ...
   }
}

public class FtpClient {
   public FtpClient(NetworkAddress address) {
      ...
   }
}

So when you build cohesive DTOs like this, they can both satisfy the purpose of the builder pattern, more simply, and with broader value/usefulness. Furthermore this approach solves the inheritance complexity the builder pattern results in:

public class SslCert {
   public NetworkAddress Authority;
   public byte[] PrivateKey;
   public byte[] PublicKey;
}

public class FtpsClient extends FtpClient {
   public FtpsClient(NetworkAddress address, SslCert cert) {
      super(address);
      ...
   }
}

You may find the DTO isn't always cohesive, or to make the groupings of properties cohesive they need to be broken across multiple DTOs - this isn't really a problem. If your object requires 18 properties and you can make 3 cohesive DTOs with those properties, you've got a simple construction that meets the builders purposes, and then some. If you can't come up with cohesive groupings, this may be a sign your objects are not cohesive if they have properties that are so completely unrelated - but even then making a single non-cohesive DTO is still preferable due to the simpler implementation plus resolving your inheritance problem.

How to improve the builder pattern

Ok so all of the rimble ramble aside, you have an issue and are looking for a design approach to solve it. My suggestion: inheriting classes can simply have a nested class that inherits from the builder class of the super class, so the inheriting class has basically the same structure as the super class and has a builder pattern that should function precisely the same with the additional functions for the additional properties of the sub-class..

When it is a good idea

Ranting aside, the builder pattern has a niche. We all know it because we all learned this particular builder at one point or another: StringBuilder - here the purpose is not simple construction, because strings couldn't be easier to construct and concatenate etc. This is a great builder because it has a performance benefit.

The performance benefit is thusly: You have a bunch of objects, they're of an immutable type, you need to collapse them down to one object of an immutable type. If you do it incrementally you will here many intermediary objects created, so doing it all at once is far more performant and ideal.

So I think the key of when it is a good idea is in the problem domain of the StringBuilder: Needing to turn multiple instances of immutable types into a single instance of an immutable type.


问:
Does a batch of operations violate REST principles?
Does it violate REST principles for a REST API to support a batch of operations (perhaps with transactional guarantees) that can be added to a queue via a POST?

This design seems outside the scope of REST architecture but not necessarily in violation of it, but I'm looking for authoritative sources here, and/or supporting explanations when/why to avoid or prefer this approach.

For example, the Parse API supports a POST to create a batch of requests, each representing what could be a separate REST request, such as the following (quoting):

```<code>curl -X POST \
  -H "X-Parse-Application-Id: ${APPLICATION_ID}" \
  -H "X-Parse-REST-API-Key: ${REST_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
        "requests": [
          {
            "method": "PUT",
            "path": "/1/classes/GameScore/Ed1nuqPvcm",
            "body": {
              "score": 999999
            }
          },
          {
            "method": "DELETE",
            "path": "/1/classes/GameScore/Cpl9lrueY5"
          }
        ]
      }' \
  https://api.parse.com/1/batch
</code>```

答:
From what I've read this does not violate REST. REST has to do with how the client and server communicate with each other; this communication has to be stateless, i.e. the client calls the server and the server responds, that's it, but that doesn't mean there isn't state involved. REST is also about being able to address resources, and resources have/are state.

One example I read (and I wish I could remember where so I could link it) was about transactions: you could do a POST to create a transaction resource, then do a series of PUTs to modify/update that transaction, then finally do a commit (I forget what HTTP verb this mapped to) to submit the transaction. All of these communications were RESTful (there was no communication channel state) but there was still state in/as the transaction resource.

Adding things to a processing queue en batch strikes me as being similar to the transaction example.

I've not done much REST stuff, but this seems OK to me.

Some somewhat related reading for interested parties


问:
Keep a programming language backwards compatible vs. fixing its flaws
First, some context (stuff that most of you know anyway):

Every popular programming language has a clear evolution, most of the time marked by its version: you have Java 5, 6, 7 etc., PHP 5.1, 5.2, 5.3 etc. Releasing a new version makes new APIs available, fixes bugs, adds new features, new frameworks etc. So all in all: it's good.

But what about the language's (or platform's) problems? If and when there's something wrong in a language, developers either avoid it (if they can) or they learn to live with it.

Now, the developers of those languages get a lot of feedback from the programmers that use them. So it kind of makes sense that, as time (and version numbers) goes by, the problems in those languages will slowly but surely go away. Well, not really. Why? Backwards compatibility, that's why. But why is this so? Read below for a more concrete situation.

The best way I can explain my question is to use PHP as an example:

PHP is loved, and hated by thousands of people. All languages have flaws, but apparently PHP is special. Check out this blog post. It has a very long list of so called flaws in PHP. Now, I'm not a PHP developer (not yet), but I read through all of it and I'm sure that a big chunk of that list are indeed real issues. (Not all of it, since it's potentially subjective).

Now, if I was one of the guys who actively develops PHP, I would surely want to fix those problems, one by one. However, if I do that, then code that relies on a particular behavior of the language will break if it runs on the new version. Summing it up in 2 words: backwards compatibility.

What I don't understand is: why should I keep PHP backwards compatible? If I release PHP version 8 with all those problems fixed, can't I just put a big warning on it saying: "Don't run old code on this version !"?

There is a thing called deprecation. We had it for years and it works. In the context of PHP: look at how these days people actively discourage the use of the mysql_* functions (and instead recommend mysqli_* and PDO). Deprecation works. We can use it. We should use it. If it works for functions, why shouldn't it work for entire languages?

Let's say I (the developer of PHP) do this:

Launch a new version of PHP (let's say 8) with all of those flaws fixed

New projects will start using that version, since it's much better, clearer, more secure etc.

However, in order not to abandon older versions of PHP, I keep releasing updates to it, fixing security issues, bugs etc. This makes sense for reasons that I'm not listing here. It's common practice: look for example at how Oracle kept updating version 5.1.x of MySQL, even though it mostly focused on version 5.5.x.

After about 3 or 4 years, I stop updating old versions of PHP and leave them to die. This is fine, since in those 3 or 4 years, most projects will have switched to PHP 8 anyway.

My question is: Do all these steps make sense? Would it be so hard to do? If it can be done, then why isn't it done?

Yes, the downside is that you break backwards compatibility. But isn't that a price worth paying ? As an upside, in 3 or 4 years you'll have a language that has 90 % of its problems fixed.... a language much more pleasant to work with. Its name will ensure its popularity.

EDIT: OK, so I didn't expressed myself correctly when I said that in 3 or 4 years people will move to the hypothetical PHP 8. What I meant was: in 3 or 4 years, people will use PHP 8 if they start a new project.

答:
I would suggest that newer versions of a language should strive to ensure that 99.99999% of code which compiles in both the old and new versions of the language should work identically in both unless it's deliberately designed not to do so, and that most of the time when the new version refuses code that compiled under the old version, it will be because the code was--at best--dodgy, and should have been written in a different way that would compile under both the old and new compiler.

For example, if I were designing a new language similar to Java or C#, I would forbid implicit type conversions in some contexts where those languages allow them.  As a simple example in C#, given

```<code>int someInt;
double someDouble;
</code>```

the expression someInt.Equals(someDouble) is guaranteed to return false, regardless of the contents of the variables.  It compiles because double can get converted to Object, and int has an Equals overload for that type, so the compiler does the conversion and makes the call.  Were I designing a new version of C# and the .NET Framework, I would have it forbid the boxing conversion since it can't possibly do anything useful.  It's possible there's some program which does such a comparison in a way which is useless but harmless, and having the compiler reject such code might break that program, but correcting or removing such useless code would be an improvement.

As a slightly less clear example, assume

```<code>float f=16777216f;
int i=16777217;
</code>```

and consider the expression f==i.  It's possible that some code does float/integer comparisons and works correctly, but the code should be rewritten as either f==(float)i, (double)f==i;, or (double)f==(double)i; [int to double promotion is lossless, so the latter two would be equivalent].  Some code which directly compares float and integer values may always deal with numbers which are sufficiently small that float and double comparisons would behave identically, but a compiler generally can't know that; code should make clear what kind of comparison is needed, rather than hoping the rules of the language will match the programmer's intention.

Body:
I would suggest that newer versions of a language should strive to ensure that 99.99999% of code which compiles in both the old and new versions of the language should work identically in both unless it's deliberately designed not to do so, and that most of the time when the new version refuses code that compiled under the old version, it will be because the code was--at best--dodgy, and should have been written in a different way that would compile under both the old and new compiler.

For example, if I were designing a new language similar to Java or C#, I would forbid implicit type conversions in some contexts where those languages allow them.  As a simple example in C#, given

int someInt;
double someDouble;

the expression someInt.Equals(someDouble) is guaranteed to return false, regardless of the contents of the variables.  It compiles because double can get converted to Object, and int has an Equals overload for that type, so the compiler does the conversion and makes the call.  Were I designing a new version of C# and the .NET Framework, I would have it forbid the boxing conversion since it can't possibly do anything useful.  It's possible there's some program which does such a comparison in a way which is useless but harmless, and having the compiler reject such code might break that program, but correcting or removing such useless code would be an improvement.

As a slightly less clear example, assume

float f=16777216f;
int i=16777217;

and consider the expression f==i.  It's possible that some code does float/integer comparisons and works correctly, but the code should be rewritten as either f==(float)i, (double)f==i;, or (double)f==(double)i; [int to double promotion is lossless, so the latter two would be equivalent].  Some code which directly compares float and integer values may always deal with numbers which are sufficiently small that float and double comparisons would behave identically, but a compiler generally can't know that; code should make clear what kind of comparison is needed, rather than hoping the rules of the language will match the programmer's intention.


问:
Upgrading old ASP classic to newer standards
For the past year I have been working in a Classic ASP \ ASP.net hybrid. The website has 1M+ hits daily.
The code, as you can imagine, is very hard to navigate. There are 200+ files.
Dozens of includes...

```<code><!--#INCLUDE virtual="sub/head.aspx"-->
</code>```

I need to make a function that would be used throughout the website and I don't even know where to put it. There is no Visual Studio project file.

My questions is... how can I upgrade it to a full ASP.net website. MVC is not an option since the owner is concerned there will be a performance decrease.
I would be happy if I could load it up in VS and have a app_data folder, plus all the goodies of ASP.net (when compared to classic asp)

答:
Classic ASP doesn't have a project file. It is a step above an HTML page, but not by a huge amount.

To convert this, you are going to have to create a new project (web application if you can, it will save you headaches later).

The INCLUDEs should still work in ASP.NET. You might have to modify them slightly. You may also have to turn on a configuration switch in IIS.

All of the server side code will be VBScript. You will have to convert it to either VB.NET code or C#.

If you have data access, it could be DAO, RDO, or ADO. ADO to ADO.NET will be pretty simple to convert. DAO and RDO use similar naming, so it should be straight-forward, if tedious, to convert them as well. Most of the conversion from DAO/RDO to ADO.NET will involve the way you get data into the server page. The Connection object will be similar enough that you may be able to use it directly. From there on out though, you will have to do things ADO.NETs way. Resultsets will need to be changed to TableAdapters, among other changes.

I doubt that you will have to make any changes to your CSS.

Your javascript that is on the page will probably stay the same too.

As for performance, compiled pages or web applications, are very fast and will be faster than the interpreted ASP pages.


问:
How do I make a domain model that doesn't violate OOP?
My game reads a number of JSON files, deserializes them, and hands the resulting objects off to the classes that need them. These deserialized objects, which can be thought of as the domain model, are normally very simple:

```<code>public class Settings
{
    public bool FullScreen = false;
    public int WindowWidth = 800;
    public int WindowHeight = 600;
}
</code>```

But one of these objects is not so simple:

```<code>public class Sprite
{
    [JsonProperty]
    private readonly string assetName;

    [JsonProperty]
    private Vector2 position;

    // other properties...

    public Sprite( string assetName, Vector2 position )
    {
        this.assetName = assetName;
        this.position = position;
    }

    public void Move( Vector2 direction )
    {
        // do move
    }

    // other methods...
}
</code>```

The properties of the Sprite class are private because I want to have good encapsulation. This means it has a constructor that accepts many arguments and several other methods for setting its properties. Also, each property needs an attribute so it can be read by the JSON parser. It looks like a POCO, but I read that POCOs should be persistance ignorant. I could create a simpler domain model that acts more like a DTO to satisfy this:

```<code>public class Sprite
{
    public string AssetName = "default.png";
    public Vector2 Position = Vector2.Zero;
}
</code>```

Now my Sprite class is nice and ignorant. I can write another class to handle business logic type of stuff:

```<code>public class SpriteWhatever
{
    private Sprite sprite;

    public SpriteWhatever( Sprite sprite )
    {
        this.sprite = sprite;
    }

    public void Move( Vector2 direction )
    {
        // do move
    }

    // other methods...
}
</code>```

But then I'm worried that my domain model is anemic. In order to avoid that, I could just make all the properties of the Sprite class public, and keep all the business logic in it, but then I have no encapsulation.

What should I do?

答: I think your approach is on the right direction. One important thing: your domain model is not the Sprite class but the SpriteWhatever class! A real domain model is the place where your business rules and behaviors are located. In your example, this is the SpriteXXX class. The Sprite class is only a data structure for carrying data. Of course this class is anemic, because data structures are anemic by definition. </p>


问:
Should IoC container be part of portable library?
I am seeing the benefits of Portable Class Libraries for centralizing Models and ViewModels to a single code-base. Where should dependency injection management (IoC container) take place, though? My Models have dependencies that I believe would benefit from being supplied through injection. I'm not sure how to go about "bootstrapping" to set up the container in the portable library, and I also saw some suggestions that a portable library shouldn't have a dependency on a DI framework. Those points have me thinking maybe the DI should be set up in the applications that use my portable library. This seems rather backwards though, requiring someone using the library to add the bootstrapping portion to their application, as well as it would be duplicated in every app that uses the library. Should the library or the application handle DI?

Some specifics on what my environment in question is like: c#, WPF application referencing PCL with Models, ViewModels and core logic. Considering using Autofac for my IoC container.

答: No, IoC is outside of the scope of a library usually, as it constricts the use. If the library is only for your own use, of course, you can do anything you wish.</p>


问:
Questions about the issue of getting stuck in a problem, and making snail's pace progress
Let me describe my background.

I am currently a software developer co-op working at an architecture firm that has a large focus on research and development, mainly in mathematical modeling and physics simulations in better aid architecture design.

I am one of the three main software developers. Realistically, we're all people that specialize in different topics, for example, one developer is an architect that's been programming and doing mathematical models since he was in high school (he's like 30 years old), and the other architect also has a Masters in data analytics. We all specialize in different things, making us part of a very multi-disciplinary group of nine people in total.

Currently I am working on a project that handles Grasshopper 3D and Rhino 3D programming, making use of the Grasshopper SDK. I really enjoy what I am doing and appreciate the learning opportunity, however, with that said, the nature of Grasshopper programming has been difficult for me.

I don't think I am that poor programming-wise, however, since most of my projects involve extending functionality beyond what the default Grasshopper SDK does, there are often times I have to spend a good couple hours or even days to understand a problem and then apply code to it. The very nature of this "functionality beyond what the default Grasshopper SDK provides" means that finding a solution to a problem isn't as simple as Googling, because of the relatively rare resources available, whether it's documentation or help threads online.

The nature of getting stuck on an issue and the only remedy to said problem has been slowly chipping away at my confidence, and I evidently see that I am slowing down in shipping out components (that's what Grasshopper 3D "tools" are called).

I've already made a good impression in the first couple months of my co-op in being known as efficient, quick, and comprehensive, however, in my three month review, once I began this task of working on Grasshopper programming, my advisors have noticed that my progress has not been as quick, and they mentioned that they are wondering what/where better to put me to work on that will bring out my full potential.

I like the idea of working on another project, but I do not wish to do so until I've finished the current one I am on, which day by day I feel like I am making snail's pace progress because of some issues I am stuck with where finding help is a problem in itself.

I dislike making a bad impression on my colleagues (and on my school as well, since I am a co-op employee), as I really believe I have the potential to do great. However, this issue of getting stuck on something, making small progresses, then getting stuck again, is simply chipping away my confidence.

What are some things I can do? I feel like once I am stuck on a problem, I find myself closing up, unable to voice it, as if asking for help is a sign of incompetency.

答: You must ask for help when you are stuck, regardless of how it makes you feel. You are using an SDK that is dragging down your productivity; it is not your fault. You cannot be considered incompetent. It is always easier to work on stand-alone code that does not depend on third party libraries, or only uses well designed, mature libraries. Your best choice in this case is is to ask for help, and publicly complain about deficiencies in the library.</p>


答:
If you need IoC in your library then it may be helpful to provide hooks so a user can use the same containers, but don't require it as the developer may want to use something else.

So make it available since you will include it, but don't limit the programmer's options, if possible.

Title: Should IoC container be part of portable library?

Body:
I am seeing the benefits of Portable Class Libraries for centralizing Models and ViewModels to a single code-base. Where should dependency injection management (IoC container) take place, though? My Models have dependencies that I believe would benefit from being supplied through injection. I'm not sure how to go about "bootstrapping" to set up the container in the portable library, and I also saw some suggestions that a portable library shouldn't have a dependency on a DI framework. Those points have me thinking maybe the DI should be set up in the applications that use my portable library. This seems rather backwards though, requiring someone using the library to add the bootstrapping portion to their application, as well as it would be duplicated in every app that uses the library. Should the library or the application handle DI?

Some specifics on what my environment in question is like: c#, WPF application referencing PCL with Models, ViewModels and core logic. Considering using Autofac for my IoC container.


问:
How to make it obvious that a function is being accessed from the outside?
This is a C specific question. I am trying to keep everything possible inside the translation unit boundaries, exposing only a few functions through the .h file. That is, I am giving static linkage to file-level objects.

Now, a couple of functions need to be called by other modules, but not directly. My module/file/translation unit subscribes to the other modules, passing a pointer to a function. Then, upon a specific event, the pointer is called with some arguments.

So I am wondering how to make it very obvious that those functions are called from some obscure location.

Should they be static or extern (and expose them in the .h) ?

Should I include some hint in the name of the functions?

Or is it enough to put a comment "called by X"?

答:
Scope modifiers should be used primarily as information for the compiler, not as a form of "close enough" documentation.  The use of static in particular permits a C compiler to make the function unusable from outside the module, including as a callback - not what you want, even though it may work with your current compiler.

Of course you should add a comment to the code, since you can see it is a potentially confusing situation. Anything unusual or unexpected needs a suitable comment. But, as stated in other answers, comments can go unread or become out-of-date.

So, the only option left is to name the function to indicate it is a callback. Most examples I have seen use _callback or _cb as a suffix, or cb_ as a prefix. Use the long form if callbacks are unusual in your code, the short form if they are common.


问:
How do I maintain consistency between hard-coded values in different files?
I have a C source file and another (non-code) file in a project which contain the same hard-coded value. Ideally, the value would be specified in only one location and be copied to the other location automatically during the build process. It's not hard to think of hackish ways to accomplish this task, but I want to know if there is a common way of doing it.

What standard method or approach should I use to guarantee that the two values remain consistent?  In other words, how should I maintain consistency in a non-hackish way?

答:
Avoid hard coded values in you programs - they will need to change at some stage so make them easy to change (even if they are compiled into an executable, you will at some stage need to change them, unless they are universal constants like Pi, or the speed of light). Also they will often change between environments, so make them easy to maintain by putting them in a file or database.

You have not specified what the other location is, but you have some options,

use a parameter file - this could be an header file that the "other" process can read if, for performance reasons, needs to be pre-compiled into the executable, or read in during the initialization of the program.

store the values in a database - this would allow you to encrypt the value if needs be (eg it is a connection string).

Pass them to the program at run time as start up arguments. You could then write a wrapper script to read from the "other" source to run the program with these arguments.


答:
the value would be specified in only one location and be copied to the other location automatically during the build process

That's exactly the way to solve the problem - but you have to decide in which location you want to maintain the values, and which location is the one where only the copy "lives". You should also take some precaution that no one starts to change the values in the copy (for example, by adding a BIG remark on top of the list like these values are auto-generated - don't change them manually.

Here are some different ways I have solved similar requirements in the past on my own:

maintain the values in an Excel sheet and add a VBA macro to generate all destination files from there (like your C code and your non-code file)

maintain the values in a header file in code, include that header file in a generator tool which produces the non-code file and compile and run that generator within your build process

maintain the values directly in the non-code text file (assumed its machine-readable) and generate the C code as an includable header from there, using some script written in your favorite scripting language.

Title: How do I maintain consistency between hard-coded values in different files?

Body:
I have a C source file and another (non-code) file in a project which contain the same hard-coded value. Ideally, the value would be specified in only one location and be copied to the other location automatically during the build process. It's not hard to think of hackish ways to accomplish this task, but I want to know if there is a common way of doing it.

What standard method or approach should I use to guarantee that the two values remain consistent?  In other words, how should I maintain consistency in a non-hackish way?


问:
Code ownership with multiple Scrum teams
If two Scrum teams use the same software component, who is responsible for providing a clear architectural vision of that component and maintain/develop this vision as the code base evolves? In Scrum you are supposed to have a collective code ownership, so how to make sure that development done by Team A doesn't interfere with development done by Team B?</p>

答:
I am not a Scrum expert, but AFAIK "collective code ownership" is meant to be per team and per product (and I think your question is not specific to Scrum, it could be applied to any "shared code" development process).

If you have two teams A, B, two products A, B and a shared component C, there are different possible scenarios. Maybe the shared component belongs primarily to product A (and is just reused, but not evolved, by the team for product B). In this situation team A is clearly responsible for the architectural vision. Or vice versa: it belongs clearly to product B - so the responsibility is there. If team A is responsible, team B might use a fork of the component to allow urgent bugfixes (there should also be a way to reintegrate them into the main line of C), but B should avoid doing any bigger evolvement of the component.

However, if both products A and B have a lot of "driving requirements" for C, you should manage C as a completely separate product, with own versioning, release management, change management, unit tests etc, and an separate team which has the responsibility for that component. That team could be just a "virtual team", consisting of separate devs from team A, B or both. This team has the "shared code ownership" for C, and the responsibility for the "architectural vision". Just think of C beeing a component delivered by a third-party vendor.


答:
For example, spotify uses a role named "System Owner" to solve the problem, directly from the document:

Technically, anyone is allowed to edit any system. Since the squads
  are effectively feature teams, they normally need to update multiple
  systems to get a new feature into production. The risk with this model
  is that the architecture of a system gets messed up if nobody focuses
  on the integrity of the system as a whole.

To mitigate this risk, we have a role called “System Owner”. All
  systems have a system owner, or a pair of system owners (we encourage
  pairing). For operationally critical systems, the System Owner is a
  Dev-Ops pair – that is, one person with a developer perspective and
  one person with an operations perspective.

The system owner is the “go to” person(s) for any technical or
  architectural issues related to that system. He is a coordinator and
  guides people who code in that system to ensure that they don’t
  stumble over each other. He focuses on things like quality,
  documentation, technical debt, stability, scalability, and release
  process.

The System Owner is not a bottleneck or ivory tower architect. He does
  not personally have to make all decisions, or write all code, or do
  all releases. He is typically a squad member or chapter lead who has
  other day-to-day responsibilities in addition to the system ownership.
  However, from time to time he will take a “system owner day” and do
  housekeeping work on that system. Normally we try to keep this system
  ownership to less than a tenth of a person’s time, but it varies a lot
  between systems of course.

I really like this idea, having the benefits or collective code ownerships at company level (not only in team level) but with this systems owners trying to ensure some architectural integrity.

A link to the complete document: https://dl.dropboxusercontent.com/u/1018963/Articles/SpotifyScaling.pdf , its a short but very, very interesting document based in real experience about scaling agile.

Title: Code ownership with multiple Scrum teams

Body: If two Scrum teams use the same software component, who is responsible for providing a clear architectural vision of that component and maintain/develop this vision as the code base evolves? In Scrum you are supposed to have a collective code ownership, so how to make sure that development done by Team A doesn't interfere with development done by Team B?</p>


问:
Does DDD make sense for apps which mostly present data?
I'm responsible for designing a dashboard and data manipulation front-end for a sale transaction database and am not quite sure what type of architecture to use. The database is populated by an external ETL system.

The required functionality for my app is very simple; it must display a few alerts of exception conditions it detects in the database, present a few charts and tables, and some basic CRUD operations on a few tables. There is very little behaviour required; the business will use the app to find out about things, rather than do things.

Given this lack of behaviour, does a DDD approach make sense? My current thinking is to create database views to encapsulate the queries my app will need, wrap these views up with an ORM, and have the web controller query the repository layer to get an ORM object with the data it needs. This ORM object would then be passed into the presentation layer.

This does of course create strong coupling between the database, the ORM framework, the presentation layer, and my logic. A reasonable amount of what logic there is would wind up in the database views.

Can I make a DDD approach work for this kind of app, or is there a more suitable way of doing it?

答:
If there is little behavior a DDD approach can be overkill, its your application its totally data-centric and with little logic probably the coupled solution can be a good decision. I don't know what technology are you planning to use, for a system like that i probably choose a framework like rails, grails or django an use ActiveRecord pattern.

The worst with this coupled systems is when you ends up unconsciously with a system like that, but if your take a conscious decisions based in your knowledge about the problem, things like DDD or ORM's are only tools in your toolbox and you pick up the right one for the project at hand.


问:
Is java.util.prefs.Preferences appropriate for accessing changes in state that need to be immediately accessed during runtime?
In my application, I'm currently creating a single instance of a UserPrefs object at startup, then passing a reference to that object to multiple other objects through their constructors.

I am doing this because it's important that multiple classes have immediate access to any real-time changes the user makes to their preferences during runtime.

The problem is that passing this object to many different constructors seems messy to me, and I'd like to move away from this. So I'm interested in possibly using the java.util.prefs.Preferences API in each class that needs access to this information. But I get the sense that the Preferences API is more commonly used to simply save a snapshot of user preferences at application shutdown, then to load them back in during startup.

So my question is: Would java.util.prefs.Preferences be appropriate in this situation?  If not, is there some other way I can share preferences state in real-time across multiple classes?

答:
As the documentation suggests,

This class allows applications to store and retrieve user and system preference and configuration data. This data is stored persistently in an implementation-dependent backing store. ... The user of this class needn't be concerned with details of the backing store.

So this class is basicly for safely storing and retrieving specific information. It wouldn't really serve your need in terms of notifying other objects of changes.

I'd suggest you take a look into the Observer design pattern. It allows an object to maintain a list of "observers", which need to be notified if the state of the object changes. So instead this object having to be passed to different constuctors, you'll have one place to handle the state changes and notify the interested objects.


答:
There is no concept of "clear architectural vision" in Scrum or agile!

I have long been an architect, and it's clear to me that in order to have have an architectural vision one needs to have a clear view of future requirements. Since in most cases the requirements aren't clear at all, it doesn't make sense to have a fixed vision.

What is necessary is to have an architecture which is adaptable enough to the changing requirements. In other words, things change, and the architecture changes - I am not advocating a "soft" architecture that can be reconfigured. I am talking about accepting that the architecture one has today will be obsolete soon and will need to be changed, so no one should "marry" to it.

Collective code ownership means that everyone should - in theory - be able to change anything. This has to be understood as the "opposite of silos". In other words, there can be skills barrier in place, which is normal and expected -- not everyone is an experienced DBA that can fine tune SQL queries, to give an example -- but from this it does not follow that only a DBA can hand optimize queries. There will be a "feature domain expert" that can help other people become proficient, but the tasks should still fall on everyone.

For example: if I am the domain expert on feature "A", then I still expect anyone else to do work on feature "A", but I am likely to be consulted when major changes need to happen or people need help. Feature "A" would certainly not be my feature. It will be a feature which I know well. It will be my interest to know many more features, and other people's interest to know this feature.

In synthesis: architecture is designed and redesigned multiple times by developers as the requirements emerge and change. Everybody is expected to make any necessary changes according to their skills, and know when to ask for help. There is no long term vision on the architecture because we trust the people and we do not trust the requirements.


问:
'Game loop' in a non-game application?
In real-time games, there is always a game loop that runs every few milliseconds, updates the game with new data and repaints the entire screen.

Is this something that is seen in other types of applications, other than games? A 'constant-update-loop'?

For example, imagine an application like MSPaint. The user can draw lines on the screen with the mouse. The line that is being drawn is displayed on the screen as it is being drawn.

Please imagine this line is actually made of a lot of smaller lines, each 2 pixels long. It would make sense to store each of these small lines in a List.

But as I said, the line that is being drawn (the large line, made out of lots of small lines) is displayed as it is being drawn. This means that a repaint of the screen would be necessary to display the new small line that was added the previous moment.

But - please correct me if I'm mistaken - it would be difficult to repaint only the specific part of the screen where the new small line was drawn. If so, a repaint of the entire screen would be necessary.

Thus it would make sense to use an 'update loop' to constantly repaint the entire screen, and constantly iterate over the list of lines and draw these lines over and over again - like in games.

Is this approach existent in non-game applications, and specifically in 'drawing' applications?

Thanks

答:
In games constant redrawing makes sense, because it is rare for whole image not change than small part of it.

Then there is case of UI, in which redrawing just part of the screen is exceedingly common. When you push button, only the visual of the button changes, and not anything else. So it makes sense to redraw just the button. Rest of the screen is saved in static image. Many of the visual glitches actually come from partial UI update. It is actually not that difficult.

Drawing applications are somewhere in the middle. They don't need constant updates but on the other side, when they do update, they update the whole image. For example 3D editors use pseudo-loop that only runs while user is editing the model but otherwise stays still. Also, modern graphics cards allow composition of multiple layers of images so whole image consists of many small images and changes are done to those small images, but the whole image is repainted every time small change occurs. Many 3D accelerated UI frameworks are like that. But this redrawing might also happen only when something changes. Constantly redrawing a screen when nothing changes eats too much energy.

To sum it up, this issue is much more complex than having or not having a loop that constantly updates the screen. But generally speaking, games are only software that actually need such constant updates. Everything is fine with on-demand updates.

Title: 'Game loop' in a non-game application?


答:
Take note that most of what happens in your computer is based on some kind of such a "game-like" loop. For example take your video card. The Open GL library taps into it via such a loop, and the Open GL API gives you hooks into that loop (like call-back functions for certain parts of the loop, when it's idle, when it's about to run etc). In fact, when you make a game using open GL, you have the option of not making the graphics-refresh part of te game loop "by hand" at all, and just letting the Open GL loop drive your game's graphics refreshing.

Similarly, JavaScript in the browser already creates a similar loop for you. This is something that is part of HTML5, and this particular API is not final now. It's called "requestAnimationFrame" and it basically promises to notify a function of your choice, each time the system is ready (about to) refresh the graphics (and you can only update the graphics-related state at this point, so as to compute it only when necessary, aka only when it is possible to make it visible via a new graphics refresh).

As for the issue of whether it's better to update only a portion of the screen or all of it, I believe the preferred option is to redraw it all, for multiple reasons (some of which you also mention):

avoid "flickering-like effect". The new screen is drawn "off-screen" completely, and only when its creation is done, is he actually shown on screen (double-buffering). This is because if it were to be drawn in real time, those real-time computations may make it that it takes too long for the drawing to happen, and this may be perceived as a "screen-flicker" by the user

in certain contexts it may be easy to quickly compute which part of the screen has been modified, and only repaint that. For example Java's Swing library allows you to do that (basically declare a rectangular sub-area of the screen which you want to update). Things can gen tricky fast, if everything can potentially move on the screen (as a contrast to your line-drawing example, imagine a game like Starcraft, where the player can scroll around the game area at any moment, thus rendering the whole screen "obsolete").

certain platforms don't support this partial screen refresh. For example certain Open GL implementations may offer non-standard ways to do this, but then you get tied in to that certain implementation, you lose portability... it's not great.

At any rate, IMHO, the purpose of the game-loop is not simply to give you "continuous screen refresh" due to the ever-changing, real-time ways in which games behave. As I said, such a "best effort" infinite refresh loop is already present in many platforms (add Java's Swing to those mentioned above). The game loop's main point is to regulate that loop, to make sure that no matter what happens, certain things move at a fixed speed. That a 3 seconds animation will always run in 3 seconds (even if this means skipping some parts of it on slower computers). This is very crucial for games, you can't have a player execute a complex, 15 buttons combo, and not have its animation run exactly at the same speed each time (and on as varied hardware as possible).

Obviously, other types of applications may require this kind of precision as well (and hence, need to implement something very similar to a game loop to achieve it). Imagine you make a word text processor, and for some reason you think it's a good idea to have a paper-clip-like character pop up and talk to the user. Now let's say you deem it acceptable that the initial pop-up animation for this guy should run in 2 seconds (a word processor user doesn't want to spend time looking at animations - apparently). You want to make sure that that animation will be 2 seconds long on either a ultra-portable laptop, as well as on a heavy gaming rig. The game loop, with it's ability to constantly self-regulate it's state-refresh-rate is perfect for achieving this.

Title: 'Game loop' in a non-game application?

Body:
In real-time games, there is always a game loop that runs every few milliseconds, updates the game with new data and repaints the entire screen.

Is this something that is seen in other types of applications, other than games? A 'constant-update-loop'?

For example, imagine an application like MSPaint. The user can draw lines on the screen with the mouse. The line that is being drawn is displayed on the screen as it is being drawn.

Please imagine this line is actually made of a lot of smaller lines, each 2 pixels long. It would make sense to store each of these small lines in a List.

But as I said, the line that is being drawn (the large line, made out of lots of small lines) is displayed as it is being drawn. This means that a repaint of the screen would be necessary to display the new small line that was added the previous moment.

But - please correct me if I'm mistaken - it would be difficult to repaint only the specific part of the screen where the new small line was drawn. If so, a repaint of the entire screen would be necessary.

Thus it would make sense to use an 'update loop' to constantly repaint the entire screen, and constantly iterate over the list of lines and draw these lines over and over again - like in games.

Is this approach existent in non-game applications, and specifically in 'drawing' applications?

Thanks


答:
We use ninject on an internal project, what I've been doing is setting up an installer module for the libraries so that when I reference them I can just pass it to the kernel setup in the main project. </p>

<p>This seems to be the best of both worlds, there's no real dependency on ninject in the library as you don't need to use the module, it just speeds things up if you are. </p>

Body:
We use ninject on an internal project, what I've been doing is setting up an installer module for the libraries so that when I reference them I can just pass it to the kernel setup in the main project.

This seems to be the best of both worlds, there's no real dependency on ninject in the library as you don't need to use the module, it just speeds things up if you are.


问:
Good idea to put bug numbers in a comment in the beginning of the source file?
Is it a good practice to put bug numbers in the file itself inside a header comment?

The comments would look something like this:

```<code> MODIFIED    (MM/DD/YY)
 abc 01/21/14 - Bug 17452317 - npe in drill across in dashboard edit mode

 cde 01/17/14 - Bug 2314558  - some other error description
</code>```

It seems helpful, but is it considered bad practice?

答:
The project I am currently assigned to at work had this type of bug numbers list at the start of every file; however, none of the developers still on the project append to it anymore. Most of them think it's a useless waste of space, as it is far inferior to tracking bug commits to a file using our version control system.

In certain critical files that have undergone many fixes and enhancements, these lists have become so large you have to scroll past them to get to the code. When greping these lists can result in several false positives as a short bug title or short description is listed with each.

In short, these lists are at best useless and at worst a massive, chaotic waste of space that makes code harder to search through and locate.


问:
How to organize repositories for a split library?
I have two libraries that implement a protocol: one provides tools for establishing a channel between two parts, and the other provides classes and tools for building and parsing the binary protocol messages.

These two libraries can be used independently, they don't depend on each other, and each has its own build setup. However, they do share a common set of examples (using both libraries) and documentation (tutorials).

I have two alternatives in mind for organizing this in Git repositories:

Alternative 1

Make each library be in its own repository. A central repository would keep the common documentation, examples and tools for cloning both repositories and bootstraping them. Users would use this main repository, and developers would work on the dedicated repositories.

I don't want to use Git submodules since they are hard to manage this way (versioning becomes much harder to do when the libraries constantly change).

Alternative 2

Place it all together: both libraries, documentation and examples. Versioning would be applied to both libraries, since they would be treated as a single (though separated) entity.

This is how we are doing it now. It makes things simpler but I feel it could be improved.

So... what are the best practices for organizing it all using Git? I'm open to other alternatives too.

Even though we're not using it right now, it's possible that we will be using continuous integration tools, automated testing and builds, etc.

答:
Source code repositories (i.e. git or other vcs) should be organised for the convenience of those who work on the source code; fix, extend and release it.

Binary repositories (i.e. Debian, maven-based repositories, etc.) should be organised for the convenience of those who work with the libraries.

Sometimes, in the short term, you use the source code repository to deliver stuff to your end-users, just because anything else would be overkill. In that case, then by definition it's not worth reorganising things for their convenience; what you are doing is either too simple, or has too few end-users. If that changes, then set up a binary repository rather than reorganise.

As you say you want to version the two things together, that suggests a single repository. And it doesn't sound so big that you are hitting the point you want to split the repository for performance reasons.


答:
The answer that isn't always as obvious as it could be is to let the teams decide how they're going to share any given component.

For example, my team recently started developing a new product line that shares a lot of code in common with two other teams who have been developing similar products for a long time.  Our product is different in a few ways, so we occasionally have to figure out ways to add customization points to the common code.

We've had some clashes about that code, and tried a few different ad hoc ways of dealing with the common ownership.  Then with a large new feature coming up, we decided we needed to get all the teams together to get on the same page, which resulted in a smaller group composed of a couple members from each team who are working out the details.

The solution our teams came up with might not work in another situation.  You might need something more simple, or something much more formal.  The point is, you take collective ownership and figure out what works for you.