答:
There are several different approaches you can take to solve this.

Have static form pages for each client

This is the easiest to build. You can define pages and fields that are unique to the client. Each page can have the client's unique look. Common code will be a little bit more difficult as things like event handlers for different fields will have to be replicated on all of the appropriate pages. You can minimize some of this by using a client framework.

Have a series of fields on each page that determines which field is shown based on the client

This sounds like what you have now. One page to rule them all. And a huge mess if the logic or application flow changes between clients. Common code won't have to be replicated as all of the code will be common to the page that it is on. You can use a client framework to help with the page production, but then you introduce the frameworks limitations on top of your monolithic page.

Build a system that allows for configurable questions based on any criteria you desire

This would be the most difficult to build. You still have one page to rule them all, but from the server you would determine what fields need to be placed on the page. A lot of logic on the page will be simplified, almost to the same point as the static form option above. Common code would be heavily used, but more from the building of the page rather than on it. You would have the option of building page completely on the server, essentially serving a single page to user based on your client's options. You could use a client framework to dress up the browser with a more responsive application page. This system may also require using the dreaded EAV style of data storage, not that there's anything wrong with this technique. There are some caveats associated with getting data from an EAV data store.

Title: How to build configurable forms?

Body:
I'm working on two separate projects now that are essentially just CMSs -- a bunch of forms for recording various bits of information. Each project is built to serve many clients, and each client seems to want to record slightly different information.

In one project we've handled this either by copying and pasting all the logic surrounding that form for each client so that we could make the changes without affecting the other clients, or we build a master form containing all possible inputs and then programmatically remove the inputs that the client doesn't want (our framework allows us to remove inputs (essentially from the 'controller') before the final template rendering). Neither solution is really clean and causes the forms to be riddled with "if" conditions based on which client we're serving.

The other project I'm just starting, and I don't want to run into the same pitfalls again, but I'm having trouble coming up with a good way to solve this problem.

I could list out all the input IDs for each form element in the database and then create a mapping between them and the clients, and then in my form template wrap each widget rendering with a check to see if the input is enabled for the current client. On the backend -- when the form is submitted -- I could save only the data that is submitted and forgo the conditionals for the most part. This creates a dependency on the IDs used in the template must match those recorded in the DB -- I don't want to create the entire form programatically as that wouldn't give me enough customizability. That's the best I can come up with.

Has anyone dealt with this sort of problem before? How did you approach it? What worked, what didn't?

For comparison, you might consider sites like Freshbooks, or Trello, or a bug tracker, or Facebook -- if any of those apps let each user customize his or her page to add or remove inputs so that they could record only the stuff they care about -- how would they manage this complexity from an architectural point of view?


问:
Merging branches where the same code was worked on
If there are two unrelated tasks, except that the changes are in the same project, and end up touching at least one of the same classes/methods, how do I manage that?

Two different developers could each pick up one task.  Each dev will create a new branch off of Integration, work in it, then need to Merge.

When Merging two branches, most of the time "Take Source Branch" is proper for Up-Merging, and "Take Target Branch" is proper for Back-Merging.

But when Back-Merging, or dual-merging up, there could be conflicts which overwrite the code of the previously merged project if they both changed the same class/method.

One answer is: "So only let one dev work on both tasks sequentially."  Except that we're in SCRUM and any dev can pick up any task.  We don't want to start assigning.

Another answer is: "Have the devs get together and hash out how to manually merge some stuff."  But that's work!  Lol.  Is there a method I'm missing?

答:
You have answered your own question:

Another answer is: "Have the devs get together and hash out how to manually merge some stuff."

That's the only way to resolve this sort of merge conflict. Assuming you don't have rogue developers forking your project, as a team you will have to agree what is the correct result of merging independent work.

There is no magic bullet that will resolve conflicting merges. It's work.

ContentLicense: CC BY-SA 3.0


问:
What is the general tech news website every programmer should read?
A link and a quick explanation why would be very helpful.

General tech news, I mean not like InfoQ which is too technical. Probably much more like P.SE than SO.

EDIT: site should help developers gain general knowledge about the industry, technologies, inventions, etc. Much like when we listen to the news every morning in our car to know what is happening in our world. But target audience must be either programmmers, geeks or any other persons interested in technology.

答: Nettuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites. We cover HTML, CSS, Javascript, CMS’s, PHP and Ruby on Rails.

ContentLicense: CC BY-SA 2.5


问:
How to support different API Versions
I am writing a Rest API and am wondering how best to handle supporting the different versions. By this I don't mean how to define a URI as V2 or V3, but rather how to structure the code given that it'd need to:

Support multiple versions at the same time, eg. V1 & V2 & V3 URIs must be live at the same time. I would retire V1 when say V4 comes in in order to constrain the amount supported at any one time.

Avoid as much code duplication as possible

Make it easy to add non-breaking changes to a version, without it impacting on other versions

It would seem that there are few approaches that could be taken:

Use Git to control the versions, with a branch for the different versions (and old versions  essentially having no new development work done on it). This would mean no code duplication as only the latest version is in the code, but previous versions would need to work with the new version of the DB until they are retired.

Duplicate code so that each version is handled in the same application and has a totally separate code path, but this would mean a lot of duplication

Re-use a lot of code across the versions, but this would make it harder to maintain as changing one version is more likely to impact a previous version

Is there any best practice to deal with this problem as all options seem to have their own problems?

答:
I don't know how different the results are from your API versions are, but you could have a compatibility layer in the middle which can toggle between the versions and fill in gaps or translate data.

That being said - it usually never works out one to one - so a switch or state machine type design has helped me with this problem.

Title: How to support different API Versions


问:
Which classes should be autowired by Spring (when to use dependency injection)?
I have been using Dependency Injection in Spring for some time now, and I understand how it works and what are some pros and cons of using it. However, when I'm creating a new class I often wonder - Should this class be managed by Spring IOC Container?

And I don't want to talk about differences between @Autowired annotation, XML configuration, setter injection, constructor injection, etc. My question is a general one.

Let's say we have a Service with a Converter:

```<code>@Service
public class Service {

    @Autowired
    private Repository repository;

    @Autowired
    private Converter converter;

    public List<CarDto> getAllCars() {
        List<Car> cars = repository.findAll();
        return converter.mapToDto(cars);
    }
}

@Component
public class Converter {

    public CarDto mapToDto(List<Car> cars) {
        return new ArrayList<CarDto>(); // do the mapping here
    }
}
</code>```

Clearly, the converter doesn't have any dependencies, so it's not necessary for it to be autowired. But for me it seems better as autowired. Code is cleaner and easy to test. If I write this code without DI, the service will look like that:

```<code>@Service
public class Service {

    @Autowired
    private Repository repository;

    public List<CarDto> getAllCars() {
        List<Car> cars = repository.findAll();
        Converter converter = new Converter();
        return converter.mapToDto(cars);
    }
}
</code>```

Now it's much more difficult to test it. Moreover, new converter will be created for every convert operation, even though it's always in the same state, which seems like an overhead.

There are some well known patterns in Spring MVC: Controllers using Services and Services using Repositories. Then, if Repository is autowired (which it usually is), then Service has to be autowired too. And this is quite clear. But when do we use @Component annotation? If you have some static util classes (like converters, mappers) - do you autowire them?

Do you try to make all classes autowired? Then all the class dependencies are easy to inject (once again, easy to understand and easy to test). Or do you try to autowire only when it's absolutely necessary?

I've spent some time looking for some general rules on when to use autowiring, but I couldn't find any specific tips. Usually, people talk about "do you use DI? (yes/no)" or "what type of dependency injection do you prefer", which doesn't answer my question.

I would be grateful for any tips concerning this topic!

答: I don't think you have to @Autowired all your classes, it should be depends on the real usage, for your scenarios it should be better use static method instead of @Autowired. I haven't see any benefit use @Autowired for those simple utils class, and that will absolutely increase the Spring container cost if not use it properly.</p>


问:
Does tweeting 9 to 5 hurt job applicants?
If you were looking into a job applicant's background and discovered that he or she has 1200 followers on Twitter and averages 50 tweets per day (more than half of which are during business hours), would it affect your hiring decision? How and why?

Personally, I'd be a little worried about the candidate's ability to focus on the job at hand if they're constantly checking in with their 'tweeps' thoughout the day. In non-tech jobs, a lot of companies simply block Twitter as an irrelevant distraction.  But it can be a useful resource---to programmers in particular. I just wonder how much is too much. At what point does it become a red flag?

答: It can count against the candidate for me but if he has a great interview, good recommendations and looks all set for the job I will try not to let him go. </p>


问:
.Net Best Practices : Common Bugs Introduced By Refactoring, Carelessness, and Newbies
What are the common bugs introduced by refactoring, carelessness, and newbies?

I would like to request the experienced programmers here to share their experience and list the bugs they used to introduce when they were inexperienced.

In your response, please write a headline mentioning the kind of bug in bold text, followed by few linebreaks, and then an explanation, cause of the bug, and finally the fix.

答:
Manually written values instead of constants

Example:

```<code>public District GetDefaultDistrict() {
  return GetById(1);
}

public IList<Revenue> GetRevenues() {
  return GetByCodes(new [] { 8010, 8011, 8096 });
}
</code>```

and thousands of use of 1, 8010, 8011 and 8096 in other places. Try to image if the default district now is 2 and 8011 moved to 8012.

Fix:

```<code>public District GetDefaultDistrict() {
  return GetById(Consts.DEFAULT_DISTRICT_ID);
}

public IList<Revenue> GetRevenues() {
  return GetByCodes(Consts.REVENUE_CODES);
}
</code>```

and use this constants everywhere where you need to determine default district id and/or other static values.

Or even:

```<code>public IList<Revenue> GetRevenues() {
  var codes = GetRevenueCodes(); // get from db
  return GetByCodes(codes);
}
</code>```

to get actual values from db. But this is just an example.

Body:
Manually written values instead of constants

Example:

public District GetDefaultDistrict() {
  return GetById(1);
}

public IList<Revenue> GetRevenues() {
  return GetByCodes(new [] { 8010, 8011, 8096 });
}

and thousands of use of 1, 8010, 8011 and 8096 in other places. Try to image if the default district now is 2 and 8011 moved to 8012.

Fix:

public District GetDefaultDistrict() {
  return GetById(Consts.DEFAULT_DISTRICT_ID);
}

public IList<Revenue> GetRevenues() {
  return GetByCodes(Consts.REVENUE_CODES);
}

and use this constants everywhere where you need to determine default district id and/or other static values.

Or even:

public IList<Revenue> GetRevenues() {
  var codes = GetRevenueCodes(); // get from db
  return GetByCodes(codes);
}

to get actual values from db. But this is just an example.


问:
Should we write detailed architecture design or just an outline when designing a program?
When I'm doing design for a task, I keep fighting this nagging feeling that aside from being a general outline it's going to be more or less ignored in the end. I'll give you an example:

I was writing a frontend for a device that has read/write operations. It made perfect sense in the class diagram to give it a read and a write function. Yet when it came down to actually writing them I realized they were literally the same function with just one line of code changed (read vs write function call), so to avoid code duplication I ended up implementing a do_io function with a parameter that distinguishes between operations. Goodbye original design.

This is not a terribly disruptive change, but it happens often and can happen in more critical parts of the program as well, so I can't help but wondering if there's a point to design more detail than a general outline, at least when it comes to the program's architecture (obviously when you are specifying an API you have to spell everything out).

This might be just the result of my inexperience in doing design, but on the other hand we have agile methodologies which sort of say "we give up on planning far ahead, everything is going to change in a few days anyway", which is often how I feel.

So, how exactly should I "use" design?

答:
Its always important when you are creating any document to understand what it's purpose is.

I think we have to be careful what we call "architecture" documents. It's all a matter of scope.

If you are talking about a system that requires several teams or groups of teams, then you are talking about a document who's purpose is to detail out at a minimum:

What are the components in the system

How are the components connected

What are each components responsibilities

Who should be working on each component

If your document is for a smaller system then you can reduce the number of items you need to include because some assumptions will be inherent to the existing system. For example suppose you are putting a feature together that will need to have work done in a website and some new calls in an API, then your document will serve as a way to nail down the following:

What logic will live in the website

What logic will live in the API

What will the API calls contracts be (best guess)

These outline documents serve to bring conversations to the front on who should do what and how should they integrate. Once those decisions are made then teams can operate largely autonomously with a much lower chance of integration issues.

The more integration issues you perceive, the more detailed you should documents should be.


问:
Testing a very specific function in a large, complex application
I'm new to testing but wholeheartedly realize how important it is. The main issue is that my company has no top-down support for testing at all. That is we don't have any unit testing and just a bit of human testing (I hope I'm using the right terminologies).

I have been trying to get testing started here and have to do it subtly because I'm often asked "when will feature X be done" and therefore can't start the week(s) long project of writing tests for all of our legacy code. Which would need to get rewritten just to provide seams for testing (if I have the concept of 'seams' right). I can, however, sneak a bit of time to test one function. Or at least I think I can.

I'm writing code that basically processes quite a bit of data and then renders it using D3. I would like to write a test for one of the most important functions, binData. It takes one optional argument (the date to start binning from) and accesses a few properties like this.rows and this.timestamps.

How would I go about doing that?

I think I'll need to create a mock object to hold this.data and this.timestamps (and the other accessed properties). In fact, I imagine several different mock objects which would allow testing of several different datasets. But other than that I'm kinda stuck. In terms of frameworks I've heard of Mocha and Jasmine and Vows but don't know which would be best.

I also don't know how to tie into the massive (and complex) class and module hierarchy and to meet each object's dependencies. That is, the function binData is in a file called, say, dataBinner.js which requires all sort of other functions in other files but doesn't explicitly include anything on it's own. Instead, it itself is included in a "manager" file which includes everything that dataBinner.js and the other modules will need. I suppose I'll need to find a way to instantiate everything necessary to test binData.

I'm not afraid to do a bit (or a lot) of reading to better understand things. Any help regarding this specific task of writing a test for binData or the larger question of how to slowly implement testing in a non-test-friendly place would be much appreciated.

CLARIFICATION

I'm 100% on board, testing-wise. I know it's important and I know that my company is incorrect by not having testing. You'd expect emails that say "fixed regression caused by fixing bug 1413" would trigger something. Or that things that shouldn't take that long take waaaaaay too long ('cause it's spaghetti legacy code).

What I'm asking is given that how do I test my one function which relies on the legacy spaghetti code. That is, how does someone inject a bit of testing into a place without it? I'm guessing that I'll have to write my own testing framework because I'll have to create mocks for the spaghetti legacy code. So that I can instantiate my object and call my function outside of the scope of the application.

答:
I'm afraid I have to agree with @Robert Harvey in that the lack of a culture of testing is your real problem. From that point of view, it's not really about mocking or getting your test to work, but on deciding whether or not you want to change this culture in your company. Be aware, that cultural changes are hard - as in almost frustratingly hard.

I suggest you do a lot of reading if you want to tackle this challenge. You must not be dumb-founded when met with resistance, but should have enough knowledge on your back to counter any arguments your managers may come up with.

Here are some particularly interesting reads in that regard:

Michael Feathers - Working with Legacy code: This one is interesting for the mere fact of his definition of legacy code. He states (and I paraphrase here) that

Legacy code is code without tests.

Based on that definition, your company is currently in the business of actively developing legacy code. Way to go.

Robert C. Martin's books about Clean Code. The first book is more about technical details, interesting for developers. However, his second book deals with professionalism in our workspace, and he makes a few important points about what it means to be a professional developer and how that ties into writing tests and holding deadlines. This book in particular will give you a lot of things to wrap your head around - and a hell of a lot of attack vectors on your current company culture's professional behavior.


问:
Do I need a suite of unit tests for inner business-logic class? Since it's going to replicate the acceptance test suite for 90%
I'm new to TDD and wondering about methodolody.

Given:

A simple project which implements functionality of, for example, a console calculator.

It has the following structure:

Fairly simple top-level class that takes console input, delegates it to a buisness-logic class and shows output in the console with some fancy formatting.

The forgoing buisness-logic class which does all the calculations and which is relatively complex.

Also let's assume we have a nice thorough suite of acceptance tests for the whole project, which performs through the user interface.

Do I need a suite of unit tests for inner business-logic class? Since it's going to replicate the acceptance test suite for 90%.

Additional, but closely related questions:

Will the answer for the question remain the same if, for example, that acceptance test suite takes 30 sec to run? 5 mins? 1 hour?

If the inner business-logic class is not yet implemented, do I need write that suit of unit tests to guide its development, or it's fine to remain only with acceptance tests?

答:
Do I need a suite of unit tests ...

Unit tests are no end in itself - you should better ask "Do I need a suite of unit tests if I want to reach a certain goal". If your goal is just to make sure the software you are writing behaves correctly "as a black box" from outside, you only need acceptance tests.

But if your goal is also that your business-logic is properly structured into small components (instead of one big "god" class), and each of that components should behave correctly, then you will need unit tests for each of that components. The reason for having components is that this keeps your software more evolvable (it will become easier to add new requirements) and more maintainable (when you added a new requirement, and you had to change the existing code, and your acceptance tests shows that you introduced a bug, the unit tests might help you to spot the root cause of that bug more quickly).

So the gist is - unit tests make only sense in the presence of units.

If the inner business-logic class is not yet developed, do I need write that suit of unit tests to guide its development?

TDD is not about writing a suite of tests beforehand. It is about writing unit tests and code "almost in parallel" ("write test - write code - refactor - rinse and repeat").

EDIT (to your comment): if you have acceptance tests in place, your program works as it should, there is no direct reason to introduce unit tests yet.

But, as soon when you have to change something in your code (probably because of new requirements), and you want to do TDD, then its a good idea to start writing unit tests for exactly the parts of your code you want to change (and not a "full test suite").

Maybe you start with a test for a function to verify its current behaviour ("green"). The acceptance tests will prevent you from introducing a bug in this stage. Then you modify the test or add an additional test to verify the intended behaviour (which makes your unit test "red"). Afterwards you add the new functionality to your function (which makes you tests green again). And now comes the important part: you check if your function has become so complex that you better refactor it now - which can be done very painlessly because of the tests you just introduced.

So the idea of unit tests (in a TDD context) is not to duplicate the purpose of acceptance tests, but to help you with your actual coding and low-level design improvements.


答:
You have multiple responsabilities in your example; all of them should be covered by their own tests.

You say you take console input, so you probably need something to parse and validate arguments. What if for example you don't pass numbers, but text? What are the upper and lower boundaries of the arguments you're willing to accept? Etc...

You have the business logic classes itself, which you can probably easily drive through tests

You have a formatter, which can also be driven by tests

You can use acceptance tests as sort of a high-level test, which you'd write first. It will ofcourse fail, because you'll be invoking all sorts of classes that don't even exist yet. But at this point you'll have a rough idea of the components you'll need.

Then you can drive each of the individual components through tests and when you're done with that, the acceptance test should pass as well.

Body:
I'm new to TDD and wondering about methodolody.

Given:

A simple project which implements functionality of, for example, a console calculator.

It has the following structure:

Fairly simple top-level class that takes console input, delegates it to a buisness-logic class and shows output in the console with some fancy formatting.

The forgoing buisness-logic class which does all the calculations and which is relatively complex.

Also let's assume we have a nice thorough suite of acceptance tests for the whole project, which performs through the user interface.

Do I need a suite of unit tests for inner business-logic class? Since it's going to replicate the acceptance test suite for 90%.

Additional, but closely related questions:

Will the answer for the question remain the same if, for example, that acceptance test suite takes 30 sec to run? 5 mins? 1 hour?

If the inner business-logic class is not yet implemented, do I need write that suit of unit tests to guide its development, or it's fine to remain only with acceptance tests?


答:
Are you looking for this person to only work 9-5?  Does a programmer really need to work from 9-5?  Might want to check this out:
http://en.wikipedia.org/wiki/ROWE

The focus should be on the results of the work, not time spent sitting in a particular location.  If you think they can do the work, hire them.

Title: Does tweeting 9 to 5 hurt job applicants?

Body:
If you were looking into a job applicant's background and discovered that he or she has 1200 followers on Twitter and averages 50 tweets per day (more than half of which are during business hours), would it affect your hiring decision? How and why?

Personally, I'd be a little worried about the candidate's ability to focus on the job at hand if they're constantly checking in with their 'tweeps' thoughout the day. In non-tech jobs, a lot of companies simply block Twitter as an irrelevant distraction.  But it can be a useful resource---to programmers in particular. I just wonder how much is too much. At what point does it become a red flag?


问:
Hungarian Notations/Systems Hungarian Should I?
I was wondering would it be worth using a form of standard such as Hungarian Notation/Systems Hungarian?

Why would I bother if everything I'm doing now is working fine?

答:
I will answer something opposite of the question. Hungarian notation actually works GREAT with autocomplete.

Say you have a variable, and the name is intHeightOfMonster.

Say you forget the name of the variable

It could be heightOfMonster or MonsterHeight or MeasurementMonsterHeight

You want to be able to type a letter and get the autocomplete suggest to you some variable names.

Knowing that the heightOfMonster is an int, you just type i and voila.

Save time.


问:
What is the appeal of Systems Hungarian?
In a now deleted question titled "What naming guidelines do you follow?", the author says:

Also I prefer to code using hungarian notation from Charles Simonyi.

I've run in to several programmers who still prefer to use Hungarian, mostly of the Petzold/Systems Hungarian flavor.  Think dwLength = strlen(lpszName).

I've read Making Wrong Code Look Wrong, and I understand the rationale for Apps Hungarian, where domain-type information is included in the variable names.  But I don't understand the value in attatching the compiler type to the name.

Why do programmers still persist on using this style of notation?  Is it just inertia?  Are there any benefits that outweigh the decreased readability?  Do people just learn to ignore the decorators when reading the code, and if so, how do they continue to add value?

EDIT:
A lot of answers are explaining the history, or why it is no longer relevant, both of which are covered in the article I cited.

I'd really like to hear from anyone out there who still uses it.  Why do you use it?  Is it in your standard?  Would you use it if it wasn't required?  Would you use it on a new project?  What do you see as the advantages?

答:
There is one thing people are missing with Hungarian. Hungarian notation actually works GREAT with autocomplete.

Say you have a variable, and the name is intHeightOfMonster.

Say you forget the name of the variable

It could be heightOfMonster or MonsterHeight or MeasurementMonsterHeight

You want to be able to type a letter and get the autocomplete suggest to you some variable names.

Knowing that the heightOfMonster is an int, you just type i and voila.

Save time.

ContentLicense: CC BY-SA 4.0


问:
Why do we use hungarian notations on local variable but not on function or global variable?
That doesn't seem to make sense.

In local variable, we sort of know the type anyway. It's local. We're working on it.

Yet in function name or global variable, the definition is very far away on other files. It seems that hungarian notations make far more sense there.

For example, in objective-c I used this

```<code>+(CGFloat) fHeightOfNavigationController
</code>```

So when I want to know the height of navigation controller, I will need to press a button that specify the function.

What's the button? What's the name of the function. Is it heightOfNavigationController? Is it NavigationControllerHeight? Is it navHeight?

I don't know which letter I should type first to activate the autocomplete. But I know the function is float.

So I just type f...

Tada... I got fHeightOfNavigationController in autocomplete.

Yet I don't think this is how most people use hungarian notation.

Why?

答:
People don't use Hungarian notation any more, its a nice idea that's had its day.

Everyone knows the problem with Hungarian - apart from making your names garbled with a special code - if you change anything, you then also have to change the name to match.
So if you have a function called iGetCustomer and one day you want to return more than just an integer, you have to change everywhere the function is called to be cstGetCustomer which is just a nuisance. (though, obviously, you have to change everywhere its used anyway as you've changed the return type!)

Still, its just one of those fashion things, nobody uses it any more, instead they use a form of name coding where some types are notated differently (eg interfaces with I prefix, exception classes with 'Exception' suffix etc).

WRT intellisense, many people type this. and then let the system present a list to pick from. If you also name according to function rather than return type, you can then group your functions (eg GetX, GetY, etc will all appear together whereas iGetX and fGetY will not).


答:
Let's assume that you have at least 3 layers of code, a presentation layer, an application/domain layer, and a persistence layer.

Since your acceptance test exercise the entire stack in your application, once you experience a bug, there is quite a lot of places where the bug could have been introduced, and after the first initial implementation of the code for a single test case, there could easily be multiple bugs present. Detecting the bug/bugs can take a considerable amount of time.

But if you do develop each of these layers in a test driven way, then there is a much higher probability that you find the bugs early, and the location of the bug is more isolated. Thus you would probably spend a lot less time fixing bugs.

Also remember that TDD is about tests driving the implementation. When practicing TDD, you are constantly changing focus from tests to implementation. This change of context is healthy for the though processes as it is a lot easier to discover patterns in code. If you on the other hand focus solely on the implementation, you brain tends to be locked onto the details of the implementation and fails to see the big picture*.

This last part, I did not write as much as a reason as to whether or not you should, or should not, write unit tests for individual software components. But more because you mention TDD as part of the question, and I wanted to bring into focus, that TDD is not just about writing unit tests - it's more of a development process.

For more info on the the process of TDD, I can recommend Ken Beck's book: Test Driven Development: By Example

* One of the reasons pair programming is effective is because the person not typing is more free to think about the big picture.

Title: Do I need a suite of unit tests for inner business-logic class? Since it's going to replicate the acceptance test suite for 90%


答:
If your business-logic class is not yet written then your acceptance tests can only be complete for what WAS written and not what the program WILL do. One of the ideas of TDD is to write the tests such that they fail now, write the code, and then see if all the tests pass, when they do then you know you are done. That only works however if the tests you write full define what the requirements of the project are, at a business level.

You need to decide what the tests are supposed to be doing.

Is the point of them to let you know when you have finished writing code, in which case you need to have the tests full define what your requirements are, see them as an enumeration of all the acceptance criteria that will make your stack holders happy.

Is the point of them to give you confidence in the codes quality, this will allow you to refactor the code and verify that it still does what it is supposed to. In this case you need to focus more on testing interfaces between components so that internal changes can be show to exhibit the same external behaviour.

Is the point to verify to a developer, while developing, that they haven't broken old requirements or that they are meeting new requirements, in which case the speed of the suite could have an impact. If you have a very tight loop where developers can run the tests so quickly they do so frequently, with time to known quality very short, then you need to include only tests that can be run quickly. These tests can then be split up in to different suites to be run at different times, e.g. in the editor after ever save, on commit, along side a build, after build, weekly, continuously etc.

Is it enough to use those acceptance tests which are already in place, or I need to develop additional unit tests?

It depends. What is the point of adding these new tests? What goal are you striving for? Acceptance tests are great to keep around if they are giving you extra information, confidence in the code, helping identify bugs. You might not agree with everything in this piece but take a look at Why Most Unit Testing is Waste as he suggests that even keeping the old tests might not be that valuable. Decide upon what you want and structure your test approach to that.


答:
hungarian isn't used all that much anymore for various reasons, most importantly code completion software solves most of the problems hungarian aimed to solve.

also hungarian in it's original format (apps hungarian) specified the usage of the variable instead of just the type (systems hungarian). Meaning that the coordinates of the mouse cursor on the screen would be scrXmouse and scrYmouse instead of imouseX and imouseY.

A function to transform it to local view could then be named translateScrXScrY2LocXLocY(int srcX, int scrY, int* locX, int* locY); then you immediately see when you made a mistake in variable order

Title: Why do we use hungarian notations on local variable but not on function or global variable?

Body:
That doesn't seem to make sense.

In local variable, we sort of know the type anyway. It's local. We're working on it.

Yet in function name or global variable, the definition is very far away on other files. It seems that hungarian notations make far more sense there.

For example, in objective-c I used this

```<code>+(CGFloat) fHeightOfNavigationController
</code>```

So when I want to know the height of navigation controller, I will need to press a button that specify the function.

What's the button? What's the name of the function. Is it heightOfNavigationController? Is it NavigationControllerHeight? Is it navHeight?

I don't know which letter I should type first to activate the autocomplete. But I know the function is float.

So I just type f...

Tada... I got fHeightOfNavigationController in autocomplete.

Yet I don't think this is how most people use hungarian notation.

Why?


问:
In which step of a software development life cycle I should design my computing algorithm?
In software design, we usually take care of UML diagrams and architecture design.

But in case of a data analysis software, we must pay attention to design algorithms and stuff like that. Consider the case of a face detection software which needs AI. Do we need to design AI part of the software explicitly in software design?

P.S: My manager says that it must set clear in feasibility study and be so clear that we could design it in design steps. Is he correct?

答:
From my experience, it is better to start with the algorithm itself. Analyze the algorithm, find out what data flows it requires, what data structures should be used, etc. This approach enables you to build the software around the most complex part of it and thus foresee and manage the risks associated with it. This will also help make implementation easier and more optimal.

If an algorithm is in a separate [independent] module, such analysis could be done after the high-level architecture is developed. But still the analysis should be completed before any decisions regarding implementation are made.

Side Note: Pay special attention on choosing the data structures that the algorithm will work with. Data structures can hide some of the complexity inside them thus making the implementation more maintainable.


答:
All algorithmical parts, especially such of higher complexity, should be well encapsulated behind a deliberately designed API. This will dramatically increase decoupling, which is one of the core design principles, IMHO.

Consequently, the algorithm needs to be designed as detailed as necessary, such that this API becomes a clear enough shape to put it into the overall picture and further changes to that API will be minimized.

You want to minimize risk while reducing the initial efforts, which is more or less a tradeoff in which you have to find the optimal balance point. You can't completely eliminate the risk of further API changes in that stage, but you can strive to avert avoidable mistakes and reduce the impact of such changes as much as possible.

Title: In which step of a software development life cycle I should design my computing algorithm?

Body:
In software design, we usually take care of UML diagrams and architecture design.

But in case of a data analysis software, we must pay attention to design algorithms and stuff like that. Consider the case of a face detection software which needs AI. Do we need to design AI part of the software explicitly in software design?

P.S: My manager says that it must set clear in feasibility study and be so clear that we could design it in design steps. Is he correct?


问:
Copyright on own implementation of Standard C Library
I am busy writing a bare-bones Standard C Library for my hobby OS. I am only including the functions I really need for now but the library is still referenced as 'libc' in my source and I plan to expand it to a fully featured C Library. My OS is going to be released as open-source so I would like to know what kind of copyright notice I should put on the source files for my 'C Library' because the coding is mine but it is still based on the source of other C libraries such as GNU C.

I have seen this copyright notice on a C Library implementation for AVR

```<code>00001 /* Copyright (c) 2002, Marek Michalkiewicz
00002    Copyright (c) 2004,2007 Joerg Wunsch
00003
00004    Portions of documentation Copyright (c) 1990, 1991, 1993, 1994
00005    The Regents of the University of California.
00006
00007    All rights reserved.
00008
00009    Redistribution and use in source and binary forms, with or without
00010    modification, are permitted provided that the following conditions are met:
00011
00012    * Redistributions of source code must retain the above copyright
00013      notice, this list of conditions and the following disclaimer.
00014
00015    * Redistributions in binary form must reproduce the above copyright
00016      notice, this list of conditions and the following disclaimer in
00017      the documentation and/or other materials provided with the
00018      distribution.
00019
00020    * Neither the name of the copyright holders nor the names of
00021      contributors may be used to endorse or promote products derived
00022      from this software without specific prior written permission.
00023
00024   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
00025   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
00026   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
00027   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
00028   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
00029   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
00030   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
00031   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
00032   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
00033   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
00034   POSSIBILITY OF SUCH DAMAGE.
00035
00036   $Id: stdlib_8h_source.html,v 1.1.1.4 2012/01/03 16:04:22 joerg_wunsch Exp $
00037 */
</code>```

答:
If you've based your source on the source of glibc in any way (including looking at the glibc source, roughly figuring out how it works, and then writing your own similar code), your library may already count as a derived work. Since glibc is licensed under the GPL with linking exception, that means your code must be under the GPL as well. The copyright should then say something like, "Based on glibc sources. Additional parts (c) ."

Deriving works indirectly from others is a tricky legal issue, and you may want to consult an expert about it. In some companies, engineers aren't allowed to look at GPL code that is remotely related to what they're doing, for fear that they could be "poisoned" by the code and produce derived works. (I remember one engineer who works on a compiler for some big company who watched a talk I gave about Clang - he told me he had to close his eyes when one of my slides contained a bit of Clang source code. And Clang isn't even GPLed.)

On the other hand, to the best of my knowledge such a loose connection has never been tested in a court, and in the case of a clearly defined programming interfaces as the C standard library, the obviousness defense may well apply in a lot of cases. In other words, if you write a simple strcpy:

```<code>char* strcpy(char* dest, const char* src) {
  for (; *src; ++src, ++dest) {
    *dest = *src;
  }
  return dest;
}
</code>```

then it will be hard to say that you copied that from someone else because that is just the simple, obvious way to implement it. But if the code gets more complex - say, it includes SIMD optimizations, then things get more fuzzy.

Body:
If you've based your source on the source of glibc in any way (including looking at the glibc source, roughly figuring out how it works, and then writing your own similar code), your library may already count as a derived work. Since glibc is licensed under the GPL with linking exception, that means your code must be under the GPL as well. The copyright should then say something like, "Based on glibc sources. Additional parts (c) ."

Deriving works indirectly from others is a tricky legal issue, and you may want to consult an expert about it. In some companies, engineers aren't allowed to look at GPL code that is remotely related to what they're doing, for fear that they could be "poisoned" by the code and produce derived works. (I remember one engineer who works on a compiler for some big company who watched a talk I gave about Clang - he told me he had to close his eyes when one of my slides contained a bit of Clang source code. And Clang isn't even GPLed.)

On the other hand, to the best of my knowledge such a loose connection has never been tested in a court, and in the case of a clearly defined programming interfaces as the C standard library, the obviousness defense may well apply in a lot of cases. In other words, if you write a simple strcpy:

char* strcpy(char* dest, const char* src) {
  for (; *src; ++src, ++dest) {
    *dest = *src;
  }
  return dest;
}

then it will be hard to say that you copied that from someone else because that is just the simple, obvious way to implement it. But if the code gets more complex - say, it includes SIMD optimizations, then things get more fuzzy.


问:
Is imperative style programming (say with Java/C) more error prone than something more declarative
I know programmers tend to get defensive with their paradigms and tools that they use.  But in your experience, with the most generic, typical pieces of code that you see with Java or C++ or C, is the code more error prone than a similar piece of code in an declarative or functional programming language.

For example, with Java there can be a lot of boilerplate and setup code need to call your target routine.  Usually developers may need to look at the implementation details to really understand what happens if they do or do not provide the correct dependencies.  Normally the developer never does that so you end up with NullPointerException bugs and other logic errors.

答:
Humans make errors. The more a human has to do, the more errors he makes. Therefore, there are two things a language can do:

Help detect errors early, e.g. through a strong type system. This has been covered by other answers.

Reduce the amount of work the human has to do.

The second point isn't simply about terseness. "Work" the human has to do isn't just the typing of the code. A lot of the work is in mapping from your idea of how something works to a way of expressing that in the code.

As a consequence, the more directly your ideas map to constructs of the programming language, the less translating you have to do, and the fewer errors you introduce in that translation. For example, in a language without higher-order functions, if you have a list of things and you want a list of things that are derived from the original things, you need to translate from the abstract idea "give me a list of derivatives of things in another list" to "create a list; go over the original list; compute the derivative of the current element; add it to the target list" and then translate that into code like

```<code>result = new List();
for each element in source { // what if you don't even have foreach?
  result.add(derive_from(element));
}
</code>```

In a language that has higher-order functions, you can more clearly express your idea, because you only have to translate it to "use the thing that gives me a list with elements corresponding to another list; give it the way to derive a new element", or in code:

```<code>result = map(source, derive_from);
</code>```

The code is succinct, but more importantly, it more directly expresses the intention. There was less mental translation, and thus less room for error.

Body:
Humans make errors. The more a human has to do, the more errors he makes. Therefore, there are two things a language can do:

Help detect errors early, e.g. through a strong type system. This has been covered by other answers.

Reduce the amount of work the human has to do.

The second point isn't simply about terseness. "Work" the human has to do isn't just the typing of the code. A lot of the work is in mapping from your idea of how something works to a way of expressing that in the code.

As a consequence, the more directly your ideas map to constructs of the programming language, the less translating you have to do, and the fewer errors you introduce in that translation. For example, in a language without higher-order functions, if you have a list of things and you want a list of things that are derived from the original things, you need to translate from the abstract idea "give me a list of derivatives of things in another list" to "create a list; go over the original list; compute the derivative of the current element; add it to the target list" and then translate that into code like

result = new List();
for each element in source { // what if you don't even have foreach?
  result.add(derive_from(element));
}

In a language that has higher-order functions, you can more clearly express your idea, because you only have to translate it to "use the thing that gives me a list with elements corresponding to another list; give it the way to derive a new element", or in code:

result = map(source, derive_from);

The code is succinct, but more importantly, it more directly expresses the intention. There was less mental translation, and thus less room for error.


问:
Version number as a part of a file name
I see that some software have the version number included as a part of their file name, while others do not. I am more used to the latter type, and I think that is more popular, but I see the former type sometimes in javascript libraries. For example, jQuery's file name is like jquery-2.1.0.js instead of jquery.js. Whenever I update these types of files, I have to look for the places in other programs that load these files, and change the file name they refer to, and manually delete the older version of these libraries. That is inconvenient to me, so I rather rename the file to exclude the version number, and keep the file name referred to to not include the version number.

I suspect that these numbers are for some kind of version control, but am not clear when and how they are used.

What are the pros and cons for including version numbers in the file name?

Is there de facto consensus on which areas of software or languages use version number in the file name, and which areas/languages do not? If so, is there any rationare for that?

答:
It makes sense to specify the version you require. Behavior you may rely on could have changed, so newer is not always better. First, test whether a new version of a library works for you. Then, update explicitly.

In the case of web resources, having the version be part of the filename is important in the context of caching. For static resources like jquery.js you will want a very long cache time before it's re-fetched. However, during an update you want your code to use the new version immediately, rather than having clients switch over to the new version during the next day or so. As foo-1.2.3.js is a different resource as foo-1.2.4.js, no caches will get in the way.

Title: Version number as a part of a file name


问:
Design for creating a menu based on user type
Problem

I am building a PHP application which has a main menu, which in turn contains various "sections" or "subheadings" with various links. There are several user types such as SuperAdmin, Admin, Teacher, Student, etc, and each type should see a potentially different menu structure. It seems that my client would like to add more types down the line.

Currently I have a huge if/elseif/... block that checks what user type you are and creates an array with arrays for all the sections, containing yet more arrays for each link (these arrays contain the url, class and caption of the url). It's about 700 lines long at the moment. As you can see, this is becoming quite complex and tiresome to get working. So what I've attempted to do is use some design patterns (of which my knowledge is not that amazing).

Failed attempts

Firstly I attempted to create a few Builder implementations: one for the link itsself, one for the "section", and finally one for the menu itself. Then I attempted implementing a Strategy pattern to check current user type, and add links to sections and these sections to the menu. The final attempt was to serialize this menu object to the DB and just read it from there (as some user types can have dynamically configured sections/links)

The real question

I have no clue whether my rationale is even remotely correct in this regard, because I've created and completely deleted all my code about 4 times now as it becomes complex to comprehend just what must go where. So I guess my actual question is this: If you had to build this kind of implementation for menus (or anything where multiple objects are built into another object, and multiple objects of that type are built into yet another object), how would you go about it? What patterns would be useful and how would one structure them to work together without killing your brain?

Thanks!

答:
PHP Dynamic and Recursive Menu System

When building the dynamic menu at my previous job, for our CMS, we had one class that dynamicly builds/prints the menu based on the menu object.

View output example of the code below

Since you're kind of new, I don't suggest making any overkill menu, but try to keep it as simple as possible.

I suggest making a class for the menu, where you send/store the menu array. This way you can make other objects unlock/lock different menu objects, or even send a sub-menu to that menu class (depending on how complex you want to make it).

This allows you to dynamicly build the menu as you run through the system code, and print the menu when your code is finished running. That way you can put the user based menu items in each section of the code, which handles that part.

For example, when running the system, make a function/method that checks the user access and for simple solutions, have hard-coded arrays with menu objects for each user access, or if going hardcore, build the menu arrays dynamicly. That's up to you.

```<code><?php
// Let's create the child menu array for the "Home" menu structure
$home[] = array('TITLE' => 'Home 1',
                'URL' => '/home-1-url-here',
                'CSS_CLASS' => 'sub-menu',
                'CHILDREN' => $home1Child);

$home[] = array('TITLE' => 'Home 2',
                'URL' => '/home-2-url-here',
                'CSS_CLASS' => 'sub-menu');

// Now we create the whole home array, with the children
$homeMenu = array('CSS_CLASS' => 'top-css-class',
                 'TITLE' => 'Home',
                 // If the top menu item is just a link, specify an URL
                 'URL' => '',
                 // Or if it has children pass them on
                 'CHILDREN' => $home);

// Let's create the child menu array for the "Gallery" menu structure
$gallery[] = array('TITLE' => 'Gallery 1',
                'URL' => '/gallery-1-url-here',
                'CSS_CLASS' => 'sub-menu');

$gallery2Child[] = array('TITLE' => 'Gallery 2.1',
                'URL' => '/gallery-2.1-url-here',
                'CSS_CLASS' => 'sub-menu-child');
$gallery2Child[] = array('TITLE' => 'Gallery 2.2',
                'URL' => '/gallery-2.2-url-here',
                'CSS_CLASS' => 'sub-menu-child');

$gallery[] = array('TITLE' => 'Gallery 2',
                'URL' => '/gallery-2-url-here',
                'CSS_CLASS' => 'sub-menu',
                'CHILDREN' => $gallery2Child);

// Now we create the whole gallery array, with the children
$galleryMenu = array('CSS_CLASS' => 'top-css-class',
                 'TITLE' => 'Gallery',
                 // If the top menu item is just a link, specify an URL
                 'URL' => '',
                 // Or if it has children pass them on
                 'CHILDREN' => $gallery);

$menu = new menu;
// Store the menu items we want in the menu
$menu->storeItem($homeMenu);
$menu->storeItem($galleryMenu);
// Print the menu
echo $menu->buildMenu();
</code>```

If you want to make sub-menus aswell, make the menu class work recursively.

```<code>class menu {
   private $mainMenuClass = 'main-menu-class';
   private $parentClass = 'parent-menu-class';
   private $menu;

   public function storeItem($menuItem, $parentClass = '') { // If no $parentClass is specified, pick the default one
      // This stores the menu in an array
      $this->menu[] = $menuItem;
   }

   public function buildMenu() {
      // Let's break down the menu array, and start building it
      $html = '<ul class="'. $this->mainMenuClass .'">'. PHP_EOL;
      foreach($this->menu as $parentClass => $item) {
         $html .= '<li class="'. $item['CSS_CLASS'] .'"><a href="'. $item['URL'] .'">'. $item['TITLE'] .'</a>'. PHP_EOL;
         // Check if it's a recursive sub-menu (with children)
         // Now we send the children array to the buildChildrenItems() method
         $html .= $this->buildChildrenItems($item['CHILDREN']);
         $html .= '</li>'. PHP_EOL;
      }
      $html .= '</ul>'. PHP_EOL;
   return $html;
   }

   public function buildChildrenItems($menuSection) {
      // Put the recursive logics here so we can keep looping
      $html = '<ul class="'. $this->parentClass .'">'. PHP_EOL;
      foreach($menuSection as $item) {
          $html .= '<li class="'. $item['CSS_CLASS'] .'"><a href="'. $item['URL'] .'">'. $item['TITLE'] .'</a>'. PHP_EOL;
          // Now here is where the recursive magic happends
          // If the child item has even more children, call this method once again for those children
          $html .= ( isset($item['CHILDREN']) && is_array($item['CHILDREN']) ) ? $this->buildChildrenItems($item['CHILDREN']) : '';
          $html .= '</li>'. PHP_EOL;
      }
      $html .= '</ul>'. PHP_EOL;
   return $html;
   }
}
</code>```

?>

From here you just design the menu as you want, using the CSS classes.

If you want to make it recursive (with dynamic sub-menus), then simply make the recursive logics before calling the buildChildrenItems() method. This is included in the code example above.

For more complex recursive menus, try these arrays.

```<code>$home1Child[] = array('TITLE' => 'Home 1.1',
                'URL' => '/home-1.1-url-here',
                'CSS_CLASS' => 'sub-menu-child');

$home121Child[] = array('TITLE' => 'Home 1.2.1',
                    'URL' => '/home-1.2.1-url-here',
                    'CSS_CLASS' => 'sub-menu-child');

    $home121Child[] = array('TITLE' => 'Home 1.2.2',
                    'URL' => '/home-1.2.2-url-here',
                    'CSS_CLASS' => 'sub-menu-child');

$home1Child[] = array('TITLE' => 'Home 1.2',
                'URL' => '/home-1.2-url-here',
                'CSS_CLASS' => 'sub-menu-child',
                'CHILDREN' => $home121Child);

$home1Child[] = array('TITLE' => 'Home 1.3',
                'URL' => '/home-1.3-url-here',
                'CSS_CLASS' => 'sub-menu-child');

$home[] = array('TITLE' => 'Home 1',
                'URL' => '/home-1-url-here',
                'CSS_CLASS' => 'sub-menu',
                'CHILDREN' => $home1Child);

$home[] = array('TITLE' => 'Home 2',
                'URL' => '/home-2-url-here',
                'CSS_CLASS' => 'sub-menu');

$home[] = array('TITLE' => 'Home 3',
                'URL' => '/home-3-url-here',
                'CSS_CLASS' => 'sub-menu');

// Now we create the whole home array, with the children

$homeMenu = array('CSS_CLASS' => 'top-css-class',
                 'TITLE' => 'Home',
                 // If the top menu item is just a link, specify an URL
                 'URL' => '',
                 // Or if it has children pass them on
                 'CHILDREN' => $home);

// Let's create the child menu array for the "Gallery" menu structure
$gallery[] = array('TITLE' => 'Gallery 1',
                'URL' => '/gallery-1-url-here',
                'CSS_CLASS' => 'sub-menu');

$gallery2Child[] = array('TITLE' => 'Gallery 2.1',
                'URL' => '/gallery-2.1-url-here',
                'CSS_CLASS' => 'sub-menu-child');
$gallery2Child[] = array('TITLE' => 'Gallery 2.2',
                'URL' => '/gallery-2.2-url-here',
                'CSS_CLASS' => 'sub-menu-child');

$gallery[] = array('TITLE' => 'Gallery 2',
                'URL' => '/gallery-2-url-here',
                'CSS_CLASS' => 'sub-menu',
                'CHILDREN' => $gallery2Child);

// Now we create the whole gallery array, with the children
$galleryMenu = array('CSS_CLASS' => 'top-css-class',
                 'TITLE' => 'Gallery',
                 // If the top menu item is just a link, specify an URL
                 'URL' => '',
                 // Or if it has children pass them on
                 'CHILDREN' => $gallery);
</code>```

View output example of the code above

Finally, in the different classes for example, let's say the Gallery. Create the gallery menu array, check what kind of access the user has, and build it properly. Then you send the gallery menu array to the menu class, as shown above.

This concept is also good for future expansions, so when adding a new class/section on the website, let's say a guestbook. All the menu logics are built in that class and just sent to the dynamic menu class which builds it.

I do not recommend putting all the menu logics inside one big menu file, but as you run the system code, process each section and build the menu object as you go.

Hope this helps you on your way!

PS. If you have alot of user access types, and want to keep a clean code, put the menu arrays for each user access in seperate php files. (user_type_member.php or user_type_admin.php).

In the php code, where the arrays are written, just make a user type check, and call the according php file to load the array for that user.

```<code>switch($userType) {
   default:
   case 'visitor': include('user_type_visitor.php'); break;
   case 'member': include('user_type_member.php'); break;
   case 'admin': include('user_type_admin.php'); break;
}
</code>```

Regards,
Andreas.

Body:
PHP Dynamic and Recursive Menu System

When building the dynamic menu at my previous job, for our CMS, we had one class that dynamicly builds/prints the menu based on the menu object.

View output example of the code below

Since you're kind of new, I don't suggest making any overkill menu, but try to keep it as simple as possible.

I suggest making a class for the menu, where you send/store the menu array. This way you can make other objects unlock/lock different menu objects, or even send a sub-menu to that menu class (depending on how complex you want to make it).

This allows you to dynamicly build the menu as you run through the system code, and print the menu when your code is finished running. That way you can put the user based menu items in each section of the code, which handles that part.

For example, when running the system, make a function/method that checks the user access and for simple solutions, have hard-coded arrays with menu objects for each user access, or if going hardcore, build the menu arrays dynamicly. That's up to you.

<?php
// Let's create the child menu array for the "Home" menu structure
$home[] = array('TITLE' => 'Home 1',
                'URL' => '/home-1-url-here',
                'CSS_CLASS' => 'sub-menu',
                'CHILDREN' => $home1Child);

$home[] = array('TITLE' => 'Home 2',
                'URL' => '/home-2-url-here',
                'CSS_CLASS' => 'sub-menu');

// Now we create the whole home array, with the children
$homeMenu = array('CSS_CLASS' => 'top-css-class',
                 'TITLE' => 'Home',
                 // If the top menu item is just a link, specify an URL
                 'URL' => '',
                 // Or if it has children pass them on
                 'CHILDREN' => $home);

// Let's create the child menu array for the "Gallery" menu structure
$gallery[] = array('TITLE' => 'Gallery 1',
                'URL' => '/gallery-1-url-here',
                'CSS_CLASS' => 'sub-menu');

$gallery2Child[] = array('TITLE' => 'Gallery 2.1',
                'URL' => '/gallery-2.1-url-here',
                'CSS_CLASS' => 'sub-menu-child');
$gallery2Child[] = array('TITLE' => 'Gallery 2.2',
                'URL' => '/gallery-2.2-url-here',
                'CSS_CLASS' => 'sub-menu-child');

$gallery[] = array('TITLE' => 'Gallery 2',
                'URL' => '/gallery-2-url-here',
                'CSS_CLASS' => 'sub-menu',
                'CHILDREN' => $gallery2Child);

// Now we create the whole gallery array, with the children
$galleryMenu = array('CSS_CLASS' => 'top-css-class',
                 'TITLE' => 'Gallery',
                 // If the top menu item is just a link, specify an URL
                 'URL' => '',
                 // Or if it has children pass them on
                 'CHILDREN' => $gallery);

$menu = new menu;
// Store the menu items we want in the menu
$menu->storeItem($homeMenu);
$menu->storeItem($galleryMenu);
// Print the menu
echo $menu->buildMenu();

If you want to make sub-menus aswell, make the menu class work recursively.

class menu {
   private $mainMenuClass = 'main-menu-class';
   private $parentClass = 'parent-menu-class';
   private $menu;

   public function storeItem($menuItem, $parentClass = '') { // If no $parentClass is specified, pick the default one
      // This stores the menu in an array
      $this->menu[] = $menuItem;
   }

   public function buildMenu() {
      // Let's break down the menu array, and start building it
      $html = '<ul class="'. $this->mainMenuClass .'">'. PHP_EOL;
      foreach($this->menu as $parentClass => $item) {
         $html .= '<li class="'. $item['CSS_CLASS'] .'"><a href="'. $item['URL'] .'">'. $item['TITLE'] .'</a>'. PHP_EOL;
         // Check if it's a recursive sub-menu (with children)
         // Now we send the children array to the buildChildrenItems() method
         $html .= $this->buildChildrenItems($item['CHILDREN']);
         $html .= '</li>'. PHP_EOL;
      }
      $html .= '</ul>'. PHP_EOL;
   return $html;
   }

   public function buildChildrenItems($menuSection) {
      // Put the recursive logics here so we can keep looping
      $html = '<ul class="'. $this->parentClass .'">'. PHP_EOL;
      foreach($menuSection as $item) {
          $html .= '<li class="'. $item['CSS_CLASS'] .'"><a href="'. $item['URL'] .'">'. $item['TITLE'] .'</a>'. PHP_EOL;
          // Now here is where the recursive magic happends
          // If the child item has even more children, call this method once again for those children
          $html .= ( isset($item['CHILDREN']) && is_array($item['CHILDREN']) ) ? $this->buildChildrenItems($item['CHILDREN']) : '';
          $html .= '</li>'. PHP_EOL;
      }
      $html .= '</ul>'. PHP_EOL;
   return $html;
   }
}

?>

From here you just design the menu as you want, using the CSS classes.

If you want to make it recursive (with dynamic sub-menus), then simply make the recursive logics before calling the buildChildrenItems() method. This is included in the code example above.

For more complex recursive menus, try these arrays.

$home1Child[] = array('TITLE' => 'Home 1.1',
                'URL' => '/home-1.1-url-here',
                'CSS_CLASS' => 'sub-menu-child');

$home121Child[] = array('TITLE' => 'Home 1.2.1',
                    'URL' => '/home-1.2.1-url-here',
                    'CSS_CLASS' => 'sub-menu-child');

    $home121Child[] = array('TITLE' => 'Home 1.2.2',
                    'URL' => '/home-1.2.2-url-here',
                    'CSS_CLASS' => 'sub-menu-child');

$home1Child[] = array('TITLE' => 'Home 1.2',
                'URL' => '/home-1.2-url-here',
                'CSS_CLASS' => 'sub-menu-child',
                'CHILDREN' => $home121Child);

$home1Child[] = array('TITLE' => 'Home 1.3',
                'URL' => '/home-1.3-url-here',
                'CSS_CLASS' => 'sub-menu-child');

$home[] = array('TITLE' => 'Home 1',
                'URL' => '/home-1-url-here',
                'CSS_CLASS' => 'sub-menu',
                'CHILDREN' => $home1Child);

$home[] = array('TITLE' => 'Home 2',
                'URL' => '/home-2-url-here',
                'CSS_CLASS' => 'sub-menu');

$home[] = array('TITLE' => 'Home 3',
                'URL' => '/home-3-url-here',
                'CSS_CLASS' => 'sub-menu');

// Now we create the whole home array, with the children

$homeMenu = array('CSS_CLASS' => 'top-css-class',
                 'TITLE' => 'Home',
                 // If the top menu item is just a link, specify an URL
                 'URL' => '',
                 // Or if it has children pass them on
                 'CHILDREN' => $home);

// Let's create the child menu array for the "Gallery" menu structure
$gallery[] = array('TITLE' => 'Gallery 1',
                'URL' => '/gallery-1-url-here',
                'CSS_CLASS' => 'sub-menu');

$gallery2Child[] = array('TITLE' => 'Gallery 2.1',
                'URL' => '/gallery-2.1-url-here',
                'CSS_CLASS' => 'sub-menu-child');
$gallery2Child[] = array('TITLE' => 'Gallery 2.2',
                'URL' => '/gallery-2.2-url-here',
                'CSS_CLASS' => 'sub-menu-child');

$gallery[] = array('TITLE' => 'Gallery 2',
                'URL' => '/gallery-2-url-here',
                'CSS_CLASS' => 'sub-menu',
                'CHILDREN' => $gallery2Child);

// Now we create the whole gallery array, with the children
$galleryMenu = array('CSS_CLASS' => 'top-css-class',
                 'TITLE' => 'Gallery',
                 // If the top menu item is just a link, specify an URL
                 'URL' => '',
                 // Or if it has children pass them on
                 'CHILDREN' => $gallery);

View output example of the code above

Finally, in the different classes for example, let's say the Gallery. Create the gallery menu array, check what kind of access the user has, and build it properly. Then you send the gallery menu array to the menu class, as shown above.

This concept is also good for future expansions, so when adding a new class/section on the website, let's say a guestbook. All the menu logics are built in that class and just sent to the dynamic menu class which builds it.

I do not recommend putting all the menu logics inside one big menu file, but as you run the system code, process each section and build the menu object as you go.

Hope this helps you on your way!

PS. If you have alot of user access types, and want to keep a clean code, put the menu arrays for each user access in seperate php files. (user_type_member.php or user_type_admin.php).

In the php code, where the arrays are written, just make a user type check, and call the according php file to load the array for that user.

switch($userType) {
   default:
   case 'visitor': include('user_type_visitor.php'); break;
   case 'member': include('user_type_member.php'); break;
   case 'admin': include('user_type_admin.php'); break;
}

Regards,
Andreas.


问:
What should be the "depth of design"?
We all know that the process of creating a design and the whole architecture of the software is very important before writing the code. But how deep should be dive into the design stuff - should we start from the general architecture and go down til the names of the classes or should be just designate common parts and start coding?</p>

答:
I would like to echo S.Lott's sentiment of "code is design" and JohnFx's advice of "design as little as possible before you start coding", but expound on why. The reason is simple - writing code is a process of discovery.

You can build castles in the air all you want, but there are things you'll only discover once you actually write the code. You'll bump into code duplication that you were simply never going to see when you were making a bunch of UML diagrams because the implementation just isn't there. You might realize a component needs to be broken up into two or more parts when you try to write unit tests for it. Moreover, you're chasing a moving target - even if you had the clairvoyance to think up the perfect design up front, it'll no longer be perfect once the requirements change.

The best advice I can give you is to follow the core idea behind agile methodologies: take a small step towards your goal, take a good look at the result, and use your newly-found insight to fix mistakes and correct your course. Keep doing that until you're done. And don't forget to Keep It Simple, Stupid!

Title: What should be the "depth of design"?


问:
Design questions for a Node.JS based Dashboard
I checked with meta and apparently this is the best place to ask!

The company I work at have many environments, and as such, many Nagios/Icinga etc boxes in each environment. We currently have a dashboard, but it was created quickly many moons ago and needs replacing. It currently scrapes the HTML of every box, builds a static HTML file and repeats.

I put together a proof of concept using PHP/MySQL (as I'm good at it) which has a page which is dynamically generated from a MySQL DB, and then there's a background script which fetches data from Nagios/Icinga API's (or resorts to scraping where no API present). This works fine, but I've been itching to learn Node.JS and from what I've read it's good for dashboards - especially as I may want interaction in future.

So, my question is where abouts in this does Node.JS site, and where abouts does it not sit? For example, should I be using Node.JS for the dashboard itself sat on something like MongoDB (never used it, but would like to try NoSQL for once) to show people the current problems etc and then I have a script in the background in PHP/Perl that does the fetching scraping? Or (option 2) does Node do the dashboard AND the fetching of data? Do I have two instances of Node? I'd also like to have a web-based config page (like an admin settings page) rather than flat file settings - again, is this something easily done in the same Node structure or is Node quite single purpose (just display a dashboard, just fetch, just do forms etc)

I could accomplish all of the above with PHP/MySQL fairly easily and quickly, but Node.JS and MongoDB seem really popular nowadays and I feel like I'm missing out.

答: I don't see why you should mix php and node. Both are server side platforms. If you want to be fast, do it with php. If you want to discover a new platform, do it with node. Both tech fill almost the same space in a web app stack.</p>


问:
Documentation required for commissioned software (product)
The company I work for has commissioned a software company to produce a compliance software for several big companies. As part of our contract it is required of them to provide us with src code and documentation in case in the future we want to take over and further develop the project in house or have another company take over.

What are the best practices for software documentation in this case? I.e. What shall I ask of them to provide us for if a 3rd company in the future were to take over?

Right now they just provided us the src code and a auto-generated class document (not even class diagram, just a list of all classes, parameters etc).

I hope someone can point me in the right direction so that I can produce a small document with what our requirements are.

答:
Your vendor is likely to produce the minimum required to fit your definition of documentation.

You will need to spend some time thinking about what kind of documentation you want, and possibly provide them with templates, a wiki, etc. that you want them to use if you don't want to get junk when you are done, and you want it to be easy to update as things change.

What are you likely to need? I think of documents that are accessible to different kinds of people, at different kinds of decision making levels. As ratchet freak said, there is lots of auto generated junk that adds zero value, and you rarely get good information at the very detailed level. Besides, software developers are generally good with the details.  You need good documentation for communicating with stakeholders and management.

I think you will want things that explain at different levels of detail.  Using the airplane altitude analogy, an example (vary the altitudes for your organization. Since you say that your commissioned software will be used by several companies, you may need more levels):

The 30,000 m view for decision makers at a very high level, for when big changes are needed. (i.e. how this software integrates with existing systems, interfaces, and the major components) You may need more than one of these, if you have disparate existing systems, so negotiation can be done among the several companies you are talking about. Above all, this needs to be brief and clear, with diagrams, and in natural language that a NON-TECHNICAL person can understand.

The 15,000 m view for project teams that might be tasked by the decision makers.  You will want this to include the specific differences in the software for the several companies you discuss in the top.  There are ALWAYS one-off situations to get from a theoretical design to getting stuff to work.  Depending on where the one-off stuff is done (by individual companies, or by this development group), this may get messy.  Again, brevity, non-technical language, and diagrams are most useful. It shouldn't matter what language the code is written in, etc. for people to understand this documentation.  You want it as a negotiation tool with the user companies, and with the development team.

The 5,000 m view of major code components and how they fit together.  Here is the first place where technical language may start to be useful.  This is for project teams who have to specify changes, and determine what major chunks of work need to be done.  Here is where the developers, designers, and start the back and forth of how things will get done, what parts of the software will need to be changed, etc.

This is what I would want. I'm a developer/integrator in a large multi-site organization. I am often in conference calls with non-technical people who don't care about details, and are trying to understand jargon of IT folks who love the details.  You need docs that will communicate the space between big picture and detail, so that you can get everyone in the same place during discussions.


答:
"Acceptance tests for the whole project, which performs through the user interface" are not scriptable. You cannot automate them and do continous integration.

That's why you have to have unist tests anyway.

Also most times, "acceptance tests" don't test limit cases, exceptions etc.


问:
About protection for important actions on the server
We developing a web service. And need our important actions (i.e. money transfer) to be protected from accidental calling. In frontend we asking user to confirm such actions. Ok.

But how to prevent accidental calling in case of developer mistake?

Is it good idea, that action require some confirmation token from developer to proceed?

答:
A web service shouldn't force UI decisions on a consuming application (any more than it has to). Confirmation of user actions is a UI decision.

Plus, you're not really enforcing anything by forcing a confirmation step. If the consuming-application developer wishes, they can simply auto-confirm. All you're doing is making it harder to consume, either way.

If you, as an API provider, want to enforce a UI decision on an API consumer, that is fair enough. But it should be done via a combination of terms and conditions, a consumer-kill switch and a prior verification step (ie. we won't approve your production API access until we've seen the application).


答: If you really feel confirmation is necessary, you can make your critical services require a time-stamped token, and require the caller to obtain a token from you immediately prior to invoking the service. Have the token expire withing a couple of seconds (actual TTL should be determined after measuring latency). I agree with pdr, though, it's not a good design pattern.</p>

Title: About protection for important actions on the server

Body:
We developing a web service. And need our important actions (i.e. money transfer) to be protected from accidental calling. In frontend we asking user to confirm such actions. Ok.

But how to prevent accidental calling in case of developer mistake?

Is it good idea, that action require some confirmation token from developer to proceed?


问:
Why sequential cohesion for operations in a method is not a good idea?
I read from the seminal  Code Complete book that method statements that require to be executed in order passing parameter from one to the next is a code smell and is an example of a sequential cohesion. Why is this not a good idea?

A contrived example of a sequential cohesion:

```<code>public Part createPart(input) {
        PartOne partOne = computePartOne(input);
        PartTwo partTwo = computePartTwo(partOne);
        PartThree partThree = computePartThree(partTwo);
        PartsBuilder partsBuilder = new PartsBuilder();
        return partsBuilder.add(partOne).add(partTwo).add(partThree).build();
    }
</code>```

Here is the exert:

Several other kinds of cohesion are normally considered to be less than ideal:

Sequential cohesion exists when a routine contains operations that
  must be performed in a specific order, that share data from step to
  step, and that don't make up a complete function when done together.

An example of sequential cohesion is a routine that, given a birth
  date, calculates an employee's age and time to retirement. If the
  routine calculates the age and then uses that result to calculate the
  employee's time to retirement, it has sequential cohesion. If the
  routine calculates the age and then calculates the time to retirement
  in a completely separate computation that happens to use the same
  birth-date data, it has only communicational cohesion.

How would you make the routine functionally cohesive? You'd create
  separate routines to compute an employee's age given a birth date and
  compute time to retirement given a birth date. The time-to-retirement
  routine could call the age routine. They'd both have functional
  cohesion. Other routines could call either routine or both routines.

答:
I think a big part of this problem was the choice of words. "Less than ideal" does not necessarily imply bad code. If you look into Ed Yourdon and Larry Constantine's original book Structured Design, you will see that the authors attribute a subjective scale to the different levels of cohesiveness:

0 - coincidental

1 - logical

3 - temporal

5 - procedural

7 - communicational

9 - sequential

10 - functional

Note that the scale is not linear, and sequential (9) is very close to functional (10). The authors also state that "the highest three suggest simple and inexpensive designs".

As you see, this doesn't support the claim that the code in your example "is not a good idea".


答: I'd suggest writing a MenuFactory that takes a list of users/roles/permissions which in turn invokes any required builders to create the actual menu structure. This way the menu building is encapsulated, and the interface through the factory should be flexible enough to handle adding or removing users/roles in the future.

Title: Design for creating a menu based on user type

Body:
Problem

I am building a PHP application which has a main menu, which in turn contains various "sections" or "subheadings" with various links. There are several user types such as SuperAdmin, Admin, Teacher, Student, etc, and each type should see a potentially different menu structure. It seems that my client would like to add more types down the line.

Currently I have a huge if/elseif/... block that checks what user type you are and creates an array with arrays for all the sections, containing yet more arrays for each link (these arrays contain the url, class and caption of the url). It's about 700 lines long at the moment. As you can see, this is becoming quite complex and tiresome to get working. So what I've attempted to do is use some design patterns (of which my knowledge is not that amazing).

Failed attempts

Firstly I attempted to create a few Builder implementations: one for the link itsself, one for the "section", and finally one for the menu itself. Then I attempted implementing a Strategy pattern to check current user type, and add links to sections and these sections to the menu. The final attempt was to serialize this menu object to the DB and just read it from there (as some user types can have dynamically configured sections/links)

The real question

I have no clue whether my rationale is even remotely correct in this regard, because I've created and completely deleted all my code about 4 times now as it becomes complex to comprehend just what must go where. So I guess my actual question is this: If you had to build this kind of implementation for menus (or anything where multiple objects are built into another object, and multiple objects of that type are built into yet another object), how would you go about it? What patterns would be useful and how would one structure them to work together without killing your brain?

Thanks!


问:
When to pay for C++ compilers
Recently I have began to wonder when developers should pay for compilers. Compilers come for free with most platforms or there is a free version easily obtainable.

Example:

OS X - GCC and Clang/LLVM come with the developer tools. No limitations here for how and what you can turn out with them.

Linux - GCC and I am sure more. I dont know the current state of linux compilers. No limitations here for how and what you can turn out with them.

Windows - MinGW and Microsoft does offer a free version of Visual Studio. No limitations with MinGW but I think with the free Visual Studio there are severe limitations.

However, as an example, Intel produces C/C++ compilers. They are hefty in price. Educationally I think that one can get the OS X version for $49 and Windows/Linux for $129 each. They then offer a complete "Studio" product too. Obviously using the educational pricing there are imposed limitations.

But what I am wondering is when should one really considering paying for compilers. One example I can think of is a video game. If you are using a compiler that works on the major platforms there would be no more switching tools for the platform. It seems there would be a level of ease in switching among platforms if the tools were the same.

Can anyone shed some light on paying for compilers like the Intel compilers and the true cross-platform benefits one might get from using them? Does one's code become less portable even trying very hard to not do platform specific techniques?

答: Sometimes it's not the compiler people pay for, it's the runtime that works with it.  Intel in particular has a tradition of providing excellent libraries for things like multithreading, media support (SSE etc) and extended-precision math.</p>

Title: When to pay for C++ compilers


答:
(Excluding the situation of web caching mentioned by @amon): I assume you make a local copy of a third-party library for your program's use, otherwise the need for a version number would be obvious.  The usage scenario of such a third party library within the software system you are developing may be one of these two:

all of the parts of your program which are using the lib shall always share the same version of the lib (ideally "the newest"), and you are going to update the lib from time to time. Then keeping the version number as part of the file name can be really tedious, and I actually would recommend to strip the number from your local copy of the file if possible. Notice that this is only a good a idea if you have confidence that the third party vendor keeps the lib mostly downward-compatible to earlier versions.

you expect to have some parts of your program which need version A, and some others which need version B. Then you will obviously need a version number for the third party lib. Note that this situation can also occur when you cannot easily test all of your software parts using the lib at once after introducing a new version.

And if you are a library vendor yourself, you should include the version number by default, but let the user of that lib decide for himself if he keeps that number or strips it away.

Title: Version number as a part of a file name

Body:
I see that some software have the version number included as a part of their file name, while others do not. I am more used to the latter type, and I think that is more popular, but I see the former type sometimes in javascript libraries. For example, jQuery's file name is like jquery-2.1.0.js instead of jquery.js. Whenever I update these types of files, I have to look for the places in other programs that load these files, and change the file name they refer to, and manually delete the older version of these libraries. That is inconvenient to me, so I rather rename the file to exclude the version number, and keep the file name referred to to not include the version number.

I suspect that these numbers are for some kind of version control, but am not clear when and how they are used.

What are the pros and cons for including version numbers in the file name?

Is there de facto consensus on which areas of software or languages use version number in the file name, and which areas/languages do not? If so, is there any rationare for that?


问:
How do I stop designing and start architecting this project as suggested by my lead?
I'm a junior developer (~3 years' exp.) and at my job we're in the process of architecting a new system. My lead developer will be the principal architect, however he's challenged me to try architecting the system myself (in parallel).

Over the course of a few iterations of brainstorming ideas and proposing what I saw as architecture suggestions, my lead has given me the feedback that most of what I've been doing was "designing" and not "architecting".

He described the difference as architecture being implementation-agnostic whereas a design is the description of an implementation. He said I need to take off my designer hat and put on my architect hat. He gave me a little bit of advice on how to do so, but I would like to ask you as well:

How do I get out of software designer mode and start thinking more like an architect?

Here are some examples of "designs" I came up with that weren't seen as relevant to the architecture by my lead:

I came up with an algorithm for loading and unloading resources from our system and my lead said that algorithms are categorically not architecture.

I came up with a set of events the system should be raising and in what order it should raise them, but this too didn't seem to cut it as architecture.

I seem to be getting caught up in the details and not stepping back far enough. I find that even when I come up with something that is at an architecture level, I often got there by trying out various implementations and mucking around in the details then generalizing and abstracting. When I described this to my lead, he said that I was taking the wrong approach: I needed to be thinking "top down" and not "bottom up".

Here are some more specific details about the project:

The project we're architecting is a web application.

I'm estimating around 10-100 thousand lines of code.

We're a start up. Our engineering team is about 3-5 people.

The closest thing I could compare our application to is a lightweight CMS. It has similar complexity and deals largely with component loading and unloading, layout management, and plug-in style modules.

The application is ajax-y. The user downloads the client once then requests data as it needs it from the server.

We will be using the MVC pattern.

The application will have authentication.

We aren't very concerned about old browser support (whew!), so we're looking to leverage the latest and greatest that is out there and will be coming out. (HTML5, CSS3, WebGL?, Media Source Extensions, and more!)

Here are some goals of the project:

The application needs to scale. In the near term our users will be on the order of hundreds to thousands, but we're planning for tens of thousands to millions and beyond.

We hope the application will be around forever. This isn't a temporary solution. (Actually we already have a temporary solution, and what we're architecting is the long-term replacement for what we have).

The application should be secure as it may have contact with sensitive personal information.

The application needs to be stable. (Ideally, it'd be stable around the level of gmail but it doesn't need to be at the extreme of a Mars rover.)

答:
If I can add anything here, it's that: don't think code. At all.

Don't think how you will write the code to accomplish something, but think about what the best method would be for accomplishing it. Your description of what you need to do should be language-agnostic, so you will be talking design patterns - which are a common "language" between users of different programming languages - to discuss how to proceed forward.

For your specific use-case, more architectural questions in my opinion would be along the lines of:

Why are you using MVC? Is it all you know of? Are there better patterns to use? Why?

What framework will you be using, and why?

How will you scale? Not code-wise, because that doesn't matter yet. What will the conditions be to scale horizontally; what  service (AWS) will you use to do this?

How is the authentication going to be performed? Not code-wise: are you going to be generating a random, unique token on each request and having it checked against the expected token? Don't think how you will do this in code. Think about why you are doing this - because this can be done in practically any web language.

Basically, don't talk at all about code. Even if you don't know how to do something, when there is a will, there is a way. Think more about how the pieces of the puzzle will fit together best, before you worry about actually putting them together.


答:
The cohesion hierarchy is very useful but you are straining at gnats in this instance. There are useful, if subtle distinctions, to be made at the high end of the spectrum. However, those distinctions do not amount to a "smell". When you get to the lower end, you can talk about smell (and even stench, in the worst cases).

The example is contrived. We could modify the example slightly by, for instance, making the age calculation process non-linear, with a set of interval calculations that require reading a database table. Therefore, from a functionality point of view, the age calculation is cohesive, and, by extension, the retirement calculation that depends on a correct age calculation are also functional.

There is still a sequential dependency between the two calculations -- the age MUST be calculated before the retirement date. Hence, one calculation must occur before the other, regardless if they are called from the same function or not. When ordering of function calls must be imposed, something must bear the responsibility for sequencing the calls.

In conclusion. No code smell. Just something that might be improved for very little benefit.

Title: Why sequential cohesion for operations in a method is not a good idea?

Body:
I read from the seminal  Code Complete book that method statements that require to be executed in order passing parameter from one to the next is a code smell and is an example of a sequential cohesion. Why is this not a good idea?

A contrived example of a sequential cohesion:

```<code>public Part createPart(input) {
        PartOne partOne = computePartOne(input);
        PartTwo partTwo = computePartTwo(partOne);
        PartThree partThree = computePartThree(partTwo);
        PartsBuilder partsBuilder = new PartsBuilder();
        return partsBuilder.add(partOne).add(partTwo).add(partThree).build();
    }
</code>```

Here is the exert:

Several other kinds of cohesion are normally considered to be less than ideal:

Sequential cohesion exists when a routine contains operations that
  must be performed in a specific order, that share data from step to
  step, and that don't make up a complete function when done together.

An example of sequential cohesion is a routine that, given a birth
  date, calculates an employee's age and time to retirement. If the
  routine calculates the age and then uses that result to calculate the
  employee's time to retirement, it has sequential cohesion. If the
  routine calculates the age and then calculates the time to retirement
  in a completely separate computation that happens to use the same
  birth-date data, it has only communicational cohesion.

How would you make the routine functionally cohesive? You'd create
  separate routines to compute an employee's age given a birth date and
  compute time to retirement given a birth date. The time-to-retirement
  routine could call the age routine. They'd both have functional
  cohesion. Other routines could call either routine or both routines.