问:
Multi-platform Map Application
I'm working on a web project (PHP, jQuery) which currently using Google Maps powering up the map functionality of the application, however we need to make it multi-platform like you can go to the dashboard and choose one from 5-10 map providers (which Goolge Maps is just one of them) to underlying your map functionality.

So, as the application is supposed to show the data on map, almost in every single place we have to deal with the API provided by that specific map provider. Currently we are thinking about revising our modular structure and/or making something like an adapter for each provider to deal with their native syntax but via our standard methods.

I wish to have your ideas and your experiences, specially if you ever made an interface for dealing via 2-3 different map providers. That would helps much and I really appreciate that.

If you need any further information, just ask me to update the question.

Update:

As Vicky Chijwani suggested Mapstraction, now I'm also wondering which one is more better (pros & cons), having an adapter implemented on Javascript or PHP?

答:
An adapter strategy sounds good enough for this case, i.e., define a common interface and then proceed to implement that interface for each provider. The choice for which map provider to use can be a configurable option in the settings.

Also see Mapstraction, a JavaScript library that provides a common interface for several map providers, including Google, Bing, Yahoo, and OpenStreetMap. It is licensed under the BSD license.

UPDATE [25th Oct '12], taken from my answer to your other follow-up question, for completeness here:

As far as I can see, there are no benefits to implementing your adapters on the server-side rather than in JavaScript. In fact you would be better off with JavaScript because it is the ubiquitous language of the web; if in the future you decide to re-write your backend using another technology, you wouldn't have to re-write the adapters.

If you're hesitant to go with JavaScript because you don't have enough experience with it, even then my suggestion would remain unchanged, because every modern, client-heavy web application demands that you be comfortable with it.

Besides, you're getting a mature, tested JavaScript adapter library - with a fairly permissive BSD license - in the form of Mapstraction, which I mentioned above, so that's a very good option if you can use it. Either way, I think JavaScript is the way to go for you.

Title: Multi-platform Map Application


问:
Learning Java with a simple project
As i remember the time when i was learning PHP, it was suggested to build a simple blog or a forum after reading the language fundamentals. I was told/read that this would cover everything that I would need to learn about PHP from a beginners book.
This advice was out there in a number of places, and after following and working with PHP it seems quite good advice. </p>

<p>Now, i am learning Java and reading the book "Thinking in Java" by Bruce Eckel. I wonder if there is any such set of similar, small projects that I could take up, that would cover all the essentials and most of what is covered in the book. </p>

答:
Start with a small project. If you jump start with android programming, you will end-up spending more time for each simple things you need to do -on a later stage.

Start with a simple java project that uses command-line input, does some calculation and makes REST call to a php backend(this will be useful in android)
(for example: accept 2 numbers as argument, and operation as 3rd arg, and perform the operation(+, -, * or /) and post the result to some URL. you can search on using an API for REST calls.
display the result for REST call on CLI.

follow best practices and nice packaging/coding standards as stated on Oracle web sites. I think this will be good enough for your start-up

ContentLicense: CC BY-SA 3.0

Title: Learning Java with a simple project


问:
What's the best way to manage reusable classes/libraries separately?
When coding, I naturally often come up with classes or a set of classes with a high reusability. I'm looking for an easy, straight-forward way to work on them separately.
I'd like to be able to easily integrate them into any project; it also should be possible to switch to a different version with as few commands as possible.

Am I right with the assumption that git (or another VCS) is best suited for this? I thought of setting up local repositories for each class/project/library/plugin and then just cloning/pulling them. It would be great if I could reference those projects by name, not by the full path. Like git clone someproject.

edit: To clarify, I know what VCS are about and I do use them. I'm just looking for a comfortable way to store and edit some reusable pieces of code (including unit tests) separately and to be able to include them (without the unit tests) in other projects, without having to manually copy files. Apache Maven is a good example, but I'm looking for a language-independent solution, optimally command-line-based.

答:
I would keep them in a repos somewhere and then use a package tool to include them in my projects.

.NET has nuget.

Javascript has npm

Ruby uses gem

etc.


问:
How to justify rewriting/revamping legacy software in a business case?
I work for a great little software company which makes good revenue from our main software package.  The problem for me is that it's almost unmaintainable.  It's written in Delphi 7 (has upgraded versions over time) and has been worked on by a lot of developers over the past 20 or so years.

The software lacks any meaningful architecture - there's no object orientation whatsoever, horrible amounts of cyclical dependencies and an over-reliance on global variables to name just a few things.  Another huge thing for me is Delphi 7 does NOT support 64-bit.

The problem here for me is that my management team don't care about technical things, they want to know why they should care.  Obviously that's expected, so what I'm asking here is for some guidance, or tales, or pitfalls about this kind of thing.

There's a few things I would love to include, namely for me, the length of time taken to debug/write a feature in "legacy" code, versus coherent, well structured OO code.  Does anyone know of any blog posts or the like where this is talked about?  For us in the company this is a huge reason.  Despite being decent developers we feel like writing a new feature is just piling more rubbish on top.  On top of that, even for me who has a decent level of understanding of the code, changing things is infuriating - a small change can have a ridiculous domino effect.

Anyone have any experiences they'd like to share?

答:
Does anyone know of any blog posts or the like where this is talked about?

Yes, here are two articles that you should review and forward to your management:

A Mess is not a Technical Debt

Technical Debt Quadrant

And here are two points about legacy software to be mindful of:

Legacy software that is difficult to modify will:

Limit a company's options for the future (assuming that the company isn't looking to just milk the cash-cow).

Frustrate current developers and impact a company's ability to attract and retain new talent.


问:
Are long methods always bad?
So looking around earlier I noticed some comments about long methods being bad practice.

I am not sure I always agree that long methods are bad (and would like opinions from others).

For example I have some Django views that do a bit of processing of the objects before sending them to the view, a long method being 350 lines of code. I have my code written so that it deals with the parameters - sorting / filtering the queryset, then bit by bit does some processing on the objects my query has returned.

So the processing is mainly conditional aggregation, that has complex enough rules it can't easily be done in the database, so I have some variables declared outside the main loop then  get altered during the loop.

```<code>variable_1 = 0
variable_2 = 0
for object in queryset :
     if object.condition_condition_a and variable_2 > 0 :
     variable 1+= 1
     .....
     ...
     .
      more conditions to alter the variables

return queryset, and context
</code>```

So according to the theory I should factor out all the code into smaller methods, so That I have the view method as being maximum one page long.

However having worked on various code bases in the past, I sometimes find it makes the code less readable, when you need to constantly jump from one method to the next figuring out all the parts of it, while keeping the outermost method in your head.

I find that having a long method that is well formatted, you can see the logic more easily, as it isn't getting hidden away in inner methods.

I could factor out the code into smaller methods, but often there is is an inner loop being used for two or three things, so it would result in more complex code, or methods that don't do one thing but two or three (alternatively I could repeat inner loops for each task, but then there will be a performance hit).

So is there a case that long methods are not always bad? Is there always a case for writing methods, when they will only be used in one place?

UPDATE:
Looks like I asked this question a over a year ago.

So I refactored the code after the (mixed) response here, split it into methods. It is a Django app retrieving complex sets of related objects from the database, so the testing argument is out (it would have probably taken most of the year to create relevant objects for the test cases . I have a "this needs done yesterday" type work environment before anyone complains).
Fixing bugs in that part of the code is marginally easier now, but not massively so.

before :

```<code>#comment 1
bit of (uncomplicated) code 1a
bit of code 2a

#comment 2
bit of code 2a
bit of code 2b
bit of code 2c

#comment 3
bit of code 3
</code>```

now:

```<code>method_call_1
method_call_2
method_call_3

def method_1
    bit of (uncomplicated) code 1a
    bit of code 2a

def method_2
    bit of code 2a
    bit of code 2b
    bit of code 2c

def method_3
    bit of code 3
</code>```

答:
Truth is, it depends. As mentioned, if the code does not separate concerns and tries to do everything in one method then its a problem. Separating code into multiple modules makes it easier to read code, as well as write code(by multiple programmers). Adhering to one module(class) per source file is a good idea to begin with.

Secondly, when it comes to functions/procedures:

```<code>void setDataValueAndCheckForRange(Data *data) {/*code*/}
</code>```

is a good method if it checks for the range of only "Data". It is a BAD method when the same range applies for multiple functions(example of bad code):

```<code>void setDataValueAndCheckForRange(Data *data){ /*code */}
void addDataValuesAndCheckForRange(Data *result, Data *d1, Data *d2){ /*code*/}
void subDataValuesAndCheckForRange(Data *result, Data *d1, Data *d2){ /*code*/}
void mulDataValuesAndCheckForRange(Data *result, Data *d1, Data *d2){ /*code*/}
</code>```

This has to be refactored to:

```<code>bool isWithinRange(Data *d){ /*code*/ }
void setDataValue(Data *d) {/*code*/ if(isWithinRange(d)){/*continue*/}else{/*warn/abort*/}
void addDataValue(Data *d, Data *d1, Data *d2) {/*code*/ if(isWithinRange(d)){/*continue*/}else{/*warn/abort*/}
void subDataValue(Data *d, Data *d1, Data *d2) {/*code*/ if(isWithinRange(d)){/*continue*/}else{/*warn/abort*/}
void mulDataValue(Data *d, Data *d1, Data *d2) {/*code*/ if(isWithinRange(d)){/*continue*/}else{/*warn/abort*/}
</code>```

REUSE code as much as possible. And that's possible when each function of your program is SIMPLE(not necessarily easy) enough.

QUOTE: The MOUNTAIN is composed of tiny grains of earth. The ocean is made-up of tiny drops of water.. (- Sivananda)

ContentLicense: CC BY-SA 4.0

Title: Are long methods always bad?

Body:
Truth is, it depends. As mentioned, if the code does not separate concerns and tries to do everything in one method then its a problem. Separating code into multiple modules makes it easier to read code, as well as write code(by multiple programmers). Adhering to one module(class) per source file is a good idea to begin with.

Secondly, when it comes to functions/procedures:

void setDataValueAndCheckForRange(Data *data) {/*code*/}

is a good method if it checks for the range of only "Data". It is a BAD method when the same range applies for multiple functions(example of bad code):

void setDataValueAndCheckForRange(Data *data){ /*code */}
void addDataValuesAndCheckForRange(Data *result, Data *d1, Data *d2){ /*code*/}
void subDataValuesAndCheckForRange(Data *result, Data *d1, Data *d2){ /*code*/}
void mulDataValuesAndCheckForRange(Data *result, Data *d1, Data *d2){ /*code*/}

This has to be refactored to:

bool isWithinRange(Data *d){ /*code*/ }
void setDataValue(Data *d) {/*code*/ if(isWithinRange(d)){/*continue*/}else{/*warn/abort*/}
void addDataValue(Data *d, Data *d1, Data *d2) {/*code*/ if(isWithinRange(d)){/*continue*/}else{/*warn/abort*/}
void subDataValue(Data *d, Data *d1, Data *d2) {/*code*/ if(isWithinRange(d)){/*continue*/}else{/*warn/abort*/}
void mulDataValue(Data *d, Data *d1, Data *d2) {/*code*/ if(isWithinRange(d)){/*continue*/}else{/*warn/abort*/}

REUSE code as much as possible. And that's possible when each function of your program is SIMPLE(not necessarily easy) enough.

QUOTE: The MOUNTAIN is composed of tiny grains of earth. The ocean is made-up of tiny drops of water.. (- Sivananda)


问:
Should you promise to deliver a feature that you aren't sure if its implementable?
In an article from HN, I came across the following advice:

Always tell your customer/user "yes", even if you're not sure. 90% of
  the time, you'll find a way to do it. 10% of the time, you'll go back
  and apologize. Small price to pay for major personal growth

But I've always thought that one should do a feasibility analysis before making any kind of promises to a customer/user, so that they aren't misled at any point. At what circumstances, then, should the above advice applicable?

答: According to my experience, when a user requests something, you should ask them for a detailed specification of what the user really wants or needs. More often than not, you will never hear about the request again.</p>


答:
You should tell them to give you time to create an "spike solution".

A spike solution is a small program that, in coding it, allows you to figure out how to do, or even whether it is possible at all, something that is creating uncertainty in a project.

For example, suppose you have never send SMS programmatically, but somehow you know it's possible. A spike solution would be to make a small program that sends a SMS. That way it is no longer an uncertainty and you can make further estimates on feasibility.

Here's what eXtreme Programming documentation says on it:

Create spike solutions to figure out answers to tough technical or
  design problems. A spike solution is a very simple program to explore
  potential solutions. Build the spike to only addresses the problem
  under examination and ignore all other concerns. Most spikes are not
  good enough to keep, so expect to throw it away. The goal is reducing
  the risk of a technical problem or increase the reliability of a user
  story's estimate. When a technical difficulty threatens to hold up the
  system's development put a pair of developers on the problem for a
  week or two and reduce the potential risk.

Title: Should you promise to deliver a feature that you aren't sure if its implementable?

Body:
In an article from HN, I came across the following advice:

Always tell your customer/user "yes", even if you're not sure. 90% of
  the time, you'll find a way to do it. 10% of the time, you'll go back
  and apologize. Small price to pay for major personal growth

But I've always thought that one should do a feasibility analysis before making any kind of promises to a customer/user, so that they aren't misled at any point. At what circumstances, then, should the above advice applicable?


问:
Use of keyword "Using" in C# interface
When I'm using C# to write some code and I define an interface using Visual Studio 2010, it always includes a number of "using" statements (as shown in the example)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestEngine.TestNameSpace
{
    interface ITest1
    {
        bool testMethod(int xyz);
    }
}
```

I wonder what these are for and if they are really necessary. Can I leave these out? Are they only necessary when I'm using those parts in my interface description?

答: These default using statements are part of your default template when creating interfaces. You can always edit the template to have them removed. See this question for more details.

Title: Use of keyword "Using" in C# interface


答:
Yes you can remove any using directive that is not being used.These directives are automatically added by visual studio since they are the most commonly used ones and if for instance you are not going to use linq in the interface then you can remove the directive

```<code> System.Linq;
</code>```

The same holds true for other directives as well.Also it is a good practice in my opinion to move the using directives inside namespaces.

Title: Use of keyword "Using" in C# interface

Body:
When I'm using C# to write some code and I define an interface using Visual Studio 2010, it always includes a number of "using" statements (as shown in the example)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestEngine.TestNameSpace
{
    interface ITest1
    {
        bool testMethod(int xyz);
    }
}
```

I wonder what these are for and if they are really necessary. Can I leave these out? Are they only necessary when I'm using those parts in my interface description?

Body:
Yes you can remove any using directive that is not being used.These directives are automatically added by visual studio since they are the most commonly used ones and if for instance you are not going to use linq in the interface then you can remove the directive

 System.Linq;

The same holds true for other directives as well.Also it is a good practice in my opinion to move the using directives inside namespaces.


答:
Visual Studio doesn't know what code you intend to write so includes the most common namespaces for you by default in the "new class" template. This is done so you don't have to resolve all the references for every single line of new code you write.

Once you have written your basic code you can safely remove the ones you don't need. You will have to add any back that you subsequently need to reference in any subsequent code you write.

If you right click and select Organize Usings > Remove and Sort it will delete any that are unused. There are also extensions that will remove and sort the namespaces automatically on saving each file.

Title: Use of keyword "Using" in C# interface


问:
Leadership does not see value in standard process for machine configuration and new developer orientation
About 3 months ago our lead web developer and designer(same person) left the company, greener pastures was the reason for leaving. Good for them I say. My problem is that his department was completely undocumented.  Things have been tough since the lead left, there is a lot of knowledge both theoretical knowledge we use to quote new projects and technical/implementation knowledge of our existing products that we have lost as a result of his departure. My normal role is as a product manager (for our products themselves) and as a business analyst for some of our project based consulting work. I've taught myself to code over the past year and in an effort to continue moving forward I've taken on the task of setting my laptop up as a development machine with hopes of implementing some of the easier feature requests and fixing some of the no brainer bugs that get submitted into our ticketing system. But, no one knows how to take a fresh Windows machine and configure it to work seamlessly with our production apps.

I have requested my boss, who is still in contact with the developer who left, ask them to document and create a process to onboard a new developer, software installation, required packages, process to deploy to the productions application servers, etc. None of this exists, and I'm spinning my wheels trying to get my computer working as a functional development machine. But she does not seem to understand the need for such a process to exist. Apparently the new developer who replaced the one who left has been using a machine that was pre-configured for our environment, so even the new developer could not set up a new machine if we added another developer.

My question is two part:

Am I wrong in assuming a process to on-board and configure a new computer to be part of our development eco-system should exist?

Am I being a whinny baby and should I figure the process out and create a document on my own?

答:
First of all, it is odd that a developer has to setup the working environment. This task is usually for system administrator(s). So, taking into account that this isn't something you should do at all, you have the right to expect someone else to do this for you.

In most (if not all) companies there is a notice period. It usually ranges from a week to a month. But anyway that time is enough for the person leaving to help the company _ make some documentation, add comments to the code, document the architecture, etc. I'm afraid its too late to do this now, but don't forget about it next time someone leaves.

You are absolutely right to expect that there should be a process for setting up a new environment. In fact, if your company grows and you have more developers, you'll face the same problem _ this could be a heavy argument to convince your boss. You could even use the argument to convince the management to hire a system administrator for such tasks (I pre-assume you don't have one since you face the problem). Besides setting development environment, if you have a new machine it has to be integrated into the local net, etc.


问:
How effectively "sell" a good design in large meetings
Many times I have witnessed a sad tragedy.  Here's what happens:

A team design review for a new project.

I see a simple design that has quite a few holes.

I casually mention the holes and ways to avoid them.

The warnings are ignored with comments like "that 'never' happen in real life"

Eventually the things that "will 'never' happen" happen

An emergency team design review for a broken project.

So what do I do?  Copping the "I told you so" attitude is not going to win friends and influence people.  Sometimes years go by and the comments from step 3 are forgotten anyway.  I definitely don't want to be the annoying pest reminding the world of the gotchas.  I often sit back and watch the Titanic sail off to Europe.

It's frustrating to see bad designs move forward.  It's also frustrating that I can't seem to convince others of the pending peril of the current path.  I do worst on team meetings where everyone has different ways of understanding different terms.  Also, egos tend to win of reason and thought.  I'm looking for good tactics to convince groups people to use some new and complicated ideas.

答:
Try to build a reputation as being the person who can identify what will work and not just what you think will have a problem in some rare use case. When you see these potential problems, just consider them a footnote that may need to be addressed later.

People get crazy in congregations. Mention your concerns to a key person outside of the meeting. They will see this as less threatening and may take the time to hear your argument instead of thinking about their defending the design. They may also take more time to explain to you the circumstances why you may have a valid point, but it is not feasible to address in v1.0.

Key! Go into the meeting with a complete understanding of what your direct supervisor's agenda is. Maybe they see this as a minor project and the last thing they need at the meeting is a naysayer taking time away from more important issues. Ask them to help you help them.

ContentLicense: CC BY-SA 2.5


答:
There should be some documentation saying what software is required to compile and run the application.

There should also be documentation outlining what a client box requires to run the application.

They are not the same list.

If your company were to hire a new developer, how long would it be expected for them to start coding? A day? A week? Without knowing what software is required to compile the code, this can be a trial and error process that could take a while. But, it should only be something that needs to be done once.

My question is, what is the new developer doing? This should be his job, not yours. He is the other guy's replacement. Yes, it sucks that he's entered an environment without documentation, but it should be his task to document things. Get him to sit down and figure out what the development environment is and to document it. Get him to figure out and document what is required to run the app on a client box.

As for contacting the old developer, I wouldn't. IMHO, if a dev leaves a company with no documentation or knowledge transfer, they are hoping to be called to do some work at a consulting rate. It is unprofessional and shouldn't be rewarded. Yes, it might take some extra time to figure it out for yourselves, but you/the team will learn something in the process and the documentation produced will be current and up to date.

Title: Leadership does not see value in standard process for machine configuration and new developer orientation

Body:
About 3 months ago our lead web developer and designer(same person) left the company, greener pastures was the reason for leaving. Good for them I say. My problem is that his department was completely undocumented.  Things have been tough since the lead left, there is a lot of knowledge both theoretical knowledge we use to quote new projects and technical/implementation knowledge of our existing products that we have lost as a result of his departure. My normal role is as a product manager (for our products themselves) and as a business analyst for some of our project based consulting work. I've taught myself to code over the past year and in an effort to continue moving forward I've taken on the task of setting my laptop up as a development machine with hopes of implementing some of the easier feature requests and fixing some of the no brainer bugs that get submitted into our ticketing system. But, no one knows how to take a fresh Windows machine and configure it to work seamlessly with our production apps.

I have requested my boss, who is still in contact with the developer who left, ask them to document and create a process to onboard a new developer, software installation, required packages, process to deploy to the productions application servers, etc. None of this exists, and I'm spinning my wheels trying to get my computer working as a functional development machine. But she does not seem to understand the need for such a process to exist. Apparently the new developer who replaced the one who left has been using a machine that was pre-configured for our environment, so even the new developer could not set up a new machine if we added another developer.

My question is two part:

Am I wrong in assuming a process to on-board and configure a new computer to be part of our development eco-system should exist?

Am I being a whinny baby and should I figure the process out and create a document on my own?


问:
What kind of process should I use to learn a big system?

Possible Duplicate:

  How do you dive into large code bases?

I just joined a new company and started to study one of the their bigger system. For me to be productive, I need to understand the entire system without too much help. Other programers are really busy and dont' have time to hold my hands.

I used to use brain map to draw a pictorial representation of the system. Any recommendations on what is the right appproach to dissect a big program? It is a .net prgoram by the way.

答:
I would start with the documentation of the system: design document, requirements document(s), database schema or possibly a user's manual.  If you are lucky, you will find all of these, but find whatever you can.  Read these to get an idea of what the system is supposed to do.    Then I would play with the system in a test environment to get a feel for how it works.  Once I am comfortable with my understanding of what the system is supposed to do, I would start looking at the code for the simplest subsystem I can find.  Maybe a single data entry form or a single analysis algorithm, the key is to find something small enough that you can understand that code completely.  Keep repeating this until you have conquered the whole system.

If this is a system of any complexity, this will take a significant amount of time.  I would also check with your new manager to see what areas (s)he wants you to focus on.  The most important thing is to attack this problem in manageable chunks, you can't learn it all in one shot.


问:
Using replacement to get possible outcomes to then search through HUGE amount of data
I have a database table holding 40 million records (table A).

Each record has a string a user can search for.

I also have a table with a list of character replacements (table B) i.e. i = Y, I = 1 etc.

I need to be able to take the string a user is searching for, iterate through each letter and create an array of every possible outcome (the users string, then each outcome with alternative letters used).

I need to check for alternatives on both lower and uppercase letters in the word

A search string can be no longer than 10 characters long.

I'm using PHP and a MySQL database.

Does anyone have any thoughts / articles / guidance on doing this in an efficient way?

答:
I have a database table holding 40 million records (table A).

It sounds like an RDBMS is not appropriate for this task.

As @Jim Arnold says, you should use either Lucene or Endeca for this task.


答:
For me to be productive, I need to understand the entire system without too much help. Other programers are really busy and dont' have time to hold my hands.

You should take this is a danger sign. You might want to look for greener pastures.

There should be a big picture presentation of the system as a whole. Multiple such big picture views. A cartoon for management, a more detailed one for the system architect, a different view for the system integrator. They should have shown you those pictures on day one and walked you through it. Someone should be mentoring you along, pointing you to training materials, tutorials, and documentation; showing you the online resources; checking on your progress; and be available now and then to answer questions you have. You shouldn't expect the mentor to spend all his/her time with you, but that mentor should be there.

With a large system it might take months, sometimes several months, for you to come up to speed and become a productive asset to the organization -- and that's with a proper system in place. Without a proper system in place, odds are good that nobody understands the system as a whole. The programmers are too busy because they're busy making a convoluted mess that will eventually come crashing down on them.

Title: What kind of process should I use to learn a big system?

Body:
Possible Duplicate:

  How do you dive into large code bases?

I just joined a new company and started to study one of the their bigger system. For me to be productive, I need to understand the entire system without too much help. Other programers are really busy and dont' have time to hold my hands.

I used to use brain map to draw a pictorial representation of the system. Any recommendations on what is the right appproach to dissect a big program? It is a .net prgoram by the way.


答:
First things first, you need to get off Visual SourceSafe. I think that needs to be said. At the very least move to TFS. And there are other options as well.

Now that that's out of the way. I think this is a case of, "if you want things done right..." Your ultimate goal should be that a developer can turn on his freshly installed machine connect to source, get latest, hit f5 (or whatever you use for your run application shortcut) and have a working application.

One option is to build a working environment from the ground up and use it as a baseline developer image. When a developer comes on board, all you have to do is deploy that image to his machine and it should work.

There are some books on how to move your environment toward a more hands-off state. I like Continuous Delivery and Continuous Integration from the Fowler series myself, but there are other options out there.


答:
Am I wrong in assuming a process to on-board and configure a new computer to be part of our development eco-system should exist?

No. Having these processes will avoid the problems that you have already faced. In some larger organizations, there is a standard disc image of what a developer's machine should look like. When a new developer is hired, an available computer with the right hardware specs is wiped and re-imaged using this "developer" disc image. A standard checklist (sometimes includes post-imaging software installation for certain tools not included in the image) is followed by the tech people that do this to ensure that all developer machines start off the same way (users can tweak and modify them after they get them - at their own peril!).

Similarly, some applications with notoriously complex setup have documents explaining to new developers how to check out the code, configure the server, and build and locally deploy the application. One application even has a setup script just for workstations to make this process easier.

Am I being a whinny baby and should I figure the process out and create a document on my own?

You are, but only a little bit. It's one thing to say that this should have all been documented long ago, and the developer who left should have done a complete knowledge transfer to their replacement days (or weeks if possible) before they left. It sounds like none of that happened, and it's all in the past now anyway.

So what now? I doubt the developer who left will be of much help. They already have a new day job and who knows what they're busy with in their own life. I doubt there's any legal grounds your manager could use to force them to help. It would be nice if they took a few hours of their own time to answer some questions, but don't count on it. It looks like you're stuck figuring out most of it for yourself. This gives you the opportunity to document the proper process thoroughly and get it right. Those whoe follow you will thank you for this! Good luck!


答:
As @jgauffin points out package management really is the way to fly here. But not everything has a package manager. Or other times you just need the sources riding with things.

Specifics are really a function of what platform, thing you want to look at here would be the sorts of features exposed by git submodules or hg subrepos. Both are designed to pull some part of your source repository from an external source. In the case of hg subrepos they don't even need to be HG -- git or svn can be accessed as well.

The real challenge comes in when you want a subrepository but you need to edit some certain files within it.

Title: What's the best way to manage reusable classes/libraries separately?

Body:
When coding, I naturally often come up with classes or a set of classes with a high reusability. I'm looking for an easy, straight-forward way to work on them separately.
I'd like to be able to easily integrate them into any project; it also should be possible to switch to a different version with as few commands as possible.

Am I right with the assumption that git (or another VCS) is best suited for this? I thought of setting up local repositories for each class/project/library/plugin and then just cloning/pulling them. It would be great if I could reference those projects by name, not by the full path. Like git clone someproject.

edit: To clarify, I know what VCS are about and I do use them. I'm just looking for a comfortable way to store and edit some reusable pieces of code (including unit tests) separately and to be able to include them (without the unit tests) in other projects, without having to manually copy files. Apache Maven is a good example, but I'm looking for a language-independent solution, optimally command-line-based.


答:
Long methods tend towards "bad" in imperative languages which favor statements, side-effects, and mutability, precisely because those features increase complexity and thus bugs.

In functional programming languages, which favor expressions, purity, and immutability, there is less reason for concern.

In functional and imperative languages alike, it's always best to factor out reusable chunks of code into common top-level routines, but in functional languages which support lexical scoping with nested functions etc., it's actually better encapsulation to hide sub-routines within the top-level function (method) than to break them out into other top-level functions.

Title: Are long methods always bad?

Body:
So looking around earlier I noticed some comments about long methods being bad practice.

I am not sure I always agree that long methods are bad (and would like opinions from others).

For example I have some Django views that do a bit of processing of the objects before sending them to the view, a long method being 350 lines of code. I have my code written so that it deals with the parameters - sorting / filtering the queryset, then bit by bit does some processing on the objects my query has returned.

So the processing is mainly conditional aggregation, that has complex enough rules it can't easily be done in the database, so I have some variables declared outside the main loop then  get altered during the loop.

```<code>variable_1 = 0
variable_2 = 0
for object in queryset :
     if object.condition_condition_a and variable_2 > 0 :
     variable 1+= 1
     .....
     ...
     .
      more conditions to alter the variables

return queryset, and context
</code>```

So according to the theory I should factor out all the code into smaller methods, so That I have the view method as being maximum one page long.

However having worked on various code bases in the past, I sometimes find it makes the code less readable, when you need to constantly jump from one method to the next figuring out all the parts of it, while keeping the outermost method in your head.

I find that having a long method that is well formatted, you can see the logic more easily, as it isn't getting hidden away in inner methods.

I could factor out the code into smaller methods, but often there is is an inner loop being used for two or three things, so it would result in more complex code, or methods that don't do one thing but two or three (alternatively I could repeat inner loops for each task, but then there will be a performance hit).

So is there a case that long methods are not always bad? Is there always a case for writing methods, when they will only be used in one place?

UPDATE:
Looks like I asked this question a over a year ago.

So I refactored the code after the (mixed) response here, split it into methods. It is a Django app retrieving complex sets of related objects from the database, so the testing argument is out (it would have probably taken most of the year to create relevant objects for the test cases . I have a "this needs done yesterday" type work environment before anyone complains).
Fixing bugs in that part of the code is marginally easier now, but not massively so.

before :

```<code>#comment 1
bit of (uncomplicated) code 1a
bit of code 2a

#comment 2
bit of code 2a
bit of code 2b
bit of code 2c

#comment 3
bit of code 3
</code>```

now:

```<code>method_call_1
method_call_2
method_call_3

def method_1
    bit of (uncomplicated) code 1a
    bit of code 2a

def method_2
    bit of code 2a
    bit of code 2b
    bit of code 2c

def method_3
    bit of code 3
</code>```


问:
How important is the ability to touch-type?
Did you learn to touch-type when you were already working as a programmer?  If so how did it affect your productivity?  Or are you still unable to touch type and do you think it holds you back?

According to Steve Yegge it is essential,

Personally I did not notice much difference, possibly because I was spending less than 25% of my work time actually typing (I was working on a large legacy project at the time and I was spending more time on reading and debugging existing code.)

答:
Being able to touch type is fairly important.  Like others have said you should be able to get the code (text, other language constructs) onto the computer without spending a lot of time thinking about which finger needs to hit what key.  This isn't so important when dealing with bug/maintenance fixes since those don't typically involve a lot of code changing in one local spot, however when cranking out new code it does play a part in your productivity (daily SLOC for the metrics geeks).

To be honest something that isn't really on topic for the question but that comes up a lot is knowing your keyboard shortcuts.  The last couple of product demo's with my clients that I have had they are continually impressed by how quickly I maneuver around in PowerPoint/Excel/etc (and the keyboard short cuts in the app I'm developing for them).  It got to the point where one meeting we spent about 10 mins off topic just talking about it.


问:
Functional testing in the verification
Yesterday my question How come verification does not include actual testing? created a lot of controversy, yet did not reveal the answer for related and very important question: does black box functional testing done by testers belong to verification or validation?

ISO 12207:12208 here mentiones testing explicitly only as a validation activity, however, it speaks about validation of requirements of the intended use. For me its more high level, like UAT test cases written by business users

ISO mentioned above does not mention any specific verification (7.2.4.3.2)except for Requirement verification, Design verification, Document and Code & Integration verification. The last two can be probably thought as unit and integrated testing. But where is then the regular testing done by testers at the end of the phase?

The book I mentioned in the original question mentiones that verification is done by static techniques, yet on the V model graph it describes System testing against high level description as a verification, mentioning it includes all kinds of testing like functional, load etc.

In the IEEE standard for V&V, you can read this: Even though the tests and
evaluations are not part of the V&V processes, the techniques described in this standard may be useful in
performing them. So that is different than in ISO, where validation mentiones testing as the activity.

Not to mention a lot of contradicting information on the net. I would really appreciate a reference to e.g. a standard in the answer or explanation of what I missed in the ISO. For me, I am unable to tell where the testers work belong.

答:
Part of the challenge here is that I think you're misreading the ISO specification.

7.2.4 Software Verification Process

7.2.4.1 Purpose

The purpose of the Software Verification Process is to confirm that each software work product and/or service of a process or project properly reflects the specified requirements.

As has been answered in some of your other questions - Verification is making sure the requirements are defined correctly based upon the business' needs.

7.2.5 Software Validation Process

7.2.5.1 Purpose

The purpose of the Software Validation Process is to confirm that the requirements for a specific intended use of the software work product are fulfilled.

Validation is being defined here as making sure the software actually does what the requirements say they should, i.e. the software's correct operation fulfills the requirements.  This is the colloquial Testing phase.

So your comment of: however, it speaks about validation of requirements of the intended use. For me its more high level, like UAT test cases written by business users is a misunderstanding of what the ISO doc is specifying.  Validation can be cursory high-level acceptance tests, but it can also be lower level, deep testing of the product.

Section 7.2.5.3.1.2 explicitly says to figure out how much testing is needed.  That's the meaning behind: a validation process shall be established

Section 7.2.5.3.1.4 hints at what should be tested but is really just saying to document what is to be tested as part of the validation plan.

IMO, The ISO doc is pretty light on the particulars of testing, so I'll refer to SWEBOK for some additional details:

SWEBOK Software Testing Breakdown of Topics  The graph here does a decent job at showing the scope of testing.

SWEBOK Test Levels  Goes into more details about unit | integration | system testing, the objectives, and techniques.

One thing to note is that SWEBOK appears to use the terms validation and verification interchangeably, which is precisely what you're trying to avoid in this question.  SWEBOK wasn't written with the degree of precision that an ISO standard is.  I would argue that it's a forgivable lapse of precision, but I understand you may not feel that way at this point.  Semantically, validate and verify are very similar terms.  Using the context of the development phase is appropriate to determine the correct, precise term.

The answer to your ultimate question of where the testers work belong[s?] is that their effort belongs in the Validation portion of the development.  The ISO doc could have been more clear in their meaning of requirements ... are fulfilled.  But that's the answer you are looking for to your question -- Testers and testing fall into section 7.2.5 Software Validation.

Title: Functional testing in the verification


问:
How should I implement the repository pattern for complex object models?
Our data model has almost 200 classes that can be separated out into about a dozen functional areas. It would have been nice to use domains, but the separation isn't that clean and we can't change it.

We're redesigning our DAL to use Entity Framework and most of the recommendations that I've seen suggest using a Repository pattern. However, none of the samples really deal with complex object models. Some implementations that I've found suggest the use of a repository-per-entity. This seems ridiculous and un-maintainable for large, complex models.

Is it really necessary to create a UnitOfWork for each operation, and a Repository for each entity? I could end up with thousands of classes. I know this is unreasonable, but I've found very little guidance implementing Repository, Unit Of Work, and Entity Framework over complex models and realistic business applications.

答:
First, you will run through every entity that you have and ask yourself :

Does it make sense to persist this entity alone?

What I mean here, is that in your object model, some entities are likely contained in others in a master-detail relationship. If your entity is highly dependant on another, do not create a repository for this entity alone because it won't likely be persisted by itself. Instead, you will create a repository for each parent class, and you will make sure that the child entities and other relations are persisted at the same time.

I don't like how they implemented the UnitOfWork pattern in the link you provided. I suggest you to do something more along these lines (original article with proper formatting). You don't have to define one class per repository. The same class can be used for every repository, each having their own instance of the UnitOfWork class for the lifetime of the operation. You can also reuse the same UnitOfWork in different repositories for changes that you want persisted at the same time.

OwnerDisplayName: Eric Falsken


问:
Object behaviour or separate class?
When it comes to OO database access you see two common approaches - the first is to provide a class (say "Customer") with methods such as Retrieve(), Update(), Delete(), etc. The other is to keep the Customer class fairly lightweight (essentially just properties) and perform the database access elsewhere, e.g. using a repository.

This choice of approaches doesn't just apply to database access, it can crop up in many different OOD scenarios. So I was wondering if one way is preferable over the other (although I suspect the answer will be "it depends")!

Another dev on our team argues that to be truly OO the class should be "self-contained", i.e. providing all the methods necessary to manipulate and interact with that object. I personally prefer the repository approach - I don't like bloating the Customer class with all that functionality, and I feel it results in cleaner code having it elsewhere, but I can't help thinking I'm seriously violating core OO concepts!

And what about memory implications? If I retrieve thousands of Customer objects I'm assuming those with the data access methods will take up a lot more memory than the property-only objects?

答:
One of the major principles of good OOP design is Separation Of Concerns.

Persistence - the loading and saving of object data is a separate concern to the business concerns of the object, the thing it is modelling.

As such, persistence concerns should be handled by a separate object - one often used pattern that you have mentioned is indeed the repository pattern.

Title: Object behaviour or separate class?


问:
Complex string matching with fuzzywuzzy
I'm attempting to write a process that matches obscure strings to a single 'master string' for further processing. I have a lot of data that looks something like this:

```<code>Basketball
Basket Ball
Football
BasketBallR
BBall
BBall - r
FootB
</code>```

...and so on. These need to be mapped to a master record like so:

```<code>Basketball       = Basket Ball, BBall
Basketball - R   = BasketBallR, BBall - r
</code>```

I also have instances of data resembling this format:

```<code>Football -r
FootBall - r-g/H,Q,HH
</code>```

These situations need to be separated into different categories before being mapped. For example FootBall - r-g/H,Q,HH should be:

```<code>Football - r
Football - g
Football - H
Football - Q
Football - HH
</code>```

At this point, it still needs to be mapped to a master record...

I've tried several different combinations of fuzzywuzzy matching methods, Levenshtein Distance measurements, regex, etc. and can't seem to find a reliable method to logically associate different naming styles of a single item with a master name.

I'm throwing my hands up in desperation. Are there any existing python resources than can help sort out my problem? Are there other options? Can anybody point out an obvious option that I might have overlooked?

Basically, any suggestion, solution, resource or alternative method is greatly appreciated.

答:
I wrote something very similar at one time where I needed to write business logic to do a reasonably good job with matching various nick names and diminutive first names to person records with their full legal name.  Eg. (James Smith = Jim Smith = Jimmy Smith etc...)

I resolved the problem by essentially compiling and slowly building a CSV file that had a proper name, and each comma delimited value after the first value on a line represented every known diminutive name I could think of.  For purposes of memory consumption and processing time I preloaded the data of the CSV file into a map of string sets.

I created a unique key for each map entry for every single first name, proper and diminutive.  Why?  So that I could easily and quickly fetch *every possible proper and diminutive name by any given proper or dimunitive name.  I used the singleton pattern because obviously this object is expensive to build and consumes quite a deal of memory, however once this object is constructed it is insanely quick to fetch not only the proper name from a diminutive name, but also to fetch other possible diminutive names.

As the system encounters new dimunitive names it will proceed to slowly add new matches and increase the success rate.

If the data set in question is relatively manageable, and memory is cheap for your scenario, you might find this to be an excellent design idea.

Unfortunately I don't think you are going to find a catch all regex pattern that is going to arbitrarily find matches like this in a data set.  Their are no clear rules to how any two words can compare in your situation.  The best way to do this is to pre-associate the data once, or to pre associate manageable or indexed chunks of the data all at once.

EDIT:

If you are dealing with an enormous set of data then obviously the above will not work.  In this case I advise looking into a massively parallel solution utilizing a Map Reduce algorithm.  Apache Hadoop is a great open source project that manages a lot of the complexity of these kinds of applications for JVM based languages.  I am not sure if such a project exists for Python.

Title: Complex string matching with fuzzywuzzy


答: Promising the moon and delivering a rock is a sort of sales-man approach which should not be tolerated. If you don't know if it's possible, research it. Or, give them a quote on the amount of time you will have to take to look into it. This way you're not promising anything you can't deliver, yet you are being paid for the time it takes you to look into it.</p>


答:
Note: Whilst the question asks about ISO 12207, and calls for Authoritative Sources, the ISO standard is copyright, and whilst there are copies available on the 'net, I have deliberately not linked to one...

Terminology time:

Verification can be summed up by "Are we building the software correctly"

Validation can be summed up by "Are we building the right software

Within ISO 12207 these are two distinct processes (para 7.2.4 and 7.2.5). These paragraphs focussing on two distinct activities - proving the process, and proving the product.  As such (IMHO) "testing" (within the normally accepted meaning) is a validation only activity.

Within the specifics of your question, and note my emphasis:

7.2.4.3.2.3 Code verification. The code shall be verified considering the criteria
  listed below:
  a) The code is traceable to design and requirements, testable, correct, and compliant
  with requirements and coding standards.

Note: testable, not tested

Verification ensures that the correct processes and standards have been followed to generate the requirements, do the design, write the code and released.

Whereas, as part of the Validation activity:

7.2.5.3.2.3 Conduct the tests in subclauses 7.2.5.3.2.1 and 7.2.5.3.2.2 {...}

Testing is a validation activity, to prove that the software is correct and does what it is supposed to do, both in terms that the requirements are met, but also that the requirements reflect what is really required.

In my opinion.

Title: Functional testing in the verification

Body:
Yesterday my question How come verification does not include actual testing? created a lot of controversy, yet did not reveal the answer for related and very important question: does black box functional testing done by testers belong to verification or validation?

ISO 12207:12208 here mentiones testing explicitly only as a validation activity, however, it speaks about validation of requirements of the intended use. For me its more high level, like UAT test cases written by business users

ISO mentioned above does not mention any specific verification (7.2.4.3.2)except for Requirement verification, Design verification, Document and Code & Integration verification. The last two can be probably thought as unit and integrated testing. But where is then the regular testing done by testers at the end of the phase?

The book I mentioned in the original question mentiones that verification is done by static techniques, yet on the V model graph it describes System testing against high level description as a verification, mentioning it includes all kinds of testing like functional, load etc.

In the IEEE standard for V&V, you can read this: Even though the tests and
evaluations are not part of the V&V processes, the techniques described in this standard may be useful in
performing them. So that is different than in ISO, where validation mentiones testing as the activity.

Not to mention a lot of contradicting information on the net. I would really appreciate a reference to e.g. a standard in the answer or explanation of what I missed in the ISO. For me, I am unable to tell where the testers work belong.


答:
I don't see how this situation is much different from a lone developer with a clueless boss. Unfortunately, I've lost count of the number of times that I was 'convinced' to build a project a certain way and ship it, despite my warnings of impending doom. That leaves you not only building, but sailing the proverbial Titanic right into an iceberg all by yourself.

Just as you described, when the bits hit the proverbial bucket, my warnings had long since been forgotten. Sometimes (luckily for me) things went bad months or more after I was no longer involved in the project. Unfortunately, this left my successor thinking that I must be crazy, as you can bet that the boss denied any hand in it :)

Anyway, a group of 'convinced' programmers can be just as clueless as a pointy haired boss, sometimes even more because they are confidently clueless, as Jeff O mentions. When this happens, you have ample time to fix things. Don't try to make a single voice of reason be heard over a collective brain fart. If you can do that effectively, your place is in congress, not behind a desk writing software.

As actions speak louder than words, you can:

Show (with test scenarios) why the design will fail under normal circumstances. This will probably result in a smaller meeting where you are the one presenting, and is probably all you need to be heard.

Show a competing product that adequately addresses what the group thought were only 'corner cases'. You would be amazed at what lengths Google goes to anticipate mistakes in its spreadsheet program, for instance.

Reiterate the last project that required a ground up re-write a week before it was supposed to ship.

In other words the first step, no matter what you do is to deal with individuals or a (much) smaller group. If your concerns really are valid, I'm sure that they'll be better received a week or two into development. Just, as you noted, avoid the 'I told you so' stance.

Title: How effectively "sell" a good design in large meetings

Body:
Many times I have witnessed a sad tragedy.  Here's what happens:

A team design review for a new project.

I see a simple design that has quite a few holes.

I casually mention the holes and ways to avoid them.

The warnings are ignored with comments like "that 'never' happen in real life"

Eventually the things that "will 'never' happen" happen

An emergency team design review for a broken project.

So what do I do?  Copping the "I told you so" attitude is not going to win friends and influence people.  Sometimes years go by and the comments from step 3 are forgotten anyway.  I definitely don't want to be the annoying pest reminding the world of the gotchas.  I often sit back and watch the Titanic sail off to Europe.

It's frustrating to see bad designs move forward.  It's also frustrating that I can't seem to convince others of the pending peril of the current path.  I do worst on team meetings where everyone has different ways of understanding different terms.  Also, egos tend to win of reason and thought.  I'm looking for good tactics to convince groups people to use some new and complicated ideas.


问:
Is this a violation of the Liskov Substitution Principle?
Say we have a list of Task entities, and a ProjectTask sub type. Tasks can be closed at any time, except ProjectTasks which cannot be closed once they have a status of Started. The UI should ensure the option to close a started ProjectTask is never available, but some safeguards are present in the domain:

public class Task
{
     public Status Status { get; set; }

     public virtual void Close()
     {
         Status = Status.Closed;
     }
}

public class ProjectTask : Task
{
     public override void Close()
     {
          if (Status == Status.Started)
              throw new Exception("Cannot close a started Project Task");

          base.Close();
     }
}
```

Now when calling Close() on a Task, there is a chance the call will fail if it is a ProjectTask with the started status, when it wouldn't if it was a base Task. But this is the business requirements. It should fail. Can this be regarded as a violation of the Liskov substitution principle?

答:
Yes, it is a violation.

I would suggest you have your hierarchy backwards. If not every Task is closeable, then close() does not belong in Task. Perhaps you want an interface, CloseableTask that all non-ProjectTasks can implement.


答:
Yes. This violates LSP.

My suggestion is to add CanClose method/property to base task, so any task can tell if task in this state can be closed. It can also provide reason why. And remove the virtual from Close.

Based on my comment:

public class Task {
    public Status Status { get; private set; }

    public virtual bool CanClose(out String reason) {
        reason = null;
        return true;
    }
    public void Close() {
        String reason;
        if (!CanClose(out reason))
            throw new Exception(reason);

        Status = Status.Closed;
    }
}

public class ProjectTask : Task {
    public override bool CanClose(out String reason) {
        if (Status != Status.Started)
        {
            reason = "Cannot close a started Project Task";
            return false;
        }
        return base.CanClose(out reason);
    }
}
```

Title: Is this a violation of the Liskov Substitution Principle?

Body:
Say we have a list of Task entities, and a ProjectTask sub type. Tasks can be closed at any time, except ProjectTasks which cannot be closed once they have a status of Started. The UI should ensure the option to close a started ProjectTask is never available, but some safeguards are present in the domain:

public class Task
{
     public Status Status { get; set; }

     public virtual void Close()
     {
         Status = Status.Closed;
     }
}

public class ProjectTask : Task
{
     public override void Close()
     {
          if (Status == Status.Started)
              throw new Exception("Cannot close a started Project Task");

          base.Close();
     }
}
```

Now when calling Close() on a Task, there is a chance the call will fail if it is a ProjectTask with the started status, when it wouldn't if it was a base Task. But this is the business requirements. It should fail. Can this be regarded as a violation of the Liskov substitution principle?


答:
Yes, it is a violation of the LSP. Liskov Substitution Principle requires that

Preconditions cannot be strengthened in a subtype.

Postconditions cannot be weakened in a subtype.

Invariants of the supertype must be preserved in a subtype.

History constraint (the "history rule"). Objects are regarded as being modifiable only through their methods (encapsulation). Since subtypes may introduce methods that are not present in the supertype, the introduction of these methods may allow state changes in the subtype that are not permissible in the supertype. The history constraint prohibits this.

Your example breaks the first requirement by strengthening a precondition for calling the Close() method.

You can fix it by bringing the strengthened pre-condition to the top level of the inheritance hierarchy:

public class Task {
    public Status Status { get; set; }
    public virtual bool CanClose() {
        return true;
    }
    public virtual void Close() {
        Status = Status.Closed;
    }
}
```
<p>By stipulating that a call of <code>Close()</code> is valid only in the state when <code>CanClose()</code> returns <code>true</code> you make the pre-condition apply to the <code>Task</code> as well as to the <code>ProjectTask</code>, fixing the LSP violation:</p>
<pre class="lang-cs prettyprint-override"><code>public class ProjectTask : Task {
    public override bool CanClose() {
        return Status != Status.Started;
    }
    public override void Close() {
        if (!CanClose())
            throw new Exception("Cannot close a started Project Task");
        base.Close();
    }
}
</code>```

Body:
Yes, it is a violation of the LSP. Liskov Substitution Principle requires that

Preconditions cannot be strengthened in a subtype.

Postconditions cannot be weakened in a subtype.

Invariants of the supertype must be preserved in a subtype.

History constraint (the "history rule"). Objects are regarded as being modifiable only through their methods (encapsulation). Since subtypes may introduce methods that are not present in the supertype, the introduction of these methods may allow state changes in the subtype that are not permissible in the supertype. The history constraint prohibits this.

Your example breaks the first requirement by strengthening a precondition for calling the Close() method.

You can fix it by bringing the strengthened pre-condition to the top level of the inheritance hierarchy:

public class Task {
    public Status Status { get; set; }
    public virtual bool CanClose() {
        return true;
    }
    public virtual void Close() {
        Status = Status.Closed;
    }
}

By stipulating that a call of Close() is valid only in the state when CanClose() returns true you make the pre-condition apply to the Task as well as to the ProjectTask, fixing the LSP violation:

public class ProjectTask : Task {
    public override bool CanClose() {
        return Status != Status.Started;
    }
    public override void Close() {
        if (!CanClose())
            throw new Exception("Cannot close a started Project Task");
        base.Close();
    }
}


答:
Liskov substitution principle states that a base class should be replaceable with any of his sub-classes without altering any of the desirable properties of the program. Since only ProjectTask raises an exception when closed, a program would have to be changed to acommodate for that, should ProjectTask be used in substitution of Task. So it is a violation.

But If you modify Task stating in its signature that it may raise an exception when closed, then you would not be violating the principle.


问:
Finding the best practice for a game simulating tool
I'm studying Java right now, and I'm thinking of this tool as my practice project.
The game is "League of Legends" in case anyone knows it, I'm not actually simulating the game as in simulating game play, I'm just trying to create a tool that can compare different champions to each other based on their own abilities and items bought inside the game.

The game basics are:

Every player has a champion in a team of 5 players playing against
another team.

Each champion has a different set of abilities (usually 4) that s/he
uses to do damage to opposing champions.

Each champion gets stronger by buying different items, increasing the
attack it deals or decreasing the damage received.

What I want to do is to create a tool to be used outside the game enabling players to try out different builds for their champions and compare the figures against other champions they usually fight against.

The goal is to enable players get a deeper understanding of the different item combinations (builds) that can be used during the games, instead of trying them out in real games which can be somehow very time consuming.

What I'm stuck at is the best practice I should follow to make this possible using Java, I can't figure out which classes should inherit from which, should I make champions and items specs in the code or extracted from other files, specially that I'm talking about hundreds of items and champions to use in that tool.

I'm self studying Java, and I don't have much practice at it, so I would really appreciate any broad guidelines regarding this, and sorry if my question doesn't fit here, I tried to follow the rules.

English isn't my native language, so I'm really sorry if I wasn't clear enough, I would be more than happy to explain anything that's not understood.

答:
I would start by laying out my objects/classes that I need to code:

main object (Champion)

with attributes of Strength, Agility, etc.

Spells

special attacks

decorator objects (Items you buy in Game)

their attributes

what increases?

Class for Champion interaction (or direct battle simulation algorithm)

attributes like Distance or time (these might even be something to Program into the champion or the item)

with the Items I would use the decorator Pattern  to add the stats together.

{very rough example}

when you have the objects all set up then I would create a Database that would hold the information for the different objects or classes

I hope that this gives you a good starting point.  I didn't want to do all the fun stuff for you.  :)

Addition

Best Database for Java?

doesn't look like it matters what database that you use when programming with Java.
I would probably go with MySQL mostly because it is Free.  as far as I know you can connect to a MySQL Database from any language.

that post mentions a couple of other Databases

HSQLDB

H2

I do most of my work with SQL Server or MySQL.


答:
Personally, I like to dig in and start changing things (learn by doing).  Ask for a task and figure out how to get that task done within the system.  Don't be afraid to ask questions - the only stupid questions are the ones you already know the answer to.  If you can get it, ask for a code review before checking anything in to the repository (any decent company should do this with new starters anyway).

You won't learn the whole system off the bat, but once you get comfortable with changing small parts of the system, you'll find it easier to branch out into other areas and figure out how they work.  I don't know the scale of the system your working with, but I've been with my current company for a year, and there's no way anyone on our team can claim to know how everything works.


问:
Resizing an image with a non-integral conversion factor
I'm resizing an image based on a non-integral conversion factor (a bmp image, in fact).  I understand how resizing works, just non with a decimal number.  For instance, if the factor were 2, I would simply write the individual pixels twice to the output file.  You can't really write 1.5 pixels if the factor were, say, 1.5.  Conceptually, how might this play out?</p>

答:
Don't think of the process as "where would this pixel go?", but rather as "from where did that pixel came?".

Then, it's easy to see that each pixel in the final picture will come from a position at a fractional coordinates in the original image, that just means it will have a color that is a weighted average of the near pixels.

That's why Photoshop (and others) lets you choose the subsampling algorithm.  Some are prettier but use more origin pixels, or need more precise math, while others are fast and doable with integer numbers but not so good looking.


答:
This is actually a big topic.  What you are asking about is called image resampling.  And there are many different algorithms that can be used.  See the wikipedia article for a basic introduction.

But as Javier hinted at, you dont generally take a pixel and write out a scaled version.  Rather, you look at a destination pixel, and figure out what source pixels you need to reference and how to weigh them to calculate the destination pixel.

Title: Resizing an image with a non-integral conversion factor

Body: I'm resizing an image based on a non-integral conversion factor (a bmp image, in fact).  I understand how resizing works, just non with a decimal number.  For instance, if the factor were 2, I would simply write the individual pixels twice to the output file.  You can't really write 1.5 pixels if the factor were, say, 1.5.  Conceptually, how might this play out?</p>


答:
When I started my current job we had a documented procedure for setting up a developer PC.

I followed the procedure on my own, determinedly avoiding to existing team's "help".

(The knowledge needs to be embodied in the document, not the developer who's been ther longest.)

I marked up the procedure with red-line changes where it was wrong or incomplete, and aw week later had two things, a procedure that worked and a working development PC.

After a hard disk failure a year later, it took 2 days to rebuild.

Tell your boss: if the hard drive fails on that PC, there will be no development happening!

I decided 2 days was a waste of two days....

Now we use virtual machines with disk images for each development project.

Setup is to copy the VM image to the target PC and start it.
There is an icon called "runme" that you click on, It asks your username and then that changes the username used to access source code to your own one. It also changes the IDE's blank document author field to your name.

(I wrote runme in about 2 hours, we're developers, we program our problems away)

Our developer PC's are standard machines except for a VM server.

We're using virtualbox, which is not expensive.

Using Virtual Machines makes replacing a machine is a no-brainer 20 minute job. This task would be faster if we had gigabit ethernet to copy the VM over.

Full discosure: I'm the team leader where I work and my management give me a free(-ish) rein.


问:
How do you dive into large code bases?
What tools and techniques do you use for exploring and learning an unknown code base?

I am thinking of tools like grep, ctags, unit-tests, functional test, class-diagram generators, call graphs, code metrics like sloccount, and so on. I'd be interested in your experiences, the helpers you used or wrote yourself and the size of the code base with which you worked.

I realize that becoming acquainted with a code base is a process that happens over time, and familiarity can mean anything from "I'm able to summarize the code" to "I can refactor and shrink it to 30% of the size". But how to even begin?

答:
A little thing I wanted to add:

One tool that I've started using recently for this kind of problem that has helped immensely is mind mapping. Instead of trying to cram all the details of how something is implemented in my head, I'll build a mindmap describing how the system I am going through works. It really helps me more deeply comprehend what is going on and what I still need to figure out. It also helps me keep track of what I need to change at a very precise scale.

I recommend using free plane amongst the plethora of mind mapping choices.

Title: How do you dive into large code bases?


答:
If possible suggest modifications that will not add significant time to a project. Try and stress that if it's not done now, then re-work later will be much more painful. It will be harder if you're trying to convince your team that a complete new direction is better, cause that will probably delay the project, etc.

Don't put people in defence mode in a meeting, they'll just fight you to be the winner. You won't get them to agree that the earth is round. This is normal politics (e.g. anyone on FoxNews)

It really helps to have the respect of other developers. If you're the new guy on the team, I think you are SOL. So just build up some team rep and really try to get to a level were you won't be dismissed right off the bat. Of course, if you are always pessimistic amount stuff, then you will just be labelled as the "negative" guy.

For simple stuff (i.e. does not impact schedules ), be sure to do your work the best way. If you put the effort into your immediate output (e.g. building test cases, or getting a some simple (but cool) features) eventually other people will notice that your code works reliably and withstands the test of time. When you start showing them some neat tricks with the code, they'll think twice shooting you down in front of everyone.

Finally, I agree you don't want to do the "I told you so" routine, but be sure to try and drop hints to your boss/tech-lead when it turns you actually were right. Maybe resend an old e-mail with your old comments. Ask them if this would help solve the "new" problem. If you don't do this, they won't even remember that you were the one who brought it up the first time. Eventually they'll get the hint that you're not just trying to be a showoff in the meetings. Next time they'll think twice about blowing you off, especially if it gets around that your "old" design is now replacing the current broken one.


答:
In short, they are called namespaces. Namespaces are also used to reference some library classes within your code. There is also a recommended guidelines on how to use namespaces in .NET

In most cases, you may simple remove them if not used. The following two namespaces are potential candidates to to be removed.

```<code>using System.Collections.Generic;
using System.Linq;
</code>```

Visual Studio will  complain and NOT compile the code, once some framework/library classes have been used without declaring their namespaces. Thus, namespace play roll of structuring your code as well as easing the references between the project classes, interfaces, constructs, etc.

Title: Use of keyword "Using" in C# interface

Body:
In short, they are called namespaces. Namespaces are also used to reference some library classes within your code. There is also a recommended guidelines on how to use namespaces in .NET

In most cases, you may simple remove them if not used. The following two namespaces are potential candidates to to be removed.

using System.Collections.Generic;
using System.Linq;

Visual Studio will  complain and NOT compile the code, once some framework/library classes have been used without declaring their namespaces. Thus, namespace play roll of structuring your code as well as easing the references between the project classes, interfaces, constructs, etc.


问:
Am I permitted to use an LGPL library without releasing the source to the rest of my application, if I dynamically reference the library?
I am a bit confused as to what I am/am not allowed to do with a LGPL Library that I intend on using in a small scale commercial C++ Application that I am developing. My current understanding, although I don't know if I am correct, is that I am permitted use the library without releasing the source to the rest of my application if I dynamically reference the library. Does anyone know if this is correct? Are there any restrictions as to how I reference the library? Thank You! I am not a native English speaker and don't understand the licence entirely.</p>

答:
Yes you can use the unmodified library with your own proprietry code - so long as your user can exchange the LGPL library for their own version (this normally means using a dynamic linked library = dll or so)

If you do modify the library you are required to release the source code of the library with your changes.

The only extra complication would be if you used ideas/concepts from the source code of the library inside your own app - then your app could be a derived work . But normally there are no problems using an LGPL library with a commercial app - that was the idea of it.


问:
Is it correct that Java Applets can do hardware acceleration while Flash can't?
I hope you can confirm or disprove whether I understand this correctly. I know for certain that Java Applets can have hardware acceleration and I wonder if this is the only known way to have graphics hardware acceleration in web pages or is there another way?</p>

答: I can't speak for the Java applets, but in flash version 11, code named molehill during development, hardware acceleration was added.</p>


问:
What's the best way to manage reusable classes/libraries separately?
When coding, I naturally often come up with classes or a set of classes with a high reusability. I'm looking for an easy, straight-forward way to work on them separately.
I'd like to be able to easily integrate them into any project; it also should be possible to switch to a different version with as few commands as possible.

Am I right with the assumption that git (or another VCS) is best suited for this? I thought of setting up local repositories for each class/project/library/plugin and then just cloning/pulling them. It would be great if I could reference those projects by name, not by the full path. Like git clone someproject.

edit: To clarify, I know what VCS are about and I do use them. I'm just looking for a comfortable way to store and edit some reusable pieces of code (including unit tests) separately and to be able to include them (without the unit tests) in other projects, without having to manually copy files. Apache Maven is a good example, but I'm looking for a language-independent solution, optimally command-line-based.

答:
A VCS is the way to go. What you need here is to decide how you are going to store you code/configuration items in your VCS repository. The first question that I would ask is how stable are these reusable components?

If they are not going to change very much, then put then into a repository/database/project/folder/(what ever terminology your VCS uses) of their own and label them according to the product they correspond to. Then when it is time to do some coding, the developer gets the system they are working on from its repository and then the shared stuff, using the appropriate label to get the appropriate versions.

If the shared libraries will only change a little bit over time, then add some branching for the development lines that need it and use labels. Now you can get the required files/versions as per the above using the appropriate labels. You then need a management process to periodically update the trunk with these branches and test it with all the affected applications.

If there is going to be a lot of customization, then you probably need to maintain separate repositories per project as that will be easier/cheaper to manage that over a bunch of repositories with lots of branches/labels/promotion groups and the integration testing that that entails.

To extract them, use some tool if you can be bothered to work out how to configure it. Or, write a quick script to get the files needed per project and create the file structure for the project when you need to start off some development, Something like this psudo code:

required_label = "version 1.1.1"

project        = "funStuff"

destination    = "server/share/folder/"

get from vcs project $project $required_label into $destination

get from vcs "library project" $required_label into $destination/lib/

echo "get to work"

This may not work if you used a IDE inbuilt version management integration. The developers may need to use the VCS's interface to check in/out configuration items that are going to be changed.

The key to making this work is to make sure that the appropriate labeling system is enforced by the VCS - the ones I have used allow you to set up a rule forcing the adding or a label on check-in or have the facility for floating labels. Use as appropriate.


问:
How to learn & introduce scrum in small startup?
In a few months, a friend will establish his startup software company, and I will be the software architect with one additional developer. Though we have no real day-to-day experience with agile methods, I have read much "overview" type of material on them, and I firmly believe they are a good - if not the only - way to build software. So with this company, I want to go for iterative, agile development from day 1, preferably something light-weight.

I was thinking of Scrum, but the question is: what is the best way for me and my colleagues to learn about it, to introduce it (which techniques when etc) and to evaluate whether we should keep it?

Background which might be relevant: we're all experienced developers around the same age with similar professional mindset. We have worked together in the past and afterwards at several different companies, mostly with a Java/.NET focus. Some are a bit familiar with general ideas from the agile movement. In this startup, I have great power over tools, methods and process. The startup's product will be developed from scratch and could be classified as middleware. We have some "customer" contacts in the industry who could provide input as soon as we get to an alpha stage.

答:
Disclaimer: I have never done any formal Scrum training (although have worked on a couple of Scrum (based) projects so far and like it very much). So you may prefer opinion from someone better versed on the subject.

IMHO if you have read the "obligatory" material such as the Scrum book, you probably know enough about it in theory. Plus, with your sw development experience, you understand how it works and what makes it work in practice. With a team of two, the simplest way is to just have the other guy read the relevant material too, then start with a discussion about your SDLC. Discuss any unclear parts or question either of you have, and work out your own process. It may be an exact Scrum, or a hybrid - do whatever fits you (your team, your project(s), your environment) the best. Then start doing it immediately, and keep reviewing and adjusting as you go - this is actually the most important gist for long term success.

You may consider taking a formal training or workshop with an experienced Scrum / Agile consultant (if there are any at reach where you live). However, for a startup team of two, this may be an expensive overkill.

Btw for further study, I found a reading list on Scrum Alliance's site.


答:
My suggestion would be for you to acquire budget for yourself to attend formal scrum master training and certification session with the scrum alliance. If this budget is not approved then try to acquire all the materials for this training, go over them yourself and see try to evangelize the Agile process to your team.

One other thought: Although anyone in the team can take up the role of a scrum master, it is probably not the best decision for the architect to be in this role. It's not that the architect is not suitable for it, but the amount of work the architect has to do outside of being a facilitator for the team is going to conflict with the scrum master role (at least in my experience).

Title: How to learn & introduce scrum in small startup?

Body:
In a few months, a friend will establish his startup software company, and I will be the software architect with one additional developer. Though we have no real day-to-day experience with agile methods, I have read much "overview" type of material on them, and I firmly believe they are a good - if not the only - way to build software. So with this company, I want to go for iterative, agile development from day 1, preferably something light-weight.

I was thinking of Scrum, but the question is: what is the best way for me and my colleagues to learn about it, to introduce it (which techniques when etc) and to evaluate whether we should keep it?

Background which might be relevant: we're all experienced developers around the same age with similar professional mindset. We have worked together in the past and afterwards at several different companies, mostly with a Java/.NET focus. Some are a bit familiar with general ideas from the agile movement. In this startup, I have great power over tools, methods and process. The startup's product will be developed from scratch and could be classified as middleware. We have some "customer" contacts in the industry who could provide input as soon as we get to an alpha stage.


问:
Effective handling of variables in non-object oriented programming
What is the best method to use and share variables between functions in non object-oriented program languages?

Let's say that I use 10 parameters from DB, ID and 9 other values linked to it. I need to work with all 10 parameters in many functions. I can do it  next ways:

1. call functions only with using ID and in every function get the other parameters from DB.

Advantage: local variables are clear visible, there is only one input parameter to function

Disadvantage: it's slow and there are the same rows for getting parameters in every function, which makes function longer and not so clear

2. call functions with all 10 parameters

Advantage: working with local variables, clear function code

Disadvantage: many input parameters, what is not nice

3. getting parameters as global variables once and using them everywhere

Advantage - clearer code, shorter functions, faster processing

Disadvantage - global variables - loosing control of them, possibility of unwanted overwriting (Especially when some functions should change their values)

Maybe there is some another way how to implement this and make program cleaner and more effective.
Can you say which way is the best for solving this issue?

答:
In short: Most languages have standards or ways to address this exact problem and will depend on the language, in C - use a struct; I don't know Ash but it might have some sort of data structure or way that you can group data together and use that instead.

In terms of the methods you have outlined:

Call functions only with using ID and in every function get the other parameters from DB.

Your disadvantage is pretty much spot on here, you shouldn't be calling the database multiple times throughout your code execution as it is slow and wasteful, get the data once and reuse it where you can.

Call functions with all 10 parameters

In the event that the particular language has no possible way of grouping data together to let you pass that around, then this is probably the best option. It saves you from using globals (especially mutable ones) that can potentially be ruined by other processes and it makes it clear where the data is coming from. Although there are many input parameters, if your language simply doesn't support data grouping then this is probably the way to go.

It is also possible to write your code in such a way that each function might not need all 10 variables, then you can just pass the ones that you need to the function and progress through your code that way. Then, the main function only knows about all 10 and deals with the end result - and you delegate particular pieces of business logic to smaller, more manageable methods.

Getting parameters as global variables once and using them everywhere

As you've stated in your disadvantages - this can quickly become out of control and if they're mutable then you don't know if someone else has changed the value or state of your variable and you can have unexpected results in your application. Using global variables is almost always a bad idea (there are some exceptions).

Although globals might sound like an easy and quick way to achieve something now, as you add more features and more functions add to your code base and your code gets bigger. It becomes harder to add features because you have to start to remember what each global is doing and what is modifying it, what state it is currently in and if your new feature/function can modify/use it at a particular point in time.


问:
How to verify the Liskov substitution principle in an inheritance hierarchy?
Inspired by this answer:

Liskov Substitution Principle
  requires
  that

Preconditions cannot be strengthened in a subtype.

Postconditions cannot be weakened in a subtype.

Invariants of the supertype must be preserved in a subtype.

History constraint (the "history rule"). Objects are regarded as being modifiable only through their methods (encapsulation). Since
  subtypes may introduce methods that are not present in the supertype,
  the introduction of these methods may allow state changes in the
  subtype that are not permissible in the supertype. The history
  constraint prohibits this.

I was hoping if someone would post a class hierarchy that violates these 4 points and how to solve them accordingly.

I'm looking for an elaborate explanation for educational purposes on how to identify each of the 4 points in the hierarchy and the best way to fix it.

Note:

I was hoping to post a code sample for people to work on, but the question itself is about how to identify the faulty hierarchies :)

答:
It's a lot more simple than that quote makes it sound, accurate as it is.

When you look at an inheritance hierarchy, imagine a method which receives an object of the base class. Now ask yourself, are there any assumptions that someone editing this method might make which would be invalid for that class.

For example originally seen on Uncle Bob's site (broken link removed):

```<code>public class Square : Rectangle
{
    public Square(double width) : base(width, width)
    {
    }

    public override double Width
    {
        set
        {
            base.Width = value;
            base.Height = value;
        }
        get
        {
            return base.Width;
        }
    }

    public override double Height
    {
        set
        {
            base.Width = value;
            base.Height = value;
        }
        get
        {
            return base.Height;
        }
    }
}
</code>```

Seems fair enough, right? I've created a specialist kind of Rectangle called Square, which maintains that Width must equal Height at all times. A square is a rectangle, so it fits with OO principles, doesn't it?

But wait, what if someone now writes this method:

```<code>public void Enlarge(Rectangle rect, double factor)
{
    rect.Width *= factor;
    rect.Height *= factor;
}
</code>```

Not cool. But there's no reason that the author of this method should have known there could be a potential problem.

Every time you derive one class from another, think about the base class and what people might assume about it (such as "it has a Width and a Height and they would both be independent"). Then think "do those assumptions remain valid in my subclass?" If not, rethink your design.

Body:
It's a lot more simple than that quote makes it sound, accurate as it is.

When you look at an inheritance hierarchy, imagine a method which receives an object of the base class. Now ask yourself, are there any assumptions that someone editing this method might make which would be invalid for that class.

For example originally seen on Uncle Bob's site (broken link removed):

public class Square : Rectangle
{
    public Square(double width) : base(width, width)
    {
    }

    public override double Width
    {
        set
        {
            base.Width = value;
            base.Height = value;
        }
        get
        {
            return base.Width;
        }
    }

    public override double Height
    {
        set
        {
            base.Width = value;
            base.Height = value;
        }
        get
        {
            return base.Height;
        }
    }
}

Seems fair enough, right? I've created a specialist kind of Rectangle called Square, which maintains that Width must equal Height at all times. A square is a rectangle, so it fits with OO principles, doesn't it?

But wait, what if someone now writes this method:

public void Enlarge(Rectangle rect, double factor)
{
    rect.Width *= factor;
    rect.Height *= factor;
}

Not cool. But there's no reason that the author of this method should have known there could be a potential problem.

Every time you derive one class from another, think about the base class and what people might assume about it (such as "it has a Width and a Height and they would both be independent"). Then think "do those assumptions remain valid in my subclass?" If not, rethink your design.


问:
Something similar to Objective-C categories in other languages?
I understand Objective-C categories and how they become useful, but I always have a hard time explaining the concept to other programmers that are not familiar with Objective C.

Maybe I'm just bad at explaining things, but I was thinking at another way to explain it by comparing to similar features offered by other (more popular) languages. (ex : I can explain the similarities between Objective C protocols and Java Interfaces)

Any examples similar to Categories ?

答:
I dont have much experience with Objective C.

However, from what I've read, the Scala: Traits or Mixin Class Composition seems to be closest to categories. Alternatively its a special case of multiple inheritance perhaps (C++).

I dont think Java has anything quite like it.