答:
Just because you move to a situation with more than one developer doesn't mean you'll be locked into strict deadlines, late hours, and specialized areas of work.  Yes, there are corporations that do that, but there are also SMBs out there that need developers too, and some of them are very similar to your current work environment, just with more than one developer.

I suppose it depends on where your career goals lie.  If you are content with your current situation, but want more developer interaction, I would suggest looking for a small company that has a team of 5-10 developers that you can join.  This will allow you to have a lot of flexibility but still have others to ping ideas off of.

From a hiring perspective, when I've reviewed potential developers I have never asked if they were a hermit.  However, examples of working within a team are incredibly important when bringing somebody on board to be part of a team.  How does a person deal with other individuals with differing opinions?  What have they done in the past to ensure that the whole group gains the best outcome?  These don't have to do with other developers, this is about working with people (which you said you already do).

If you are looking to go into a senior technical leadership role, you will definitely need to move to a position with a few other developers where you have the opportunity to become a team lead.  It is very hard to explain that you have the expertise to run a development team if you don't have experience working on a development team.

Title: Solo developer vs. team developer : should I move on?

Body:
I work as a solo developer in a small company. There's more than enough work, but the same does not apply for money. Thus, I won't be seeing any new colleagues in the near future.

I am responsible for absolutely everything that has do to with IT operations. This involves development and maintenance of software used in-house, development and maintenance of various websites which our clients use, website infrastructure, local network infrastructure including maintenance of several servers and in-house support to mention the most immediate things.

I really enjoy 95% of what I do, and I've got a high degree of flexibility in my work. I get to decide what do when, and no one really tells me what do to except that I now and then sit down with my colleagues to create a roadmap for what I need to get done. I do consider myself to have a high work ethic and being above average focused on what I do, so things get done.

However, I've come to the point where I really miss having other people around me who work with the same. Even though I need to get familiar with a wide range of technologies as I am a solo developer, I have the feeling that I am missing out one the "knowledge sharing" which other "like minded" people who work in bigger companies are taking part in. I don't really have anyone to discuss programming obstacles and design decisions with - and I am starting to miss that. Also, I'm worried about what future employers might think of this "hermit" who has been working on his own for too long to ever be able to take part in a team.

However, on the other side, I'm thinking that I won't get my current degree of flexibility in a larger company. I'll be seeing a lot more strict deadlines, late hours and specialized areas of work. Also; I'm not sure if this idea of "knowledge sharing" will ever take take place?

Has anyone else been in this situation? Is it a good idea seen from a career perspective and a personal development perspective? Should I consider moving on to a bigger place to (maybe) become a part of a larger group of developers and "like minded" people? In other words, will the grass be greener on the other side?


问:
The rationale behind Falsy values
I'm wondering what the arguments for/against Falsy values are. On what principles would you decide to add or exclude them from a language? Are there any problems you could see them causing off-hand?

For users of languages that support Falsy values:

Where specifically have you used them to your advantage?

Where have you had unpleasant run-ins with them?

Are there any rules or finer points in your language/project/team about where it's appropriate or inappropriate to use them?

For users of other languages:

Have you ever seen a situation where you've thought "I wish I could use a Falsy value here"?

I'm tagging the question haskell and python because AFAIK those two represent opposite ends of the spectrum (Haskell demanding Bools when you use if, and Python treating None and some "empty" values as Falsy), but feel free to talk about your experience from other languages. Just mention where on the spectrum they stand.

答:
The problem with "falsy" values is that they inevitably lead to ambiguities between in- and out-of-bounds responses: cases where an operation returns a "falsy" value that could mean either failure to produce an answer or success at producing an answer whose value is the "falsy" value.

One familiar example would be Java's Map<K,V>.get(K key) method, which returns null in two situations:

The map doesn't have an entry for the key you asked for.

The map has an entry that maps that key to null.

Contrast Haskell, where not only are a and Maybe a different types, but also Maybe (Maybe a) and so on.  In Haskell, if you need to (and most of the time you don't), you can distinguish between Nothing ("outer" failure) and Just Nothing ("inner" failure).

ContentLicense: CC BY-SA 3.0

Title: The rationale behind Falsy values


问:
How should I manage short-term user preferences, to simplify data cleanup?
When rolling out a new feature, sometimes it makes sense to notify the end user what it is, and give them an opportunity to provide feedback whether the software should get them to 'try something new' or 'put it off'.

In a cloud software, how should user preference data such as this be managed? A small piece of information would have to be stored to save the preference, but eventually, it becomes irrelevant. (The old way is phased out.) The simple thing to do is just leave that data there. After all, it doesn't take much space.

Eventually, as more features and changes come and go, and more messages are added, dismissed, and removed; there would be many items in the data storage that is no longer used, and there would be cost in the form of programmer hours in preserving or separating that data.

Are there coding and software maintenance patterns that would make sense to get rid of old data structures along with removal of old features? Is there a common solution to this data cleanup?

答: Store the meta-data about what the features and their options are, and link the preferences to them.  Once you have done that, then when the options are eliminated it's a simple script to remove irrelevant preferences.  </p>


问:
Solo developer vs. team developer : should I move on?
I work as a solo developer in a small company. There's more than enough work, but the same does not apply for money. Thus, I won't be seeing any new colleagues in the near future.

I am responsible for absolutely everything that has do to with IT operations. This involves development and maintenance of software used in-house, development and maintenance of various websites which our clients use, website infrastructure, local network infrastructure including maintenance of several servers and in-house support to mention the most immediate things.

I really enjoy 95% of what I do, and I've got a high degree of flexibility in my work. I get to decide what do when, and no one really tells me what do to except that I now and then sit down with my colleagues to create a roadmap for what I need to get done. I do consider myself to have a high work ethic and being above average focused on what I do, so things get done.

However, I've come to the point where I really miss having other people around me who work with the same. Even though I need to get familiar with a wide range of technologies as I am a solo developer, I have the feeling that I am missing out one the "knowledge sharing" which other "like minded" people who work in bigger companies are taking part in. I don't really have anyone to discuss programming obstacles and design decisions with - and I am starting to miss that. Also, I'm worried about what future employers might think of this "hermit" who has been working on his own for too long to ever be able to take part in a team.

However, on the other side, I'm thinking that I won't get my current degree of flexibility in a larger company. I'll be seeing a lot more strict deadlines, late hours and specialized areas of work. Also; I'm not sure if this idea of "knowledge sharing" will ever take take place?

Has anyone else been in this situation? Is it a good idea seen from a career perspective and a personal development perspective? Should I consider moving on to a bigger place to (maybe) become a part of a larger group of developers and "like minded" people? In other words, will the grass be greener on the other side?

答:
This aligns with my saying: "Programming is like sex. You can do it alone, but it  is way less fun that way. And turns you nuts if you do it that way for too long."

Yes, it's convenient to be quite your own boss and lone master of department. Also it's scary to leave the established shell.  Not to mention to face the hostile world outside. And start from the bottom again.    Parting is even harder if you are not kicked out, and/or you feel bad about abandoning the company that needs you and maybe got pretty much locked in.

I've been there. Worked some 12 years at a company as a 1-man army. Last years it was like many would call the Kanaan, worked mostly sitting home, just getting a note "X client wants something check it out", then few days later mailed that contract can be signed for X amount and Y deadline, then a month later sent another mail that invoice can be sent. And worked maybe 1 hour/day averaged -- for the full time money. And everyone was content boss and clients likewise.

but it grew on me, and despite having all the time, it was mostly just wasted.

I eventually posted an ultimatum to rearrange work so I can work in team, or I'm out. Boss probably thought it a bluff. Bottom line, I left for good.   Thought will have job next day. Yeah, sure. ;-)

Faced  a series of uber-WTF interviews and companies, but after a few months got a job. At a company that turned out bigtime sucker, but the local teams really rocked. At least when I joined, a year after that massive leaving started, obviously with the best poeple. Got about the same money but 8+ hours work in the office + commotion. In a project that had a ton of serious problems. And remote bosses guarded all the bugs.

but overall, I felt alive again, and happy to do relevant work. in a team that struggled for the same, and was happy that we finally started making progress against all the wind and hostile weather.   In my count the switch was well worth it.   The only thing to be sorry about that I didn't leave 4-5 years earlier.

The follow up is not really relevant (actually I left eventually, this time only 1 year later than optimal, made a home project, then joined another company that was promising, while our team made incredible progress the company turned south, and this time I finally left exactly on the zenit -- and after a calculated summer vacation landed where I work now with no plans to leave.) the point is life works out, never the way you expect, but for the better in the long run.

The bottom line is, if you no longer see the Sun, you better close the false hopes. It just will not get better. You can either force your way or look for actually fertile ground.


答:
I'm in a very similar situation to what you have described. My main issue is the money, since you have mentioned it. Sometimes I think I'm too lonely and crave for more action and knowledge sharing, however looking back at my previous companies I know this wouldn't probably be the case ( bad code, ego clashes, pointless red tape, etc) whereas now I spend my time in learning the technologies I want to learn, read books, and use the tools of my choice. It is boring sometimes, scary others, lack motivation at times, but overall quite satisfying as you solve challenges as a full stack developer.

To keep up to date and get new ideas I usually browse this website, programmers SE. Another thing I have done in the past is small gigs in odesk: you can work for other programmers on their projects and benefit from learning their techniques. Don't do it for the money though, unless you live in a country with very low wages.

One final word of advice: if you don't have several years of experiences already I would go back to a team of developers. All the different techniques and knowledge I have picked up over the years I don't think I would have been able to do it by myself, even with google and SO. A part of it is simply irreplaceable. At that point, I would say, you can make the most of being a solo developer and have fun.


问:
How do you demo software with No UI in the Sprint Review?
We are doing agile software development, basically following Scrum.   We are trying to do sprint reviews but finding it difficult.  Our software is doing a lot of data processing and the stories often are about changing various rules around this.

What are some options for demoing the changes that occurred in the sprint when there isn't a UI or visible workflow change, but instead the change is a subtle business rule on a processing job that can take 10s of minutes or even a couple of hours?

答:
One option I find potentially fulfilling to business (BSA's, BA's, managers, and the like) is providing a five to ten slide presentation on what was expected, and what was accomplished. And then if there is a meaningful method of displaying the results of the work done, such as a data dump, or SQL query results, and time to explain them somewhat, then I find the stakeholders to often be satisfied.

It is often difficult to provide a meaningful demo for non-programmers/non-technical staff on back-end type systems. I have tried the above a couple of times, and feel that the stakeholders were more satisfied in their response, than when I simply executed the software and showed them the results.

Granted however, this may be more work than its worth to you. You'll need to weight out the benefit and the work required to make it happen.


答:
During the sprint you create value. There is always some difference between what you had at start and end of sprint.  Normally even in a way noticeable by the client.  So just show the difference.

in some cases the sprint deals with discovery or internal rearrangements that may sound subtle, still you must be able to show the difference and explain the public why you think it good and what is the benefit from all the effort put in.  (?In a corner case you can refer to Edison who first discovered some over thousand ways of how it is NOT possible to make a working lightbulb.)

If real processing takes long, it's okay to show a time-zipped video or just a table of figures. Or pre-collected output of results.

Title: How do you demo software with No UI in the Sprint Review?

Body:
We are doing agile software development, basically following Scrum.   We are trying to do sprint reviews but finding it difficult.  Our software is doing a lot of data processing and the stories often are about changing various rules around this.

What are some options for demoing the changes that occurred in the sprint when there isn't a UI or visible workflow change, but instead the change is a subtle business rule on a processing job that can take 10s of minutes or even a couple of hours?


问:
Where does the reporting function fit into Enterprise Software development Best Practices
At my company, I develop and maintain all the operational reporting used by management to run the business.  There is no reporting position on the application development team.  I've taken it upon myself to step in and attend design review meetings to give input to the development team on how changes will impact reporting, consult on how modify designs to avoid impacting existing reports and what I will need in new development to be able to report on the data.  It's been my experience that reporting is a key functional position on an enterprise application development team.  I'm hoping to find some documentation that supports that concept as an industry standard or Best Practice.  Can anyone help me there?</p>

答:
I don't see why you are treating "reporting" differently from any other application.

It has users, it has requirements, it has interfaces to other systems.

So treat it like any other system. Identify the stakeholders, lock down the requirements and establish formal interfaces with your data providers.

Perhaps, more importantly, define it as a proper "project/application" within your company bureaucracy so the other teams must take into account the impact of their changes on your system. You need some sort of official status to force the other teams to comply with your interface definitions, and, go through the formal procedures when they want to change them.


问:
Independency and estimation of user stories that rely on shared predecessor
Lest's say I have user stories about using product catalog in shop:

As an administrator I can add/modify/delete catalog items (one or more user story, doesn't matter here)

As a customer I can search product catalog

As a customer I  can view product details

Each of this stories rely on predecessor: design and create database to store product information.

I can express db creation as:

another story: As a shop owner I want to store information about products I sell

Task to be done in story which will be firstly chosen to do

In first case I create story dependency, in second I wondering where estimate this additional task. Let's say it adds additional two story points. To which story should add this points? All (and re-estimate remaining stories in the future), none? I think that second option also can hinder estimation - I have to remember to add this story points to  dependent stories and then possibly remove it.

How to deal with such situations?

答:
I would avoid using story dependencies, it leads to a slippery slope.  As has been said before, how do you know you need a database.  Perhaps flat file or something similar could work for your situation.

Creating the database upfront/early is not really a good option as that will severely limit your options for the code.

I would move forward by using Mocks, XML or some other light weight data input mechanism for the development.  Then as the overall design for the code begins to evolve, you can use the Mocks/XML as the basis for your database design.  The mocks are not throw away, as they can be used later for automated validation of code changes.  Does the creation of the database even need to be work done in an iteration?  Is it possible to review the Mock structure with someone who could create the database based on the mocks and provide it at an agreed upon point in the future?

Story-wise, you may want to think about breaking down "As a customer I can search product catalog" even further?  How do they search the product catalog, by Product ID, Description, Color, Size, Price?  As written, I would say the story has a high probability of taking more than a single iteration to complete.

Finally I would suggest reading some of Scott Ambler's material at [http://www.ambysoft.com/scottAmbler.html][1]

[1]: http://www.ambysoft.com/scottAmbler.html  Scott has done a lot of work regarding databases and how they relate to agile.

Cheers!


答:
On what principles would you decide to add or exclude them from a language?

I don't think that's the right question. Every language designer has something in mind when they design their language, and that often will dictate some of the answers.  For example, if you are designing for type-safety, then you won't allow numbers to be true or false. If you are designing for "easy scripting", you will allow lots of short-cuts.

For example, SQL treats NULL and false as so different that you have to use different operators on them ("is null" vs "= false"). Ruby thinks 0 is true, but Perl thinks it's false.

In Ruby, the set of things that are false is small enough to be easy to remember (Just false and nil).

Where specifically have you used them to your advantage?

When picking up default values from various places:

```<code>my_name = env.name || command_line_swich.name || default_name
value = config['value'] || raise("no value found")
</code>```

Are there any problems you could see them causing off-hand?

Yes. In Perl, doing the above with numbers is a bad idea (because 0 could be valid, but will be ignored because it's false). Even in Ruby, it breaks when you have boolean values.

Are there any rules or finer points in your language/project/team about where it's appropriate or inappropriate to use them?

Not really. We use them wherever we can get away with it, which proves their value.

Title: The rationale behind Falsy values

Body:
I'm wondering what the arguments for/against Falsy values are. On what principles would you decide to add or exclude them from a language? Are there any problems you could see them causing off-hand?

For users of languages that support Falsy values:

Where specifically have you used them to your advantage?

Where have you had unpleasant run-ins with them?

Are there any rules or finer points in your language/project/team about where it's appropriate or inappropriate to use them?

For users of other languages:

Have you ever seen a situation where you've thought "I wish I could use a Falsy value here"?

I'm tagging the question haskell and python because AFAIK those two represent opposite ends of the spectrum (Haskell demanding Bools when you use if, and Python treating None and some "empty" values as Falsy), but feel free to talk about your experience from other languages. Just mention where on the spectrum they stand.

Body:
On what principles would you decide to add or exclude them from a language?

I don't think that's the right question. Every language designer has something in mind when they design their language, and that often will dictate some of the answers.  For example, if you are designing for type-safety, then you won't allow numbers to be true or false. If you are designing for "easy scripting", you will allow lots of short-cuts.

For example, SQL treats NULL and false as so different that you have to use different operators on them ("is null" vs "= false"). Ruby thinks 0 is true, but Perl thinks it's false.

In Ruby, the set of things that are false is small enough to be easy to remember (Just false and nil).

Where specifically have you used them to your advantage?

When picking up default values from various places:

my_name = env.name || command_line_swich.name || default_name
value = config['value'] || raise("no value found")

Are there any problems you could see them causing off-hand?

Yes. In Perl, doing the above with numbers is a bad idea (because 0 could be valid, but will be ignored because it's false). Even in Ruby, it breaks when you have boolean values.

Are there any rules or finer points in your language/project/team about where it's appropriate or inappropriate to use them?

Not really. We use them wherever we can get away with it, which proves their value.


问:
Requirements Analysis Communication
How can I convert this requirement into one requirement:
For columns where there are just numbers, numeric sorting will be used. For columns that have numbers and letters, alpha-numeric sorting will be used. For Date columns, time sorting will be used. All sorting will have ascending and descending properties.</p>

答: "Sort the chosen column using the the appropriate collating sequence for the data type, at least numbers, date, time and alphanumeric string types should be supported both ascending and descending."</p>

Title: Requirements Analysis Communication


问:
Getting Started with Data Collection and Analysis
I have a very very limited understanding of SQL and PHP. I have a few projects I want to try and work on, which will require doing some web scraping for data collection and then storing, sorting through, and analyzing the data. I would like to also have this data available on my website so others can sort through it as well.

My question is which direction I should go to learn the skills necessary for this. I am willing to put the time and effort in, but want to make sure I am going about it the right way. My first thought was to take an online Standford Intro to Databases course, then some web scraping tutorials, and then some PHP tutorials.

I then stumbled onto the software called "Orange", which is "Open source data visualization and analysis for novice and experts. Data mining through visual programming or Python scripting. Components for machine learning. Add-ons for bioinformatics and text mining. Packed with features for data analytics."

Would it be better to scrap the SQL and PHP learning and focus on learning this "Orange" program? Or any other programs? Any help would be appreciated. I am willing to work hard at this, but do not want to spend a lot of time learning SQL and PHP if I should focus elsewhere.

答: I'd go the PHP route--learn some good database theory (how to set up properly normalized tables, etc.), regular expressions (which you'll probably use for extracting the data), and other things related to the process as you find you need them. You'll learn a lot more that way than by using some other piece of software. It will also have wider applicability--just think of all the use cases for PHP, SQL, and (you will soon find) regular expressions that are removed from data collection and analysis.</p>


问:
How to unit test a class which is just an adapter that logs input and output to a third-party library?
I have the following (in C#, but the question could also apply to Java):

```<code>public interface ILibraryAdapter
{
    string Property1 { get; }
    string Method1(string param1);
    ...
}

public class ThirdPartyLibrary : ILibraryAdapter
{
    private readonly ThirdPartyClass thirdPartyClass;
    private readonly ILog log;

    public ThirdPartyLibrary(ThirdPartyClass thirdPartyClass, ILog log)
    {
        this.thirdPartyClass = thirdPartyClass;
        this.log = log;
    }

    public string Property1
    {
        get
        {
            log.Trace("ThirdPartyClass.get_Property1()");
            var result = thirdPartyClass.Property1;
            log.Trace(string.Format("ThirdPartyClass.get_Property1() returned {0}", result));
            return result;
        }
    }

    public string Method1(string param1)
    {
        log.Trace(string.Format("ThirdPartyClass.Method1({0})", param1));
        var result = thirdPartyClass.Method1(param1);
        log.Trace(string.Format("ThirdPartyClass.Method1({0}) returned {1}", param1, result));
        return result;
    }

    ...
}
</code>```

where the ... represents more of properties and methods being wrapped and logged (about two dozen total).

The separate calls to the logger in each method are part of the requirements.

How should I unit test this class?

Note: The names of the properties and methods of the third-party class do not always match the names of the properties and methods of ILibraryAdapter.

答:
If I were writing a test for this in Java, I would use a mocking library (like Mockito) and create a mock instance of ThirdPartyClass (and possibly the ILog instance).  Then I would create an instance of ThirdPartyLibrary, passing in the mocked objects.

Once you have that, call the methods you want to test, and verify that the interaction with the mocked objects are what you expect.


答:
How can I convert this requirement into one requirement

You can't - not if you want to write good requirements.

e.g. of what you should be striving for.....

Req A. Sorting will be done based on selected column with the choice of ascending or descending sort order.

Req B. The sort sequence will be based on the data type of the column, and will support Date, Time, Number and Alpha Numeric Formats

Req B1. Date sorting will be ......

Req B2. Time sorting will be ......

Req B3. Alpha sorting will be ......

......

this might be a bit OTT - on purpose to make a point....

Title: Requirements Analysis Communication

Body:
How can I convert this requirement into one requirement:
For columns where there are just numbers, numeric sorting will be used. For columns that have numbers and letters, alpha-numeric sorting will be used. For Date columns, time sorting will be used. All sorting will have ascending and descending properties.</p>


答:
The order that records are presented shall be determined by a composite sorting strategy.

A sorting strategy shall consist of a comparison method for a general data format and an arrangement (ascending or descending).  Examples of general data formats include alphanumeric, numeric, and datetime.

A composite sorting strategy is an ordered mapping of sorting strategies to column or field references where subsequent strategies act as tie breaker resolvers.

Title: Requirements Analysis Communication


问:
I don't understand how TDD helps me get a good design if I need a design to start testing it
I'm trying to wrap my head around TDD, specifically the development part. I've looked at some books, but the ones I found mainly tackle the testing part - the History of NUnit, why testing is good, Red/Green/Refactor and how to create a String Calculator.

Good stuff, but that's "just" Unit Testing, not TDD. Specifically, I don't understand how TDD helps me get a good design if I need a Design to start testing it.

To illustrate, imagine these 3 requirements:

A catalog needs to have a list of products

The catalog should remember which products a user viewed

Users should be able to search for a product

At this points, many books pull a magic rabbit out of a hat and just dive into "Testing the ProductService", but they don't explain how they came to the conclusion that there is a ProductService in the first place. That is the "Development" part in TDD that I'm trying to understand.

There needs to be an existing design, but stuff outside of entity-services (that is: There is a Product, so there should be a ProductService) is nowhere to be found (e.g., the second requirement requires me to have some concept of a User, but where would I put the functionality to remind? And is Search a feature of the ProductService or a separate SearchService? How would I know which I should choose?)

According to SOLID, I would need a UserService, but if I design a system without TDD, I might end up with a whole bunch of Single-Method Services. Isn't TDD intended to make me discover my design in the first place?

I'm a .net developer, but Java resources would also work. I feel that there doesn't seem to be a real sample application or book that deals with a real line of business application.  Can someone provide a clear example that illustrates the process of creating a design using TDD?

答:
A functionality can have many design and TDD will not completely tell you which one is the best. Even, if tests will help you build more modular code, it can also lead you to build modules that suits tests requirement and not production reality. So you have to understand where you are going and how things should fit in the whole picture. Put otherwise, there are Functional and Non-Functional requirements, don't forget the last one.

Concerning design I refer to Robert C. Martin books (Agile Development) but also Martin Fowler's Patterns of Enterprise Application Architecture and Domain Driver Design. The later especially is very systematical in extracting the Entities and Relations out of the requirements.

Then, when you get a good feelings of the options available to you on how to manage those entities, you can feed you TDD approach.


问:
Does anyone do hardware benchmarks on compiling code?
I've seen a bunch of sites that benchmark new hardware on gaming performance, zipping some files, encoding a movie, or whatever. Are there any that test the impact of new hardware (like SSDs, new CPUs, RAM speeds, or whatever) on compile and link speeds, either linux or windows?

It'd be really good to find out what mattered the most for compile speed and be able to focus on that, instead of just extrapolating from other benchmarks.

答: Tom's Hardware used to, but it looks like they stopped doing it back in 2008: http://www.tomshardware.com/charts/desktop-cpu-charts-q3-2008/benchmarks,31.html. None of the newer CPU charts include the Linux Kernel compiling test.</p>

ContentLicense: CC BY-SA 2.5


问:
How can this all fit into 64kb?
So, I am here at assembly 2011 and there was this demo played: http://www.youtube.com/watch?v=69Xjc7eklxE&feature=player_embedded

It's one single file only, it says that in the rules. So I repeat, how have they made this to fit into so small file?

答:
There is a PowerPoint presentation of how the rendering was done in this specific demo. This alone doesn't explain how everything fits into 64 kilobytes, but is the key for how the geometry was created in such a little space.

There is also lots of interesting read in his blog about his other demoscene productions.

Title: How can this all fit into 64kb?


问:
Is this pattern bad?
I notice that when I code I often use a pattern that calls a class method and that method will call a number of private functions in the same class to do the work. The private functions do one thing only. The code looks like this:

```<code>public void callThisMethod(MyObject myObject) {
    methodA(myObject);
    methodB(myObject);  // was mehtodB before
}

private void methodA(MyObject myObject) {
    //do something
}

 private void methodB(MyObject myObject) {
    //do something
}
</code>```

Sometimes there are 5 or more private methods, in the past I have moved some of the private methods into another class, but there are occasions when doing so would be creating needless complexity.

The main reason I don't like this pattern is that is not very testable, I would like to be able to test all of the methods individually, sometimes I will make all of the methods public so can I can write tests for them.

Is there a better design I can use?

答:
For me this seems like a bad practice for two reasons.

It is unclear how those methods depend on each other. If there is an order to strictly adhere to then this order should be reflected in the code. Otherwise a hidden temporal coupling (see item G31 in Clean Code) is introduced. Making the coupling  obvious can be achieved by returning an object from every method and passing that on to the next method.

If those methods don't really depend on each other an interface should be introduced with a single method. The different implementations should be kept in a collection in a field of the owning class of callThisMethod and that method should only iterate through that collection and invoke the collection elements method. This way you are adhering more to the open closed principle, because adding another functionality is just the matter of configuring another interface implementation to be kept in that list and not changing the owning class of callThisMethod

Title: Is this pattern bad?


问:
Implementing search over large data set, PHP or Mysql stored procedure?
I'm building an Online Food Ordering System with PHP and MYSQL, One of the feature of the application is to allow users to search for the restaurants by typing the area name.
I would like to know using PHP for search will be more efficient or using Stored Procedure or using any third party tool.

Efficient in the sense when it is to be searched among large set of data which one will be the fastest?

答:
Most likely this should be done with SQL. This would be simpler and have better performance.

But would depend on a few details. Especially how exact or complicated you want it to be able to find the information the user typed in (maybe a list of available areas would be a better ui option here)

You could do a simple search like:

```<code>SELECT * FROM areas WHERE name LIKE 'input%';
</code>```

This would of course fail for any typo the user makes and maybe return several records and you would have to offer the user further options to select one of those.

Assuming at some point you found a single record, it should be simple to find restaurants by area_id.

Body:
Most likely this should be done with SQL. This would be simpler and have better performance.

But would depend on a few details. Especially how exact or complicated you want it to be able to find the information the user typed in (maybe a list of available areas would be a better ui option here)

You could do a simple search like:

SELECT * FROM areas WHERE name LIKE 'input%';

This would of course fail for any typo the user makes and maybe return several records and you would have to offer the user further options to select one of those.

Assuming at some point you found a single record, it should be simple to find restaurants by area_id.


答:
You may need to redesign how client provide "area" information. The geography information is naturally in hierarchy. So you'd better provide a multi-steps input process. All restaurants are stored with state,city,town or street information, client will be provided with drop-down list, first select a state, then select a city, then a town or street, then you fetch the corresponding restaurants and display them on the page.

Or, leverage map service provider's API, first convert their INPUT into coordinates. And you have coordinates information associated with each restaurant.

Title: Implementing search over large data set, PHP or Mysql stored procedure?

Body:
I'm building an Online Food Ordering System with PHP and MYSQL, One of the feature of the application is to allow users to search for the restaurants by typing the area name.
I would like to know using PHP for search will be more efficient or using Stored Procedure or using any third party tool.

Efficient in the sense when it is to be searched among large set of data which one will be the fastest?


问:
Object oriented vs vector based programming
I am torn between object oriented and vector based design. I love the abilities, structure and safety that objects give to the whole architecture. But at the same time, speed is very important to me, and having simple float variables in an array really helps in vector based languages/ libraries like Matlab or numpy in Python.

Here is a piece of code I wrote to illustrate my point

Problem: Adding Tow volatility numbers. If x and y are two volatility numbers, the sum of the volatility is (x^2 + y^2)^0.5 (assuming certain mathematical condition but that's not important here).

I want to perform this operation very fast, and at the same time I need to ensure that people don't just add the volatility in the wrong way (x+y). Both of these are important.

The OO based design would be something like this:

```<code>from datetime import datetime
from pandas import *

class Volatility:
    def __init__(self,value):
       self.value = value

    def __str__(self):
       return "Volatility: "+ str(self.value)

    def __add__(self,other):
        return Volatility(pow(self.value*self.value + other.value*other.value, 0.5))
</code>```

(Aside: For those who are new to Python, __add__ is just a function that overrides the + operator)

Let's say I add tow lists of volatility values

```<code>n = 1000000
vs1 = Series(map(lambda x: Volatility(2*x-1.0), range(0,n)))
vs2 = Series(map(lambda x: Volatility(2*x+1.0), range(0,n)))
</code>```

(Aside: Again, a Series in Python is sort of a list with an index)
Now I want to add the two:

```<code>t1 = datetime.now()
vs3 = vs1 + vs2
t2 = datetime.now()
print t2-t1
</code>```

Just the addition runs in 3.8 seconds on my machine, the results I have given doesn't include the object initializaion time at all, its only the addition code that has been timed. If I run the same thing using numpy arrays:

```<code>nv1 = Series(map(lambda x: 2.0*x-1.0, range(0,n)))
nv2 = Series(map(lambda x: 2.0*x+1.0, range(0,n)))

t3 = datetime.now()
nv3 = numpy.sqrt((nv1*nv1+nv2*nv2))
t4 = datetime.now()
print t4-t3
</code>```

It runs in 0.03 seconds. That's more than 100 times faster!

As you can see, the OOP way gives me a lot of security that people won't be adding Volatility the wrong way, but the vector method is just so crazy fast! Is there a design in which I can get both? I am sure a lot of you have run into similar design choices, how did you work it out?

The choice of language here is immaterial. I know a lot of you would advise that use C++ or Java, and the code may run faster than vector based languages anyway. But that's not the point. I need to use Python, because I have a host of libraries not available in other languages. That's my constraint. I need to optimize within it.

And I know, that a lot of people would suggest parallelization, gpgpu etc. But I want to maximize single core performance first, and then I can parallelize both the versions of code.

Thanks in advance!

答:
This is one of those areas where it is impossible to give definitive answers, because it concerns a trade-off.
As you found out, neither OO, nor vector-based is always superior, but it all depends on how the software will be used.

You could try to combine the best of both and create both a Volatility object and a VolatilitySeries object, where the second conceptually represents a Series of Volatility objects, but internally uses a storage method that is much better suited for vectorizing the computations (a structure of arrays).
Then you just have to educate your users that using VolatilitySeries is much preferable over Series(Volatility).


问:
Is there a reason that tests aren't written inline with the code that they test?
I've been reading a bit about Literate Programming recently, and it got me thinking... Well-written tests, especially BDD-style specs can do a better job at explaining what code does than prose does, and have the big advantage of verifying their own accuracy.

I've never seen tests written inline with the code that they test. Is this just because languages don't tend to make it simple to separate application and test code when written in the same source file (and nobody's made it easy), or is there a more principled reason that people separate test code from application code?

答:
Another reason for separating tests is that you often use additional or even different libraries for testing than for the actual implementation. If you mix tests and implementation, accidential usage of test libraries in the implementation cannot be caught by the compiler.

Also, tests tend to have way more code lines than the implementation parts they test, so you'll have trouble finding the implementation between all the tests. :-)


问:
Does dedicated maintenance work hamper a programmer's career?
The majority of my work over the last three years has largely been around maintaining legacy systems that needed patching up or the occasional revamp before being sold again.

I understand the critical role dedicated maintenance programmers have to play in companies with a large number of projects and limited developers on hand.

But as I judge my current career progress and look at my peers; contractors and corporate developers alike; I do feel as if I am lagging far behind since I've gained a great deal of breadth in terms of the areas I've touched but not much depth.
I've begun to address this by starting a blog, working on my own little git-hub projects and rescheduling my life to have time to do personal coding after work on a regular basis.

I feel that were I to interview at other companies to escape maintenance work I would have to represent myself as being quite junior in skill level since I would not have the depth of level of knowledge required of a person with three years experience focused on a particular path in feature development would. So half my current work experience would count for naught in the long run.

But this leads me to my main questions, apologies if this feels too centered around my personal dilemma,:

Do dedicated maintenance programming roles end up being detrimental to an early career?
Are other programmers right to avoid roles like these?
Does doing this line of work lock you into doing similar tasks unless you're prepared to start over as a junior?

答:
In any job, the experience you get is specific to what you are doing, which limits your range of possibilities when applying for other jobs based on that experience.  It isn't specific to maintenance.  I think other questions are more relevant than whether something is maintenance or new software development:

How widespread are the specific technologies you are working with?  If you are maintaining something that is obsolete and rarely used elsewhere, then that would limit your future career opportunities (but so would developing new software for a system/platform/technology that is not widely used).

How does your current work equip you for the work you want to do in the future?  Maintenance work, as you pointed out, is important and will always be around.  There is nothing wrong with having a career focused on this type of programming; there will always be lots of possibilities for system maintainers.  But maybe it is not what you want to do.  It is a concern if your current work is not preparing you for what you are interested in.

However, I would not be too worried.  One thing you say is:

I've gained a great deal of breadth in terms of the areas I've touched
  but not much depth.

Don't think of this as a problem, because it can be used to your advantage.  Having broad experience means there is a wide range of things to which you can say "yes, I have done that."  Lots of jobs ask for experience in several different technologies and tasks.  You would likely have an advantage over a developer who has very deep experience in one technology.

Furthermore, lots of jobs involve a mixture of maintenance and new development.  If you wanted to do more new development, you could use your existing maintenance experience to transition into a mixed role that will give you more development experience.

In conclusion, your resume is probably better than you think it is.  A lot of it will come down to how well you analyze the strengths of your experience, and then communicate those strengths in the application and interview process.


问:
RESTful API design. What should I return if there are no rows?
I'm currently coding an API for a social network with the Slim Framework. My question is: What are the best practices when there are no rows to return in the json structure?

Lets say that this call /v1/get/movies returns 2 rows from the table movie names:

```<code>[
    {"name": "Ghostbusters"},
    {"name": "Indiana Jones"}
]
</code>```

But, then I call /v1/get/books and there are no rows in that table. Should I just return an empty structure?

```<code>[
]
</code>```

...or would it be better a message and an error code?

```<code>[
    "errors": {
        "message": "no matches found",
        "code": 134
    }
]
</code>```

Which is a better practice? (the API will be used in iOS and Android apps) Thanks!

答:
I don't think the rigth answer is the one that is marked.

The answer provided by nirth should be the best, in a true REST scenario. The body response should be empty and the http status code: 204; the resource does exists but it has "no content" at that time: is empty.

REST HTTP_Status_Codes


问:
Real world T4 usage
How many of you have ever used (or even know of)  the Visual Studio Text Templating Engine?

I mean, T4 templates have been around for quite some years now. The where initially included in Visual Studio 2005 SDK, and they where moved to Visual Studio 2008 core just before releasing it.

What I want to know is if this is really used out there. I mean, why doesn't the VS team invested in a descent minimal editor for the templates? It doesn't even have syntax couloring!
I know there are a couple of good T4 editors out there, but as they don't come built in, I tend to think that this is an unknown feature for most developers.

Have you ever used T4 templates in any of your projects? I'm really interested in answers that explain how they created their own T4 to accelerate, automate, or generate artifacts for your project.

答: I use the strong typed Page reference template from this article:  http://blog.devarchive.net/2008/01/auto-generate-strong-typed-navigation.html</p>

Title: Real world T4 usage


问:
Is this book a reliable source for beginning Java EE?
Core Servlets and Javaserver Pages: Core Technologies, Vol. 1 (2nd Edition)

Can I rely on this book to learn Servlets and JSP,or is there a better book out there I should be reading instead?

答:
Oracle covers both JSP and Servlet under SCWCD exam. The exam objective fully covers the advanced concepts so better you may prepare for SCWCD certification exam. It gives you deep knowledge in concepts. In my experience I said it, the certification help me more to go to next level in my carrier.

An excellent material I refer you that one I used for my preparation. I hope this is the only one material enough for your preparation, because it has both study guide and also sample mock exams.

The Exam Objectives are explained with example programs in this study guide so you can easily and quickly learn the concepts. I used EPractize Labs SCWCD 5 Certification Training Lab for my preparation.

For more details read the scwcd 5 preparation article.


答:
I would have to represent myself as being quite junior in skill level since I would not have the depth of level of knowledge required of a person with three years experience focused on a particular path in feature development would

Correct. You would not be able to say "3 years experience designing systems from scratch using X, Y, and Z", you'd have to say "3 years experience MAINTAINING systems from scratch using X, Y, and Z" unless you want to out right lie on your CV.

I feel that were I to interview at other companies to escape maintenance work I would have to represent myself as being quite junior in skill level since I would not have the depth of level of knowledge required of a person with three years experience focused on a particular path in feature development would

If you want to say "I design and build systems from scratch" then yes, you would have to class yourself as junior.

What is quite common in IT, (and I'm not saying this is what you are doing) is for people to assume that because they have been working for X years, they have X years experience and after {indeterminate number of years} they should be considered a Senior {Widget} developer.

Now, don't get me wrong, there is nothing wrong with maintenance work, everybody has to do it at some time or another, but what you have realised is that being stuck doing that for too long will likely make it hard for you to get away from that role in the future. This often goes hand in hand with being "stuck" not learning newer technologies/tools/methods.

Ideally, you want a mix of "new" system work and legacy work.

On a positive note, you presumably have seen a lot of different architectures (good and bad), different approaches, how bad decisions can make the legacy programmers work much harder later down the line. These are all positives than can be accentuated.

Good luck!

Title: Does dedicated maintenance work hamper a programmer's career?

Body:
The majority of my work over the last three years has largely been around maintaining legacy systems that needed patching up or the occasional revamp before being sold again.

I understand the critical role dedicated maintenance programmers have to play in companies with a large number of projects and limited developers on hand.

But as I judge my current career progress and look at my peers; contractors and corporate developers alike; I do feel as if I am lagging far behind since I've gained a great deal of breadth in terms of the areas I've touched but not much depth.
I've begun to address this by starting a blog, working on my own little git-hub projects and rescheduling my life to have time to do personal coding after work on a regular basis.

I feel that were I to interview at other companies to escape maintenance work I would have to represent myself as being quite junior in skill level since I would not have the depth of level of knowledge required of a person with three years experience focused on a particular path in feature development would. So half my current work experience would count for naught in the long run.

But this leads me to my main questions, apologies if this feels too centered around my personal dilemma,:

Do dedicated maintenance programming roles end up being detrimental to an early career?
Are other programmers right to avoid roles like these?
Does doing this line of work lock you into doing similar tasks unless you're prepared to start over as a junior?


答:
Do dedicated maintenance programming roles end up being detrimental to an early career? Are other programmers right to avoid roles like these? Does doing this line of work lock you into doing similar tasks unless you're prepared to start over as a junior?

First up, you should know that you're considered a junior for quite a while. You may get arbitrary promotions because you're good and this is the only way to give you a decent payrise, but you'll still be considered a junior as you head on to your next job.

Second, if I'm hiring someone with 2-4 years' experience, I don't really care whether their work was purely maintenance. If you've spent 10 years in maintenance and I'm hiring for a greenfields project, I may have questions but, for the first few years, I honestly kind of expect it.

On the other hand, if I'm hiring someone who has NEVER worked in maintenance, I'm going to be more suspicious. I've had many candidates for jobs who have spent their first 4 years skipping from one "good" job to another and every single one has learned nothing about what makes for maintainable code. And, make no mistake, if I'm hiring for a greenfields project I intend to stick with, I don't care whether YOU are going to maintain the code, I care that you know how to leave it maintainable for future developers.

These other programmers you mention, who avoid jobs like these, generally avoid them because they're less fun, not because it hinders their career.

Finally, you should know that a very large percentage (I would conservatively guess at about 80%) of software development jobs are more than 50% maintenance.

So, to cut through all that and answer your question: No, I don't think it's going to hinder your career. Unless you stay there for far too long. The common rule of thumb is "once you start feeling like you're getting the same year of experience every year, it's time to go." If you feel, each year, like you're a better developer than you were last year, you're fine (and that goes for me, 20 years into my career, as much as you).


问:
Design pattern advice required for sending xml files to different destinations
I am using an Export Module, now I want to extend it for different connections.
I have a database which contains products
Its Description, Review, Images etc. I use the serialize function to save it as XML file.
After saving it as XML, in admin pannel I have possibility to select how this XML file will be exported.

for example throught ftp, http, local, webservice, email etc.
user has the possibility to select one or more connections to export the files.

Each connection like ftp, http has it own settings in Database e.g ftp domain, username, password.

what will be the best way to write these connection classes (by implementing Interface or using Abstract class or some Manager)

and how to pass them to the export component as one exoprt may have on to many connections.

答:
You can use something along the lines of the Factory Pattern.

A sample of it for your situation would be along the lines of

```<code>public interface IExporter
{
    void ExportXmlFile(string pathToFile);
}
public abstract class Exporter : IExporter
{
    public Exporter() { }

    public virtual void ExportXmlFile(string pathToFile)
    {

    }
}

public class ExportertFactory
{
    public static IExporter GetExporter(ExportType type)
    {
        switch (type)
        {
            case ExportType.Ftp:
                return new FtpExporter();
            case ExportType.Http:
                return new HttpExporter();
            case ExportType.Xml:
                return new XmlExporter();
            default:
                throw new Exception("Unknonw ExportType");
        }
    }
}
public enum ExportType
{
    Xml = 1,
    Ftp = 2,
    Http = 3
}

public class FtpExporter : Exporter
{
    public FtpExporter()
        : base()
    {
        //Connect to database to get FTP Settings
    }

    public override void ExportXmlFile(string pathToFile)
    {
        //Export File via FTP
    }

}
public class HttpExporter : Exporter
{
    public HttpExporter()
        : base()
    {
        //Connect to database to get Http Settings
    }

    public override void ExportXmlFile(string pathToFile)
    {
        //Export File via Http
    }
}

public class XmlExporter : Exporter
{
    public XmlExporter()
        : base()
    {
        //Connect to database to get Xml Settings
    }

    public override void ExportXmlFile(string pathToFile)
    {
        //Export File via Xml
    }
}

public class Client
{
    public Client()
    {

    }
    public void ExportFile()
    {
        IExporter exportMethod = ExportertFactory.GetExporter(ExportType.Ftp);
        exportMethod.ExportXmlFile("FilePath");
    }
}
</code>```

Depending on what method the user clicks, or for each one you can create the necessary

```<code>IExporter exportMethod = ExportertFactory.GetExporter(ExportType.Ftp);
exportMethod.ExportXmlFile("FilePath");

exportMethod = ExportertFactory.GetExporter(ExportType.Http);
exportMethod.ExportXmlFile("FilePath");
</code>```

lines for each one.

The abstract class Exporter is optional. You may chose to put some common functionality there for each export type. If you chose not to use it, just set each concrete implementation to use the interface, rather than the abstract class

Body:
You can use something along the lines of the Factory Pattern.

A sample of it for your situation would be along the lines of

public interface IExporter
{
    void ExportXmlFile(string pathToFile);
}
public abstract class Exporter : IExporter
{
    public Exporter() { }

    public virtual void ExportXmlFile(string pathToFile)
    {

    }
}

public class ExportertFactory
{
    public static IExporter GetExporter(ExportType type)
    {
        switch (type)
        {
            case ExportType.Ftp:
                return new FtpExporter();
            case ExportType.Http:
                return new HttpExporter();
            case ExportType.Xml:
                return new XmlExporter();
            default:
                throw new Exception("Unknonw ExportType");
        }
    }
}
public enum ExportType
{
    Xml = 1,
    Ftp = 2,
    Http = 3
}

public class FtpExporter : Exporter
{
    public FtpExporter()
        : base()
    {
        //Connect to database to get FTP Settings
    }

    public override void ExportXmlFile(string pathToFile)
    {
        //Export File via FTP
    }

}
public class HttpExporter : Exporter
{
    public HttpExporter()
        : base()
    {
        //Connect to database to get Http Settings
    }

    public override void ExportXmlFile(string pathToFile)
    {
        //Export File via Http
    }
}

public class XmlExporter : Exporter
{
    public XmlExporter()
        : base()
    {
        //Connect to database to get Xml Settings
    }

    public override void ExportXmlFile(string pathToFile)
    {
        //Export File via Xml
    }
}

public class Client
{
    public Client()
    {

    }
    public void ExportFile()
    {
        IExporter exportMethod = ExportertFactory.GetExporter(ExportType.Ftp);
        exportMethod.ExportXmlFile("FilePath");
    }
}

Depending on what method the user clicks, or for each one you can create the necessary

IExporter exportMethod = ExportertFactory.GetExporter(ExportType.Ftp);
exportMethod.ExportXmlFile("FilePath");

exportMethod = ExportertFactory.GetExporter(ExportType.Http);
exportMethod.ExportXmlFile("FilePath");

lines for each one.

The abstract class Exporter is optional. You may chose to put some common functionality there for each export type. If you chose not to use it, just set each concrete implementation to use the interface, rather than the abstract class


答:
Isn't TDD intended to make me discover my design in the first place?

No.

How can you test something that you have not designed first?

To illustrate, imagine these 3 requirements:

A catalog needs to have a list of products

The catalog should remember which products a user viewed

Users should be able to search for a product

These are not requirements, these are definitions of data. I do not know what is the business of your software, but it is not likely that analysts speak that way.

You need to know what are the invariants of your system.

A requirement would be something like:

A customer can order a certain quantity product, if there is enough of this product in stock.

So if this is the only requirement, you may have a class like:

```<code>public class Product {

  private int quantity;

  public Product(int initialQuantity) {
    this.quantity = initialQuantity;
  }

  public void order(int quantity) {
    // To be implemented.
  }

}
</code>```

Then using TDD, you would write a test case before implementing the order() method.

```<code>public void ProductTest() {

    public void testCorrectOrder() {

        Product p = new Product(10);
        p.order(3);
        p.order(4);

    }

    @Expect(ProductOutOfStockException)
    public void testIncorrectOrder() {

        Product p = new Product(10);
        p.order(7);
        p.order(4);

    }

}
</code>```

So the second test will fail, then you can implement the order() method the way you like.

Title: I don't understand how TDD helps me get a good design if I need a design to start testing it

Body:
I'm trying to wrap my head around TDD, specifically the development part. I've looked at some books, but the ones I found mainly tackle the testing part - the History of NUnit, why testing is good, Red/Green/Refactor and how to create a String Calculator.

Good stuff, but that's "just" Unit Testing, not TDD. Specifically, I don't understand how TDD helps me get a good design if I need a Design to start testing it.

To illustrate, imagine these 3 requirements:

A catalog needs to have a list of products

The catalog should remember which products a user viewed

Users should be able to search for a product

At this points, many books pull a magic rabbit out of a hat and just dive into "Testing the ProductService", but they don't explain how they came to the conclusion that there is a ProductService in the first place. That is the "Development" part in TDD that I'm trying to understand.

There needs to be an existing design, but stuff outside of entity-services (that is: There is a Product, so there should be a ProductService) is nowhere to be found (e.g., the second requirement requires me to have some concept of a User, but where would I put the functionality to remind? And is Search a feature of the ProductService or a separate SearchService? How would I know which I should choose?)

According to SOLID, I would need a UserService, but if I design a system without TDD, I might end up with a whole bunch of Single-Method Services. Isn't TDD intended to make me discover my design in the first place?

I'm a .net developer, but Java resources would also work. I feel that there doesn't seem to be a real sample application or book that deals with a real line of business application.  Can someone provide a clear example that illustrates the process of creating a design using TDD?

Body:
Isn't TDD intended to make me discover my design in the first place?

No.

How can you test something that you have not designed first?

To illustrate, imagine these 3 requirements:

A catalog needs to have a list of products

The catalog should remember which products a user viewed

Users should be able to search for a product

These are not requirements, these are definitions of data. I do not know what is the business of your software, but it is not likely that analysts speak that way.

You need to know what are the invariants of your system.

A requirement would be something like:

A customer can order a certain quantity product, if there is enough of this product in stock.

So if this is the only requirement, you may have a class like:

public class Product {

  private int quantity;

  public Product(int initialQuantity) {
    this.quantity = initialQuantity;
  }

  public void order(int quantity) {
    // To be implemented.
  }

}

Then using TDD, you would write a test case before implementing the order() method.

public void ProductTest() {

    public void testCorrectOrder() {

        Product p = new Product(10);
        p.order(3);
        p.order(4);

    }

    @Expect(ProductOutOfStockException)
    public void testIncorrectOrder() {

        Product p = new Product(10);
        p.order(7);
        p.order(4);

    }

}

So the second test will fail, then you can implement the order() method the way you like.


问:
What is the justification of use .inc files to declare and implement code is some Delphi RTL units?
Starting with #Delphi #XE2 many of the new RTL units related to Vcl styles, OSX and so on, uses inc files to declare types, classes and implement code (just like the FPC does), what is the justification to do that? you can see what i mean if you inspect one of these folders (source\rtl\posix, source\rtl\posix\osx, source\rtl\sys )</p>

答: Possibly to avoid duplicating this stuff in framework/platform specific units and without adding them to the most basic RTL units. Then again, that could also have been achieved with separate units. For type declarations that should really have been done. For implementation code I can see one reason to put it into an .inc file instead of its own unit: the code is relying on the Delphi specific rules regarding private class members (strict private was added to avoid this).


问:
What is a Package Diagram? and What is a Sequence Diagram?
In many interviews I've been asked this question. What is a Package Diagram? and What is a Sequence Diagram? and difference between Package Diagram and Sequence Diagram.

Thanks in Advance.

Edit

Sorry, google give me lot of answer, but i want to practical answer with example.

答:
Well, some googling would have brought up the answers in a few seconds.

Package Diagram

Package diagrams can use packages containing use cases to illustrate the functionality of a software system. Package diagrams can use packages that represent the different layers of a software system to illustrate the layered architecture of a software system. The dependencies between these packages can be adorned with labels / stereotypes to indicate the communication mechanism between the layers.

People find package diagrams extremely useful on larger-scale systems to get a picture of the dependencies between major elements of a System . These diagrams correspond well to common programming structures . Plotting diagrams of packages and dependencies helps you keep an application's dependencies under control.

Sequence Diagram

A sequence diagram shows object interactions arranged in time sequence. It depicts the objects and classes involved in the scenario and the sequence of messages exchanged between the objects needed to carry out the functionality of the scenario. Sequence diagrams are typically associated with use case realizations in the Logical View of the system under development

Since you have a C++ background, the concept of packages is probably not known to you. You can roughly compare it to the concept of namespaces in C++. Its main purposes are encapsulation and dependency minimation as well as simplifying division of labor and structuring your system at design time.


问:
Solo developer vs. team developer : should I move on?
I work as a solo developer in a small company. There's more than enough work, but the same does not apply for money. Thus, I won't be seeing any new colleagues in the near future.

I am responsible for absolutely everything that has do to with IT operations. This involves development and maintenance of software used in-house, development and maintenance of various websites which our clients use, website infrastructure, local network infrastructure including maintenance of several servers and in-house support to mention the most immediate things.

I really enjoy 95% of what I do, and I've got a high degree of flexibility in my work. I get to decide what do when, and no one really tells me what do to except that I now and then sit down with my colleagues to create a roadmap for what I need to get done. I do consider myself to have a high work ethic and being above average focused on what I do, so things get done.

However, I've come to the point where I really miss having other people around me who work with the same. Even though I need to get familiar with a wide range of technologies as I am a solo developer, I have the feeling that I am missing out one the "knowledge sharing" which other "like minded" people who work in bigger companies are taking part in. I don't really have anyone to discuss programming obstacles and design decisions with - and I am starting to miss that. Also, I'm worried about what future employers might think of this "hermit" who has been working on his own for too long to ever be able to take part in a team.

However, on the other side, I'm thinking that I won't get my current degree of flexibility in a larger company. I'll be seeing a lot more strict deadlines, late hours and specialized areas of work. Also; I'm not sure if this idea of "knowledge sharing" will ever take take place?

Has anyone else been in this situation? Is it a good idea seen from a career perspective and a personal development perspective? Should I consider moving on to a bigger place to (maybe) become a part of a larger group of developers and "like minded" people? In other words, will the grass be greener on the other side?

答:
As an extension to the "Join an OpenSource-project"-idea from @NemanjaTrifunovic I can suggest going to conferences or do professional trainings.

Getting out of the daily routine by seeing how others fix problems you had/have, or to see how new technologies may help to change your view, or to learn a new technology which has nothing to do with your current job can be a great motivation boost.

Why not presenting your solutions on a conference yourself?

Your boss, if he is clever, will be happy to pay you all the (travel/trainings-)costs, because he (should) knows that things like that motivate a lot.

And in addition to that you might build up a network which in the future will help you find a job.


问:
JUnit Testing in Multithread Application
This is a problem me and my team faces in almost all of the projects. Testing certain parts of the application with JUnit is not easy and you need to start early and to stick to it, but that's not the question I'm asking. The actual problem is that with n-Threads, locking, possible exceptions within the threads and shared objects the task of testing is not as simple as testing the class, but testing them under endless possible situations within threading.

To be more precise, let me tell you about the design of one of our applications:

When a user makes a request several threads are started that each analyse a part of the data to complete the analysis, these threads run a certain time depending on the size of the chunk of data (which are endless and of uncertain quality) to analyse, or they may fail if the data was insufficient/lacking quality. After each completed its analysis they call upon a handler which decides after each thread terminates if the collected analysis-data is sufficient to deliver an answer to the request.

All of these analysers share certain parts of the applications (some parts because the instances are very big and only a certain number can be loaded into memory and those instances are reusable, some parts because they have a standing connection, where connecting takes time, ex.gr. sql connections) so locking is very common (done with reentrant-locks). While the applications runs very efficient and fast, it's not very easy to test it under real-world conditions.

What we do right now is test each class and it's predefined conditions, but there are no automated tests for interlocking and synchronization, which in my opionion is not very good for quality insurances.

Given this example how would you handle testing the threading, interlocking and synchronization?

答:
Since I was never really happy with the answers I received I had already given up and solved the concurrency issues with time but without having actual tests that proved that they were not existing any more. But today I stumbled upon a solution for the problem.

Links that explain writing those kind of tests:

https://github.com/junit-team/junit/wiki/Multithreaded-code-and-concurrency

http://tempusfugitlibrary.org/recipes/2012/05/20/testing-concurrent-code/

http://www.planetgeek.ch/2009/08/25/how-to-find-a-concurrency-bug-with-java/

In short all these tests initialize Runnable and start them at exactly the same time to achieve a maximum concurrency-load, this way concurrency issues should be exposed.


问:
Unit tests and language-native function calls
Is there a best practice for calling language-native functions when writing testable code?

I have experimented a little with php code and have come up with two methodologies:

create a wrapper class for all native functions and mocking this wrapper when writing tests

using "namespace magic": calling all native functions without  specifying the global namespace (aFunction in stead of \aFunction) and then writing a method stub in the given namespace during testing, which will result in the code to be tested using the stub instead of the native function

Is there a more commonly used approach? What are the benefits and shortcomings of the most commonly used methodologies to test language-native function calls?

答:
You don't unit-test language native functions. You test your code. You rely on the language you're using as well as on any third party library.

Library / Language Code

If you want the external code to be tested, that's ok, but not within your project. Fork the third party software, and do the tests there, be it PHP or a mailer class or whatever. Many projects come with unit tests nowadays, so likely there already is something for you to build on.

The reason is simple. As soon as you fix something in a third party software, you immediately loose the ability to update, and thus the greatest benefit from using that software. Forking into your own (sub) projects works like a proxy, where you can change the software, but still are able to update (e.g. using git rebase), and, as an extra, you can easily contribute back to the projects, you rely on.

Resources

If you - like you stated in your comment - want to make FTP (or MySQL or whatever) testable, i.e., get independend from PHP resources, encapsulate them in their own classes. If you use an FTP class like

```<code>class FTP
{
    ...

    public function connect($server, $user, $pass)
    {
        ...
    }

    public function put($bytes)
    {
        ...
    }

    ...
}
</code>```

in combination with Dependency Injection, you can easily mock it. The class itself is usually not unit-tested - it is subject of an integration test within a controlled environment.

Body:
You don't unit-test language native functions. You test your code. You rely on the language you're using as well as on any third party library.

Library / Language Code

If you want the external code to be tested, that's ok, but not within your project. Fork the third party software, and do the tests there, be it PHP or a mailer class or whatever. Many projects come with unit tests nowadays, so likely there already is something for you to build on.

The reason is simple. As soon as you fix something in a third party software, you immediately loose the ability to update, and thus the greatest benefit from using that software. Forking into your own (sub) projects works like a proxy, where you can change the software, but still are able to update (e.g. using git rebase), and, as an extra, you can easily contribute back to the projects, you rely on.

Resources

If you - like you stated in your comment - want to make FTP (or MySQL or whatever) testable, i.e., get independend from PHP resources, encapsulate them in their own classes. If you use an FTP class like

class FTP
{
    ...

    public function connect($server, $user, $pass)
    {
        ...
    }

    public function put($bytes)
    {
        ...
    }

    ...
}

in combination with Dependency Injection, you can easily mock it. The class itself is usually not unit-tested - it is subject of an integration test within a controlled environment.


答:
I think you should convince your company to look for at least one other developer. Maybe a junior that you would train on-site to become familiar with the system. That way you would have an on-going, purposeful stream of conversation.

Point your company to the Bus Factor to convince them. Only having one developer responsible for everything is a very high risk. No one should keep all their eggs in only one basket.


问:
Is Java (still) the cross platform language of choice?
When I started using Java in the nineties, it was all "Write once, run anywhere!" from day one. That was probably all true then and I was a part of the choir as well.

I am not sure what to think about that anymore, considering all the other languages using multi platform runtimes (python, flash, perl, html, php...). But I am still seeing lots of arguments that says you should use Java because it is supposedly better for cross platform development.

So, Is that still true today? Is Java still the language of choice for multi platform development?

Please be specific with focus on cross platform aspects.

I am not asking for general language feature comparisons.

Update: Great responses so far! Most answers seems to be favoring Java or web. Any input from the script crowd?

答:
I think you have those choices:

1) use either a

compiled or

interpreted
language.

2) How will you package and deliver your code?

One "front-end", one binary/script?

One "front-end", multiple binaries/scripts?

Multiple "front-ends", multiple binaries/scripts?

Those choices affect performance, soure code visibility and distribution.

Do you mind giving away your source code? Compiled languages might be for you.
Compiled languages seem to perform better in micro-benchmarks than interpreted (even JITed) languages. Also if you depend on a runtime environment like Java, Python, Ruby etc your code might be harder to distribute.

I found that most popular cross-platform desktop applications go for "One front-end, multiple binaries" using C/C++ and a crosss-platform widget library, e.g.Audacity, Blender, Firefox, Google Earth, OpenOffice, Skype, Songbird, Stellarium, VLC.


问:
Need help understanding Constructor Chaining
I'm trying to understand constructor chaining better. I understand that this technique can be used to reduce code duplication for initialization of a class object and I also understand the order in which they're executed.

I found the following example and I cannot see clearly what the benefits are in the code? And whether it's necessary? I don't understand why both constructors have 'this' keyword in them, would calling either constructor (and passing in relevant parameters) have the same result?

```<code>//Constructors
public MyClass(double distance, double angle) : this(distance, angle, 0)
{
}

public MyClass(double distance, double angle, double altitude) : this()
{
Distance = distance;
Angle = angle;
Altitude = altitude;
}
</code>```

答:
First off, you get reduced code duplication as the top constructor is chained to the second - passing in a 0 for the altitude parameter; the other passed in parameters are passed in to the chained constructor from the values used in the constructor itself (the distance and angle parameters). The reduced duplication is in the fact that the second constructor is the one doing the initialization and it is not duplicated in the first constructor.

Another benefit is that you now have overloaded the constructor such that the altitude parameter is optional and will default to 0 if not supplied.

The second constructor is chained to a parameterless constructor that you have not shown in your example. This one may very well initialized other parts of the class - initialization that is not repeated elsewhere.

would calling either constructor (and passing in relevant parameters) have the same result?

Sure. But this is some nice syntactic sugar - makes the code easy to read and short.


问:
Using GPLv3 software in a open source project licensed BSD (3-Clause)

Preamble

If I say "BSD" I mean the 3-Clause BSD license

If I say "GPL" I mean the GPLv3 license

I am not the author of the GPL project

I am the author of the BSD project

Simple Task

I want to use a 3rd party software (GPL) in (or better 'with') my open source project (BSD).

Situation

I won't change any of the GPL project code (using it AS IS).

I want to use it as kind of a library (I know about LGPL but it's not available).

I will use the GPL software as bulk, not only parts of the code.

I will indicate the use of the GPL project with the license, homepage and where and why it is used in my BSD project (in README file).

I will not take the credits for the functionality of the GPL project.

I will take the credits for my project and the "Adapter" connecting my BSD project to the GPL project.

I don't want to re-license the GPL project as BSD

I won't charge any fees or something like that.

To gain insight, you can find the BSD project at

GitHub: MOC-Framework (see /Extension/FlowPlayer and /Module/Office/Video)

and the GPL project here:

Flowplayer (free flash-version)

Simple Question

Is this possible?

Closing Words

I found some discussions, stating "it is possible", others say "no". Most of the "no" were for commercial projects. Most of the "yes" are referring to: "include BSD in GPLv3", but that's not what I mean. I want GPLv3 along with BSD.

I simply can't figure it out.

答:
Yes, it's possible to link your BSD project and the GPL project.  However, it means you must release the combined version as GPL.

Skim over FSF's GPL compatible licenses and you'll see a range of commentary about how well a particular license can fold into the GPL.  And yes, by compatible, what FSF really means is how easily can you combine two works and release the resultant work as a GPL'd work.  It's obviously a bit self-serving, but at least you can better understand the ramifications to your project when you combine it with a GPL'd project.


答:
In my opinion the most relevant benefit apart from achieving minimal code duplication is that using an object with chained constructors always yields full and correctly initialized objects with the least amount of executed code, even if the client doesn't have enough information about the parameter values.

Another point is that by using chained constructors, you are able to get more construction possibilities for free if you use them in Telescopic Constructor Pattern. If you find yourself confused with too many parameters, consider the Builder Pattern instead. Joshua Bloch wrote about the refactoring in Effective Java Item 2.

Title: Need help understanding Constructor Chaining

Body:
I'm trying to understand constructor chaining better. I understand that this technique can be used to reduce code duplication for initialization of a class object and I also understand the order in which they're executed.

I found the following example and I cannot see clearly what the benefits are in the code? And whether it's necessary? I don't understand why both constructors have 'this' keyword in them, would calling either constructor (and passing in relevant parameters) have the same result?

```<code>//Constructors
public MyClass(double distance, double angle) : this(distance, angle, 0)
{
}

public MyClass(double distance, double angle, double altitude) : this()
{
Distance = distance;
Angle = angle;
Altitude = altitude;
}
</code>```


问:
How do you demo software with No UI in the Sprint Review?
We are doing agile software development, basically following Scrum.   We are trying to do sprint reviews but finding it difficult.  Our software is doing a lot of data processing and the stories often are about changing various rules around this.

What are some options for demoing the changes that occurred in the sprint when there isn't a UI or visible workflow change, but instead the change is a subtle business rule on a processing job that can take 10s of minutes or even a couple of hours?

答:
My own personal preference for things that do back-end work is to find the end-user change.  If the data you are processing eventually winds up in a report, show the before/after differences in the report.

I'm assuming the desire for the change came from a need.  What was the problem that triggered the need to do the story?  Your user story 'voice form' should indicate to you how you will be able to demo the problem by acting as the user in your story (i.e. As Joanne I need to view the report without users that are in Europe).

Additionally, you can look to your test team to help you in this case.  There must have been some way that the test team was able to verify that the story was Done.  How did they do this?  Are you able to show that process within the demo?


问:
mvc pattern - splitting model into data-access and business logic layers
I've had a chance to try it out and I like it very much. I'm thinking of using it in all of my future projects. I'd like to hear some critique and opinions about it. I've done a little research on the subject and I'm not sure I've seen this approach around, but I'm pretty sure that it must have been tried by some more experienced people and I'd like to avoid any pitfalls that come with it

The idea is that model is split into:
1. db access layer (dal)
2. business logic layer (bll)

so db access layer contains (ideally) no logic at all other then db access logic - prepared queries that are supplied with parameters, when called, and which return results from db, if needed (in case of SELECT queries). these classes are not tested (if no logic is inserted into them), since they don't contain any if/for/while/throw... commands

business logic layer which contains actual logic of the app. controllers do not see dal and only call bll which in turn calls dal when needed. bll needs to be tested (i use unit testing) and since it is kept separate from the db access, when read-only functionality is being tested, db access can be mocked using dependency injection (create mock class alternative for every dal class with all the same methods, load them via the factory method when requested from bll and depending on whether the call came from testing environment or not load either mock or 'real' class. of course in case of write functionality (DELETE, INSERT), testing would have to include db calls, so in that case 'real' class would be called, rather then mock, but this can still be very useful if system has more read then write db calls

Benefits of this approach:

code separation - it keeps your business logic clean of db access code which improves readability, especially in big methods that need to make several calls to db. it makes it easier to maintain code and also allows you to encapsulate db access logic, which can be called from a numer of blls which also makes it easier to maintain

it makes it easier to switch databases at any point, which is not something that happens often, but if it does happen, it's not an easy thing to do, everybody who had to do it at some point know what i'm talking about

when testing bll with mock classes, it makes tests run faster since no calls to db are made. this is not too significant, but can help when you are tweaking some functionality intensively and testing it along the way. at the same time it makes it much easier to test performance of 'pure logic' detached from db calls

drawbacks:

more cluttering because of adding whole new layer of classes to the system

slightly lower performance due to the added dependancy injection which takes time to resolve

while mock classes do nice work, they do have to be created and maintained so there is added bureaucracy to the whole system

Am I missing anything? Do you prefer system that I described or good ol' fashion 3 layer mvc and why? I'm no guru, I'm still exploring various architectures, but I like this one very much and would love to hear what my more experienced colleagues have to say about it

答:
Your instincts are good, but I don't think they should be part of MVC thinking anymore, because both business logic and data access should be independent of view.  You should be able to reuse both regardless of whether they are displayed using browser, desktop, tablet, or mobile device.

I think it falls under the category of proper layering for a service oriented architecture.

Services need not SOAP; deployment choices are separate.  These are interface-based objects.

What you call "business logic" is what I think of as the service layer.  I disagree with the statement about business logic not knowing about persistence tier.  Business logic must know about the persistence tier, because it needs to manage transactions as units of work.

I also disagree with the "lower performance due to added dependency injection".  This should be done on startup and won't have a measurable effect on long-term averages.  It's amortized over all the calls to the service.

Both service and persistence layers should be interface based.

OwnerDisplayName: Ajant

OwnerDisplayName: duffymo


答:
MVC means model-view-controller separation for the client-side, in this case, your site. It has nothing to do with the backend layering.

Concerning backend layering; I personally like the onion approach as described here and applied here. The business layer is independent on the data layer implementation or any other technical aspect, as it only knows interfaces.

So in your controller you use the backend services (note that I'm not saying WCF services - it can be WCF, but doesn't have to be). You get data back in a specific format (the model) and you then could transform this data into viewmodels which are designed specifically for a view.

The backend services would then have the various layers that you need to implement the chosen architecture (business layer, data layer etc), but this is independent of your ASP.NET MVC site.

And don't avoid using dependency injection for the wrong reasons. It should be the default programming style.

Title: mvc pattern - splitting model into data-access and business logic layers

Body:
I've had a chance to try it out and I like it very much. I'm thinking of using it in all of my future projects. I'd like to hear some critique and opinions about it. I've done a little research on the subject and I'm not sure I've seen this approach around, but I'm pretty sure that it must have been tried by some more experienced people and I'd like to avoid any pitfalls that come with it

The idea is that model is split into:
1. db access layer (dal)
2. business logic layer (bll)

so db access layer contains (ideally) no logic at all other then db access logic - prepared queries that are supplied with parameters, when called, and which return results from db, if needed (in case of SELECT queries). these classes are not tested (if no logic is inserted into them), since they don't contain any if/for/while/throw... commands

business logic layer which contains actual logic of the app. controllers do not see dal and only call bll which in turn calls dal when needed. bll needs to be tested (i use unit testing) and since it is kept separate from the db access, when read-only functionality is being tested, db access can be mocked using dependency injection (create mock class alternative for every dal class with all the same methods, load them via the factory method when requested from bll and depending on whether the call came from testing environment or not load either mock or 'real' class. of course in case of write functionality (DELETE, INSERT), testing would have to include db calls, so in that case 'real' class would be called, rather then mock, but this can still be very useful if system has more read then write db calls

Benefits of this approach:

code separation - it keeps your business logic clean of db access code which improves readability, especially in big methods that need to make several calls to db. it makes it easier to maintain code and also allows you to encapsulate db access logic, which can be called from a numer of blls which also makes it easier to maintain

it makes it easier to switch databases at any point, which is not something that happens often, but if it does happen, it's not an easy thing to do, everybody who had to do it at some point know what i'm talking about

when testing bll with mock classes, it makes tests run faster since no calls to db are made. this is not too significant, but can help when you are tweaking some functionality intensively and testing it along the way. at the same time it makes it much easier to test performance of 'pure logic' detached from db calls

drawbacks:

more cluttering because of adding whole new layer of classes to the system

slightly lower performance due to the added dependancy injection which takes time to resolve

while mock classes do nice work, they do have to be created and maintained so there is added bureaucracy to the whole system

Am I missing anything? Do you prefer system that I described or good ol' fashion 3 layer mvc and why? I'm no guru, I'm still exploring various architectures, but I like this one very much and would love to hear what my more experienced colleagues have to say about it

OwnerDisplayName: Lud


问:
Daily Scrum when the team is just fixing bugs
I understand all the advantages of Daily Scrum and my team does it when we are working on stories.

But sometimes we just have bugs to fix for days, while we're waiting for new stories, and when this happen we put daily scrum aside. Some of developers says that "There's no need to do a Daily Scrum when we have nothing to discuss".

I don't know if a Daily Scrum when we don't have any new story to develop is necessary. Is there anything interesting we can do on a daily scrum when we just have bugs to fix?

答:
The whole SCRUM is summarized in a single picture and like 2 pages of text. It has very few "mandatory" elements. Daily SCRUM is one of them. Guess what? ;-)

I don't get the motivation not doing it. If there is nothing to discuss, everybody will just report that and it is over in 15 seconds. With everybody happy that whole team is on track.

And if someone have something relevant to report?


问:
Automatically observing changes in database tables
currently I'm working on a project with the following setting:

There is a proprietary application which performs transactions on a Microsoft Access database (which is actually stored as an .mdb file)

The API of the application doesn't have enough functionality for the requirements we're facing

Our application has direct access to the database

We're designing a C# application which has to react to events which are not triggered through the API, so the only way I can think of is to somehow observe the database directly and react accordingly to custom events.

One approach would probably be to query the DB time triggered and react, but this possibly leads to performance issues when the DB is large. I would rather appreciate an approach, where the DB itself notifies our application if specified events occur.

EDIT: The proprietary application is Enterprise Architect modeling tool, so the expected number of concurrent users will definitely not exceed 10 users and the database size will not be larger than 50 MB. Would it probably be an acceptable solution to outsource the polling activity in a separate thread and notify the rest of the application by events?

Concerning the number of users and database size, which load can the MS Access database approximately handle?

Is there any well-known pattern/approach for this kind of problem available and if you don't know any, how would you face this problem?

答:
Microsoft Access(2010+) have data macros which are like triggers, but I don't think they run unless an Access application is running or if an ODBC connection can recognize them. You may not have the ability to add these.

It's not too much to have a service pole the database. As far as your performance concerns, the frequency may need to be less than you prefer. The number of concurrent users is going to affect this as well. You have no control over this third party app to optimize performance on that end.

I have no idea if this is a pattern.


问:
Experimenting with "big data" and map reduce
I was thinking about experimenting a bit with using mapreduce and such on a dataset we have to see if we can benefit from it in any way.

What route should I go if I want to be able to instantly, without any major modification, deploy my findings to some kind of grid/cloud-system to see if there is any extra benefit to have it scaled in the cloud.

答:
"The Cloud" is just a bunch of machines that you don't own. Running on those machines is no different than running on the machines that you do own, except that you pay for the time and bandwidth.

If you're using a tool like Hadoop, adding machines is just a matter of configuration (you don't mention platform, but it's the main player in the non-Google map-reduce space, which is just one of the big-data techniques).

My recommendation is that you work through the tutorial, get a single-node implementation of your application running, then immediately move to a cloud service like Amazon EC2. You can start with two small instances for about a dollar a day, and increase the number of machines from there.

As a cautionary note: unless you're dealing with 100s of gigabytes of data (and preferably terabytes), I don't think you'll see much benefit of either horizontal scaling or "the cloud." There is a not-insignificant time to setup and teardown map-reduce operations.