问:
Optimizing code by using registers, but what if they are not enough in number?
One way to optimize code is to minimize the access to arrays and use variables instead, because that way we use registers instead of loading data to cache memory.

For example, if in a loop I'm going to use 3 times a data from an array, say radius[i], I'd better declare a variable tmp, and give it the value of radius[i]. Every time I need to call radius[i] I'll use tmp instead.

The problem is, the number of registers is limited (to 8 in some cases, it depends on the architecture).

What if I have more variables than the number of registers? Will the usage of variables in this case slow down my program more than having access to cache memory?

I am coding in c language.

答:
Having more variables than registers isn't necessarily a problem. If a variable's value isn't used after a certain point in the function, the compiler can use that register for another variable. Even when there's more variables in use at a certain point than there are registers, the compiler will probably do a better job of figuring out the order in which they need to be moved in and out of registers than you.

The point of a high level language is to abstract away those details. I know if you program in C you're probably concerned about performance, but C is also an unsafe language, which means a mistake will take execution off the rails and result in undefined behavior. Write code that is simple and easy to follow. Forget about that kind of micro-optimization unless you have a clear performance goal, you've profiled the application, confirmed you're not reaching that goal, and you've identified the specific part of the code that needs optimizing. And in that case, there is no definitive answer we can give you - you'll have to try different variations of the code, profile, and see which one ends up being faster on your particular combination of compiler, OS, and architecture.


问:
As a sole developer (for now), how should I be using Git?
I have multiple projects on Git that I eventually want to bring others into. However, right now it's just me and I use Git and GitHub very simplistically: no branches and basically just using the commits as a backup to my local files. Sometimes I'll go back and look at previous versions of my files for reference, but I haven't needed to do any rollbacks to this point, though I appreciate the option should I need it in the future.

As a sole developer, what Git or GitHub features could I take advantage of that would benefit me right now? What should my workflow be like?

Also, are there any particular practices that I need to start doing in anticipation of adding others to my projects in the future?

答:
For a simpler model, you can look at what GitHub does. "GitHub flow" is very simple, and there's an excellent guide here:
https://guides.github.com/introduction/flow/index.html

Summary (from Scott Chacon's blog):

So, what is GitHub Flow?

Anything in the master branch is deployable

To work on something new, create a descriptively named branch off of master (ie: new-oauth2-scopes)

Commit to that branch locally and regularly push your work to the same named branch on the server

When you need feedback or help, or you think the branch is ready for merging, open a pull request

After someone else has reviewed and signed off on the feature, you can merge it into master

Once it is merged and pushed to ‘master’, you can and should deploy immediately

ContentLicense: CC BY-SA 3.0


答:
This is called register allocation, and the compiler/optimiser will take care of it for you. Just make sure to turn optimisation on. If you want to see what it does, just compile to assembler ... and then learn to read and understand assembler. The quality of implementation will vary, but in general you don't need to think about this unless you have a specific performance problem.

The only time it might be worth thinking about this up-front, is when you know an array can't be aliased, but it will be hard for the compiler to prove this. Eg,

```<code>double radius[3];
double *possible_alias = get_ptr();
...
for (int i=0; i<3; ++i) {
    *possible_alias *= radius[i];
    do_something_else(radius[i]);
}
</code>```

if you know the pointer assignment won't change radius[i], but the compiler may be unable to rely on it, you could write

```<code>    double r = radius[i];
    *possible_alias *= r;
    do_something_else(r);
</code>```

In general, don't worry about this sort of micro optimisation unless you find a specific performance problem. Reserve your efforts for writing code that's clear, easy to debug and understand, and choosing the right data structures and algorithms.

As for how to profile your code, that's a massive topic, and the support depends on your platform and toolchain. There are compiled-in sampling profilers (like gprof, for the GCC toolchain), post-hoc profilers (like Intel's VTune and the free valgrind), or you can just time whole runs or write your own timing points manually. None of this is likely to be worth the effort unless your program is objectively too slow in the first place.

Note to OP: the discussion in comments below is about the situations in which the CPU may be able to optimise this at run time, even if the compiler couldn't. At least on modern x86 platforms, it just reduces even further the value of thinking about this.

Title: Optimizing code by using registers, but what if they are not enough in number?

Body:
One way to optimize code is to minimize the access to arrays and use variables instead, because that way we use registers instead of loading data to cache memory.

For example, if in a loop I'm going to use 3 times a data from an array, say radius[i], I'd better declare a variable tmp, and give it the value of radius[i]. Every time I need to call radius[i] I'll use tmp instead.

The problem is, the number of registers is limited (to 8 in some cases, it depends on the architecture).

What if I have more variables than the number of registers? Will the usage of variables in this case slow down my program more than having access to cache memory?

I am coding in c language.

Body:
This is called register allocation, and the compiler/optimiser will take care of it for you. Just make sure to turn optimisation on. If you want to see what it does, just compile to assembler ... and then learn to read and understand assembler. The quality of implementation will vary, but in general you don't need to think about this unless you have a specific performance problem.

The only time it might be worth thinking about this up-front, is when you know an array can't be aliased, but it will be hard for the compiler to prove this. Eg,

double radius[3];
double *possible_alias = get_ptr();
...
for (int i=0; i<3; ++i) {
    *possible_alias *= radius[i];
    do_something_else(radius[i]);
}

if you know the pointer assignment won't change radius[i], but the compiler may be unable to rely on it, you could write

    double r = radius[i];
    *possible_alias *= r;
    do_something_else(r);

In general, don't worry about this sort of micro optimisation unless you find a specific performance problem. Reserve your efforts for writing code that's clear, easy to debug and understand, and choosing the right data structures and algorithms.

As for how to profile your code, that's a massive topic, and the support depends on your platform and toolchain. There are compiled-in sampling profilers (like gprof, for the GCC toolchain), post-hoc profilers (like Intel's VTune and the free valgrind), or you can just time whole runs or write your own timing points manually. None of this is likely to be worth the effort unless your program is objectively too slow in the first place.

Note to OP: the discussion in comments below is about the situations in which the CPU may be able to optimise this at run time, even if the compiler couldn't. At least on modern x86 platforms, it just reduces even further the value of thinking about this.


问:
Is recursion an instance of being "too clever" when programming?
I've read several books and learned through experience that optimizing code to the point where it is inscrutable, or coming up with an extremely fast but extremely complex solution to a problem is not desirable when working in teams, or even when you're working by yourself and have to understand your clever solution some time later.

My question is, should recursion be treated in the same manner?  Does the average programmer understand recursion easily and thus one should use it with impunity, or does the average programmer not understand recursion very well and one should stay away from it for the sake of overall team productivity?

I know there are simple answers of, "Any programmer who doesn't understand recursion isn't worth a grain of salt, so don't worry about them" but I was wondering if you all had some real world experience you would like to share that would illuminate the issue more than the opinion I just mentioned.

答: I understand it but I have never explicitly used it.  I think anyone that calls themselves a programmer should know or learn what it is as much as they need to know what the stack and heap are.  Hey, everyone needs to know how min/max works on tic-tac-toe, via fancy recursion.</p>

ContentLicense: CC BY-SA 2.5


问:
Why are deadlines always so short?
I'm a junior developer in a small company (in a team of 2 developers). Everytime we are asked to implement a new feature:

the deadline is set so that we just have time to do the development: there is no error margin (if something takes a little bit more time than expected, we are late) ; almost no time for tests (we are pretty sure there will be bugs) ; no time to refactor anything

we are asked to start the development before the features are completely specified, so new things to do show up but the deadline stays as it is

The result is that we deliver software that has bugs and the technical debt keeps growing. We use technology that was considered as a recent version in 2006 or so.

There was one release that I remember very well. When we did a demonstration to the boss, he told us "What!?? You took two weeks to produce that?!" and all we could answer was "No, in fact it took us three weeks". I had a meeting with him and another junior developer (that quit the company because of this said meeting!), and he basically told us that he was not happy because what we released was crap.

The technical debt and the need to refactor were so big in the parts that we had to modify (but we were told not to refactor because we have no time) that:

we had to add a layer of bad code on top of the already bad code;

we took much time to try and understand completely incomprehensible code.

I don't feel like I'm responsible for this bad release, I think that it's the boss' responsibility to hire good developers that, at least, understand the basic principles of OOP. But hiring juniors is so much less expensive...

He is already saying that we are late for the development I'm working on at the moment. He spent more than one year to "redesign" a tool that was already present in our application, but now he wants us to implement it in two weeks. I personally think that if we want to do it correctly, we need at least one month, or maybe even 6 weeks.

I don't know what to do, because I think that the boss thinks that we are just slow and ineffective. That's not the way I will get the raise I think I deserve.

Why is it like that? That doesn't seem so hard to understand that if I need x days to complete a task, I can't do it in x/2 days, even if you say "please" and ask with a smile. That seems so obvious that the deadline will be missed and/or that the quality requirements won't be met.

I don't need to know how I can explain to my boss that software development is a longer process that just clicking an icon. Because I hope he already knows that.

答:
Your team clearly suffers from Overly optimistic schedules :

The challenges faced by someone building a three-month application are quite different than the challenges faced by someone building a one-year application. Setting an overly optimistic schedule sets a project up for failure by underscoping the project, undermining effective planning, and abbreviating critical upstream development activities such as requirements analysis and design. It also puts excessive pressure on developers, which hurts developer morale and productivity.

If you are really working hard, then it is the problem of the management.

is it always like that? Are the deadlines always short?

My experience is : yes, they usually are. But if the plan is too optimistic, then it is doomed for failure.

is there something I can do about it?

Nowhere you said that you are involved in the schedule planning, which is really weird. I guess, this is so, because you are still a junior developer. Even then, they should ask you.

The only reasonable answer is to plan properly. How long will design, development, and refactoring take? Give best, most likely and worse estimates, and present them to your manager. What is important is not to back up from your estimates, and not allow negotiations about them (see this).

Title: Why are deadlines always so short?


答:
When we submit a man-year estimate, that number is determined by a gut-feeling based on experience, on guessing at the risks of new tools, new problems, etc. Normally we get it about right, but we can't justify this. In the old days, when man-years grew on trees, our bosses, who were ex-softies themselves, trusted us, we got those hours given and off we went.

Since then two things happened; budgets got slashed and management courses were invented as a cheap substitute for engineering.

So now we have bosses who are under immense pressure to cut costs, because the competition has cut costs too, and these very people have little or no technical background. So if you say 5 man-years, he will say, well, I'll give you 4, because that works for him when he gets a plumber in. Now good, we know that cheap and hasty plumbing means leaks in the future, but by then he will have moved house, or in the manager's case gone off to a better-paid job in another branch.

But it's not always that bad. You have an extreme case, and that firm is going to go belly up sometime, so think seriously about finding a new job.

Title: Why are deadlines always so short?

Body:
I'm a junior developer in a small company (in a team of 2 developers). Everytime we are asked to implement a new feature:

the deadline is set so that we just have time to do the development: there is no error margin (if something takes a little bit more time than expected, we are late) ; almost no time for tests (we are pretty sure there will be bugs) ; no time to refactor anything

we are asked to start the development before the features are completely specified, so new things to do show up but the deadline stays as it is

The result is that we deliver software that has bugs and the technical debt keeps growing. We use technology that was considered as a recent version in 2006 or so.

There was one release that I remember very well. When we did a demonstration to the boss, he told us "What!?? You took two weeks to produce that?!" and all we could answer was "No, in fact it took us three weeks". I had a meeting with him and another junior developer (that quit the company because of this said meeting!), and he basically told us that he was not happy because what we released was crap.

The technical debt and the need to refactor were so big in the parts that we had to modify (but we were told not to refactor because we have no time) that:

we had to add a layer of bad code on top of the already bad code;

we took much time to try and understand completely incomprehensible code.

I don't feel like I'm responsible for this bad release, I think that it's the boss' responsibility to hire good developers that, at least, understand the basic principles of OOP. But hiring juniors is so much less expensive...

He is already saying that we are late for the development I'm working on at the moment. He spent more than one year to "redesign" a tool that was already present in our application, but now he wants us to implement it in two weeks. I personally think that if we want to do it correctly, we need at least one month, or maybe even 6 weeks.

I don't know what to do, because I think that the boss thinks that we are just slow and ineffective. That's not the way I will get the raise I think I deserve.

Why is it like that? That doesn't seem so hard to understand that if I need x days to complete a task, I can't do it in x/2 days, even if you say "please" and ask with a smile. That seems so obvious that the deadline will be missed and/or that the quality requirements won't be met.

I don't need to know how I can explain to my boss that software development is a longer process that just clicking an icon. Because I hope he already knows that.


问:
what licence for an application that uses libraries with different licences
I have developed .NET software that uses two libraries:

Library A has MIT licence and I'm using my own version of it as I edited the source code of this library.

Library B has Ms-PL licence and I use only the binaries.

My application will be distributed freely in binaries and source code(including the source code of library A).

Since it is my first time to distribute a public application I want to know few things:

what Licence I should choose.

a part from the to-be-chosen licence Eula presented to the user in the installation , what else I should do for the binaries ?

for the source code, what should I include exactly ?

答:
There are two main considerations for which license to choose for your application

You must be comfortable with the license terms (the freedoms/restrictions given to users/modifiers of your software)

The chosen license must be compatible with the licenses of all the libraries you use. This rules out the GPL license in your case, because it is incompatible with the Ms-PL.

After you have chosen a license, you can usually find a page through google explaining how to apply the license to your software.

The details differ from license to license, but generally there is a file with the full license text that you should include in your project and a text that should appear in every source file along with your copyright statement.

Software released under an open source license doesn't generally have an EULA , but sometimes an installer shows the copyright license(s) where it would show an EULA for commercial software.


答:
Yes, this is true of any language, within a function or some confined code space you have more things in flight than registers to hold them you have to spill over into memory, and you will fall off of a performance cliff at that point.

When you hit that point how far the performance falls off, etc varies widely.

There is value in understanding this and it is very easy to understand this by creating simple functions, compiling and disassembling them to see what is really going on.  You will want to use the optimizer in general to avoid just really slow code all the time, but that amplifies the problem, as little as one operation in one line of code can greatly affect performance.  Because as you are asking, you will hit that Nth operation that causes the number of registers needed to exceed the number if free registers you have and now you have to spill over into memory.  Likewise you hit other performance cliffs when your caches fill up or striping of your data causes cache thrashing, etc.

At the end of the day though this is the nature of using high level languages, if you plan on porting this code at all you can do a little tuning to avoid blatant performance hits on all platforms, but you are not going to get too much benefit trying to overoptimize for one platform and possibly hurting others.  If you truly have a performance problem you need to first prove you have a performance problem related to the code in question and then solve that using assembly for that or any target where that code is causing a performance problem.  And yes that creates a readability and maintainability problem.

In general readability, maintainability, performance, choose two.


答:
Deadlines are always too short because the estimates are inaccurate.

There are two important points to consider with deadlines:

Estimates must be based on all expected effort (including understanding, implementing, testing new/previous behaviour, and deployment, and more)

Sometimes estimates are wrong

Point 1 speaks for itself as estimates must reflect the work that's required, and at the speed of the person(s) doing the work.

Point 2 however acknowledges that whilst estimates may improve over time, and the typical Scotty Principle should apply, there is always the chance that the estimate is just plain wrong.

It is up to the whole team (everyone including the manager) to accept that deadlines being too short indicates a problem in the estimations.

Your case indicates that the problem could be that your deadlines are given to you without proper investigation into the level of effort required (i.e. asking you how long it would take to do the work).

Sometimes the deadline is immovable e.g. releasing before date X means you all get paid, whilst after means no one buys/pays for the work; here everyone must accept that there isn't time to get the work done as completely as it could be.

Lastly, there could potentially be a trust issue where the manager has been burned in the past by work being overestimated; if you deliver early and report this to your manager you will build trust and the team attitude will improve.

Decide how much effort to put into this; if it still isn't working decide to move on to another team/company.

Just be aware that this scenario is not limited to this specific manager, at this specific company, and the sooner you determine your way of handling this the better you will be.

Title: Why are deadlines always so short?


问:
block access to area/controller's methods but allow inherited controller to run methods, asp .net mvc5
I am trying to find out how to block a whole area/controller from being accessed by typing url website.com/area1/basecontroller/method1 (this area also contains the views that will be displayed) , while still being able to inherit said controller and use the method from original controller like so website.com/area2/extendedbasecontroller/method1.

There would not be a method1 in the extendedbasecontroller, it would just perform method1 from the basecontroller

Is it possible or could it be achieved in a different way?

答: A different way is what you want here -- extract a class that does method1 and then reference the class in both controllers. MVC controllers really shouldn't ever call each other in general.


答:
One issue I've seen a few times is that the PHBs don't quite get that the first working version of a product is far from done -- they can't see that it is still really a rough draft.

Nowadays I ask them "so, when you write a proposal do you get it complete and send it to the client or do you go through a drafting process?"

Refactoring is our drafting process.

Title: Why are deadlines always so short?


答:
I believe the primary reason deadlines are often too tight comes from a profound misunderstanding.

There are several variables to juggle when producing something:

effort: the necessary duration to be spent to produce

elapsed: the duration between beginning and finishing

The effort is non-negotiable, if it takes you 10 hours to accomplish a task there is nothing you can do about it. Another person might be able to do it either faster or slower, however. In Agile practices, the recommendation is to measure the effort in points to account for differences in velocity between developers.

The elapsed however, varies widely: it depends on how many people will be working on parallel, how many hours each day they will work on it, etc... In the end, therefore, the elapsed depends on planning: who will be affected to the task, when, ...

Often times, deadlines are negotiated. Because the elapsed depends a lot on planning (and shifting priorities), there is indeed some slack, and therefore they can be negotiated indeed to a degree. Bad managers, however, tend to impose unrealistic deadlines because they keep pushing them past that degree reasoning that since they managed to push it back some, they might as well try some more.

When this happens to you, and they keep pressuring you, you might be interesting in the Agile movement. Agile "cheated" by introducing a third variable: scope.

Instead of sizing the whole thing, you size it piecemeal (and make the dependencies between the pieces explicit). If your manager wishes to reduce the elapsed time, he may then remove some pieces.

Title: Why are deadlines always so short?


问:
Managing 'done' but not releasable code in TFS
I am working in an organisation with 11 scrum teams developing on the same code base.  Currently, all development is done in trunk, and at the end of a sprint everything MUST be releasable, or it must be backed out (an arduous process) as a release is cut.

My opinion is that while work in a sprint is (ideally) 'done' at the end of the sprint, this doesn't necessarily mean ready for release. You may be at a point where you do not have a Minimum Viable Product to release, but have some stories complete. If a story is not done, or the story is only part of a larger feature, it should be easy to keep this separate from the release ready code.  At the moment it is all backed out, the release cut is taken, then it is checked back in. A huge waste of time!

We use continuous integration, which is the main argument for everyone developing on trunk.  Occasionally teams use a team branch, but this is currently frowned upon.

I've been considering simply having a 'dev' and 'release' branch, and pushing features to release when they are an MVP, or having a branch for each story or feature, but this is very admin heavy in TFS. Have other people dealt with similar issues in the past, and what are your thoughts on the best way forward?  Unfortunately, we are tied to TFS in the short term.

答:
The scrum guide is very clear: The work of a sprint is to deliver a potentially releasable increment of 'done' product at the end of each sprint.

There are a number of reasons for this but the main one is to avoid incurring unnecessary technical debt. Until you have made your product potentially releasable, you do not know how much work remains to be done, or how long it will take to release.

It looks like you have an excellent branching policy in place and it's great to see that you are doing continuous integration. I wouldn't change a thing.

One issue I do see though, is where you describe a story as being part of a larger feature. I can understand why this would cause issue with your branching policy. But I think the problem is with your pbi. A good product backlog item should be independent and I'd be more inclined to look at improving that to resolve the problem, rather than compromising on branching.


问:
C programming practice, passing a pointer to a function
Consider the following C function which takes as argument a string, which is then stored inside a struct:

```<code>struct mystruct* usestring(char* string)
{
    struct mystruct *struct;
    struct = malloc(sizeof(struct mystruct));
    struct->string = string;
    return struct;
}
</code>```

My understanding is that the string passed to the function is the same string that is stored inside the struct.

What is the proper etiquette in this situation? Should I make a copy of the string and store that in the struct, or should I expect that the function caller will not modify the string later?

答:
This will always depend on many factors, but as elementary guidance:

For pointers to const, ownership should not be transferred and the callee should not assume the pointed object will continue to exist after it returns.

For pointers to non-const, ownership transfer must be documented. Whether ownership is transferred or not is a matter of what is more practical in the particular place.

Pointers should be to const whenever possible.

This is not always the most efficient thing to do (you sometimes copy when the object actually will continue to exist), but it is a way to reduce the number of places where you have to be careful.


问:
With a highly bespoke responsive website, will it be most effecient to customise bootstrap / use something else (pure-io?) / roll my own rules
I've got a few non trivial responsive website builds coming up. They are not platforms or apps, but large marketing / brochure websites where eye for detail is important.

I've used bootstrap extensively as well as pure.io, as well as my own rules.

I'm wondering what is the most efficient way to build these. I am planning on starting with bootstrap and customising, but I chose pure.io in the past, as I had to make so many changes to bootstrap to get a very fiddly design into it (ie it went against bootstrap conventions)

Does anyone have any advice on this?

答:
You have the fundamental problem of working with multi-purpose "framework" code. The choice of a CSS foundation like Bootstrap vs Pure vs roll-your-own are not much different from Flask vs Django vs do-it-yourself, AngularJS vs Backbone.js vs home-grown,  or dojo vs jQuery vs adhoc.

The fundamental questions are always ones like: What will get me there fastest, cheapest, most efficiently, and with the greatest ease? What will be the simplest and most flexible? What will be the most maintainable? What will require the least rework and force-fitting?

The fundamental problem is that those frameworks are always trying to support a large and diverse set of applications, and they are generally prescriptive. They assume that there are "right ways" to do things, and that most applications should do things those ways. Some are more emphatically normative, trying to impose the "right way," while others are merely conventional or suggestive. You see the same kind of differences in language design, where Python and Java for example clearly suggest "There is a right way to do it! Do it that way!" while Perl, PHP, and Ruby are more "Hey, man! Whatever floats your boat! Tim Toady!"

In your case, you seem to already have a good amount of experience with the options, and to understand the kind of diversions and patches that will be required for your fiddly custom projects. Absent examples of those designs, we probably cannot say whether building up from Pure or adjusting back from Bootstrap will be less work.

I have personally chosen the build-up route more often. It's challenging to discover how complex frameworks operate under the covers, and the best ways to extend them. I hate the feeling of constantly fighting my framework. If I find just the right way to subclass or adjust the framework, it can be awesome and elegant. But if I don't find that elegant adjustment, and then have to hack at it crudely, the process of figuring out work-arounds, and then debugging them and making them reliable, is onerous. There's also a gamble involved that you will be able to find the right work-arounds. Occasionally, it is not even feasible (at least, not in the allotted time/budget). So I would rather start with a smaller platform and build up. That has proven more reliable and effective for me.

So that argues for the Pure route. But you, good sir, seem much closer to the specific job/framework tradeoffs involved, and therefore are best positioned to make this choice. In the end, they're both great foundations, and either one will probably get you what you need.


问:
Should my internal MVC/MVVM application use Web Services for Persistence?
Just talking about internal applications or intranet web apps... At some companies I've seen their business-logic piece (Model in MVC/VM in MVVM) on one (or both) sides of a Web Service.  And on the other side of the web service is the Persistence.

```<code>MVC/MVVM > Service Layer > Persistence
</code>```

This is only for intranet/internal application customers, and both the web or app code, and the persistence (usually ORM) dlls both sit on the same server, or even in the same folder.

I'm used to seeing internal apps and intranet websites that reference a business-layer... then that business-layer connects to persistence.  So the app itself is persistence-ignorant.

But with my own apps, if something needed to be exposed externally, that something is opened up via a web service.  But otherwise, everything stays internal.

Is there a reason for why I've seen a couple different companies do this?  They didn't seem to know the answer themselves.

答:
I tend to think that's a bit silly. More formally, it's an example of what I would call "speculative generality".

The counterargument would be that the architecture you describe allows for other sorts of clients to be easily plugged into the same system with less effort, and that one never really knows what sort of new direction the project might take. (Realistically, though, sometimes these things can be known to a very great extent. Pretending everything's an unknown and requires generalization can be a very bad way to work, in my experience.)

I suppose that the deciding factor is how much effort the team thinks it will take to use Web Services. Superficially, it doesn't seem like the sort of thing that would require too much extra work. However, debugging and configuration implications must be considered (as opposed to just the code itself), and that's where I think that the Web Services approach probably damages the developer experience.


问:
Is it bad practice to resolve null arguments to default static variables?
First, let me show you an example (written in ActionScript 3.0):

```<code>class GameObject {
    public static function MakeFromName( pName:String,
                                         pAtlas:TextureAtlas = null,
                                         pGameData:Object = null ):GameObject {

        // If these arguments are not passed, they default to the static INSTANCE's
        // currentAtlas and currentData.
        if (pAtlas == null) pAtlas = GameBaseClass.INSTANCE.currentAtlas; // <--
        if (pGameData == null) pGameData = GameBaseClass.INSTANCE.currentData; // <--

        var theSymbolData:Object = pGameData.symbols[pName];
        var theSymbolTextures:Vector.<Texture> = pAtlas.getTextures( pName );

        var newGO:GameObject = new GameObject();
        newGO.MakeFromData( pName, theSymbolTextures, theSymbolData );

        return newGO;
    }

    // MakeFromData defined somewhere down in the code...
}
</code>```

I'm having this debate with a coworker regarding the above 'null' (basically optional) parameters.

To me, it makes sense to auto-resolve those two parameters (pAtlas and pGameData) to some sort of central resource (in this case, the primary Atlas and Data used in the game). This GameBaseClass goes hand-in-hand with GameObject, so I see no harm in referring to it's singleton-instance's properties. The developer still has the option to supply their own Atlas and Data.

BUT, my coworker believes this ties the classes together too much - it isn't loose enough.
I can understand his point if it was actually referring to the derived classes used in the game (i.e: AwesomeGame.INSTANCE.currentAtlas, where AwesomeGame extends GameBaseClass). But it isn't! From his point of view, the developer should be forced to enter every single parameters, nothing optional (in this particular situation).

Is there any way to have the best of both worlds?

The only other way I can think of is just to write two separate methods (one with the 2nd and 3rd arguments, and one without), but that still doesn't address the issue with the GameBaseClass dependency.

Any ideas?

EDIT:
In the above example, I used ActionScript 3.0 which does not support assigning non-constant variables. In other words, it allows hardcoded Numbers, Strings (empty ones too), Booleans, and Constants (although I don't think it would work with non-primitive constants, could be wrong though). Since the GameBaseClass.INSTANCE.currentAtlas is a property that could change in the lifetime of the running application, this cannot be inlined as a 'compile-time' default value.
Hope that makes more sense!

答:
If those parameters are not optional, then raise an exception.

Is they shoudn't be optional, then Intelligent defaults are a good idea.

Also if GameBaseClass is a top abstraction, you are adhering to the Dependency Inversion Principle. Your class depends on an abstraction not on a concretion.


答:
That is perfectly fine. This is often the compromise between the "passing everything in makes it too complex!" and the "using a static directly makes things inflexible and hard to test!" camps.

Personally, I would only do this if the common (75%+) usage is to use the default instance. Otherwise, people will go with the easiest route (less arguments) which isn't necessarily the correct route. Making people specify the parameters means they'll say "how do I make a TextureAtlas?" rather than using the common one, which is its own incorrect route.

Having these sane defaults encourages users of the class towards doing the right thing most of the time, while not precluding them from doing the right thing when it deviates from the norm (with a little more work).

Title: Is it bad practice to resolve null arguments to default static variables?

Body:
First, let me show you an example (written in ActionScript 3.0):

```<code>class GameObject {
    public static function MakeFromName( pName:String,
                                         pAtlas:TextureAtlas = null,
                                         pGameData:Object = null ):GameObject {

        // If these arguments are not passed, they default to the static INSTANCE's
        // currentAtlas and currentData.
        if (pAtlas == null) pAtlas = GameBaseClass.INSTANCE.currentAtlas; // <--
        if (pGameData == null) pGameData = GameBaseClass.INSTANCE.currentData; // <--

        var theSymbolData:Object = pGameData.symbols[pName];
        var theSymbolTextures:Vector.<Texture> = pAtlas.getTextures( pName );

        var newGO:GameObject = new GameObject();
        newGO.MakeFromData( pName, theSymbolTextures, theSymbolData );

        return newGO;
    }

    // MakeFromData defined somewhere down in the code...
}
</code>```

I'm having this debate with a coworker regarding the above 'null' (basically optional) parameters.

To me, it makes sense to auto-resolve those two parameters (pAtlas and pGameData) to some sort of central resource (in this case, the primary Atlas and Data used in the game). This GameBaseClass goes hand-in-hand with GameObject, so I see no harm in referring to it's singleton-instance's properties. The developer still has the option to supply their own Atlas and Data.

BUT, my coworker believes this ties the classes together too much - it isn't loose enough.
I can understand his point if it was actually referring to the derived classes used in the game (i.e: AwesomeGame.INSTANCE.currentAtlas, where AwesomeGame extends GameBaseClass). But it isn't! From his point of view, the developer should be forced to enter every single parameters, nothing optional (in this particular situation).

Is there any way to have the best of both worlds?

The only other way I can think of is just to write two separate methods (one with the 2nd and 3rd arguments, and one without), but that still doesn't address the issue with the GameBaseClass dependency.

Any ideas?

EDIT:
In the above example, I used ActionScript 3.0 which does not support assigning non-constant variables. In other words, it allows hardcoded Numbers, Strings (empty ones too), Booleans, and Constants (although I don't think it would work with non-primitive constants, could be wrong though). Since the GameBaseClass.INSTANCE.currentAtlas is a property that could change in the lifetime of the running application, this cannot be inlined as a 'compile-time' default value.
Hope that makes more sense!


问:
Web design standards
While designing web pages using php, are there standards that should be followed? For example suppose there are two pages. First page looks like this:

```<code><body>
<div>
<?php include 'page2.php';?>
</code>```

page2.php file looks like this:

```<code><?php print 'some text';?>
</div>
</body>
</code>```

Is such designing a standard practice? Does it affect search engine results?

答:
What you have there is idiomatic HTML generation

No problem with that - if you're happy to maintain it. As others have said, it is the final response that is important.

How can you check your response?

Use the Web Developer toolbar for Firefox, which will manage access to these validation sites from W3C:

XHTML validator

CSS validator

Ideally, you should target XHTML Strict but your requirements may vary.

And the search engine?

It won't see how you generate the response, it will only see the response. Search engines on the whole prefer to see well-formed, standards compliant XHTML simply because it's easier for them to parse. However, check out the Google web master notes for what they look for in order to promote your site to the top of the search results. (Hint: Google wants timely, relevant content that is considered to be the definitive resource as a result of others approving it).

OwnerDisplayName: Sanket Raut

Title: Web design standards


答:
As others have said, it depends on context.

Consider the following code, which creates new instances of struct mystruct and adds them to a list:

```<code>while ( some_condition )
{
  char inputString[SIZE];
  if ( getInput( inputString ) )
  {
    struct mystruct *newStruct = usestring( inputString );
    addEntry( list, newStruct );
    ...
  }
}
</code>```

Every instance of newStruct in the list will wind up pointing to the same string; even better, that pointer will be invalid after the while loop exits.

In this particular case, you should make a copy of the input string and store that to the struct.  Of course, that opens up questions about how that memory is to be recovered, who's responsible for it, etc.

Title: C programming practice, passing a pointer to a function

Body:
Consider the following C function which takes as argument a string, which is then stored inside a struct:

```<code>struct mystruct* usestring(char* string)
{
    struct mystruct *struct;
    struct = malloc(sizeof(struct mystruct));
    struct->string = string;
    return struct;
}
</code>```

My understanding is that the string passed to the function is the same string that is stored inside the struct.

What is the proper etiquette in this situation? Should I make a copy of the string and store that in the struct, or should I expect that the function caller will not modify the string later?

Body:
As others have said, it depends on context.

Consider the following code, which creates new instances of struct mystruct and adds them to a list:

while ( some_condition )
{
  char inputString[SIZE];
  if ( getInput( inputString ) )
  {
    struct mystruct *newStruct = usestring( inputString );
    addEntry( list, newStruct );
    ...
  }
}

Every instance of newStruct in the list will wind up pointing to the same string; even better, that pointer will be invalid after the while loop exits.

In this particular case, you should make a copy of the input string and store that to the struct.  Of course, that opens up questions about how that memory is to be recovered, who's responsible for it, etc.


问:
How are some IEEE 754 floats printed succinctly?
Using this calculator, I can see how the decimal ".8" and the expression ".7 + .1" have different representations:

```<code>.8      = 1.1001100110011001100110011001100110011001100110011010 *2-1
.7 + .1 = 1.1001100110011001100110011001100110011001100110011001 *2-1
                                                              ^^
</code>```

But what mechanism causes "0.8" to be printed for the top value? E.g. alert(.8) in JavaScript. Why does it not print something like "0.800000011920929"?

Is this a feature of IEEE 754 or the programming language implementing it?

答:
The paper How to Print Floating-Point Numbers Accurately by Guy L. Steele Jr. and Jon L White describes one approach to the problem of printing numbers.

Quoting from that paper:

What is the correct number of digits to produce if the user doesn’t specify? If a system prints too many digits, the excess digits may be “garbage,” reflecting more information than the number actually contains; if a system prints too few digits, the result will be wrong in a stronger sense: converting the decimal representation back to
  binary may not recover the original binary value.

Which echos delnan's comment: "What would you expect to be printed?"

As far as I can tell, how IEEE 754 numbers are printed is a feature of the programming language.

The Steele and White paper explain some techniques for printing floating point numbers accurately, and they, or something similar, may be implemented in JavaScript.


答: Most implementations round floating point numbers by default to 6 significant digits (removing any trailing zeros) when converting them to strings, as that seems to match the expectations of most users.</p>

Title: How are some IEEE 754 floats printed succinctly?

Body:
Using this calculator, I can see how the decimal ".8" and the expression ".7 + .1" have different representations:

```<code>.8      = 1.1001100110011001100110011001100110011001100110011010 *2-1
.7 + .1 = 1.1001100110011001100110011001100110011001100110011001 *2-1
                                                              ^^
</code>```

But what mechanism causes "0.8" to be printed for the top value? E.g. alert(.8) in JavaScript. Why does it not print something like "0.800000011920929"?

Is this a feature of IEEE 754 or the programming language implementing it?


问:
I don't understand the arguments against operator overloading
I just read one of Joel's articles in which he says:

In general, I have to admit that I’m a little bit scared of language features that hide things. When you see the code

```<code>i = j * 5;
</code>```

… in C you know, at least, that j is being multiplied by five and the results stored in i.

But if you see that same snippet of code in C++, you don’t know anything. Nothing. The only way to know what’s really happening in C++ is to find out what types i and j are, something which might be declared somewhere altogether else. That’s because j might be of a type that has operator* overloaded and it does something terribly witty when you try to multiply it.

(Emphasis mine.) Scared of language features that hide things? How can you be scared of that? Isn't hiding things (also known as abstraction) one of the key ideas of object-oriented programming? Everytime you call a method a.foo(b), you don't have any idea what that might do. You have to find out what types a and b are, something which might be declared somewhere  altogether else. So should we do away with object-oriented programming, because it hides too much things from the programmer?

And how is j * 5 any different from j.multiply(5), which you might have to write in a language that does not support operator overloading? Again, you would have to find out the type of j and peek inside the multiply method, because lo and behold, j might be of a type that has a multiply method that does something terribly witty.

"Muahaha, I'm an evil programmer that names a method multiply, but what it actually does is totally obscure and non-intuitive and has absolutely nothing to do whatsoever with multiplying things." Is that a scenario we must take into consideration when designing a programming language? Then we have to abandon identifiers from programming languages on the grounds that they might be misleading!

If you want to know what a method does, you can either glance at the documentation or peek inside the implementation. Operator overloading is just syntactic sugar, and I don't see how it changes the game at all.

Please enlighten me.

答:
Based on the other answers I've seen, I can only conclude that the real objection to operator overloading is the desire for immediately obvious code.

This is tragic for two reasons:

Carried to its logical conclusion, the principle that code should be immediately obvious would have us all still coding in COBOL.

You don't learn from code that is immediately obvious. You learn from code that makes sense once you take some time to think about how it works.


答:
I don't think your defaults create the coupling.  I think you wanting them is a sign that the coupling already exists.  There are at least two other signs of tight coupling here:

You're not even using those parameters directly, you're using members of those parameters, which is a Law of Demeter violation.

Wanting multiple factory-like methods that call each other.

There are other ways to avoid passing parameters around all over the place:

Move MakeFromName to another existing class.  Perhaps the code that calls it, or TextureAtlas.

Create one new class for the sole purpose of creating GameObjects.  Its constructor could store the Atlas and GameData, then you can create many GameObjects with the same dependencies with factory.MakeFromName(name).

Invert the dependencies so a GameObject doesn't need to know about the textures and symbols.

Pass in the textures and symbols later when the GameObject is used, rather than when it is created.

Move the responsibility for the defaults into the GameObject constructor.  In other words, have default symbols and textures instead of default atlases and game data.

Consolidate the places where you call MakeFromName into one place.  If you have one place where the association between atlas, game data, and name is made, rather than being scattered all over the place, you won't care about a couple extra parameters.

I can't really advise you further without seeing all your code.  Keep in mind, it's often hard to tell if these suggestions will help without trying them.

As a side note, I'm wondering why you didn't just make those objects a default in the function signature, instead of assigning it to null there and checking for null later.  It seems like an unnecessary intermediate step.

Also as a side note, I don't know what language this is, but I'm guessing that Object is its top level base class from which all objects ultimately derive.  If so, using it this way for your game data isn't advisable.


答:
Couldn't you do something like that:

```<code>class GameObject {
    public static function MakeFromName( pName:String,
                                         pAtlas:TextureAtlas = GameBaseClass.INSTANCE.currentAtlas,
                                         pGameData:Object = GameBaseClass.INSTANCE.currentData ):GameObject {

        var theSymbolData:Object = pGameData.symbols[pName];
        var theSymbolTextures:Vector.<Texture> = pAtlas.getTextures( pName );

        var newGO:GameObject = new GameObject();
        newGO.MakeFromData( pName, theSymbolTextures, theSymbolData );

        return newGO;
    }

    // MakeFromData defined somewhere down in the code...
}
</code>```

This way your intentions become clear from the signature, if you won't passe the value, it'll fallback to the default value.

Body:
Couldn't you do something like that:

class GameObject {
    public static function MakeFromName( pName:String,
                                         pAtlas:TextureAtlas = GameBaseClass.INSTANCE.currentAtlas,
                                         pGameData:Object = GameBaseClass.INSTANCE.currentData ):GameObject {

        var theSymbolData:Object = pGameData.symbols[pName];
        var theSymbolTextures:Vector.<Texture> = pAtlas.getTextures( pName );

        var newGO:GameObject = new GameObject();
        newGO.MakeFromData( pName, theSymbolTextures, theSymbolData );

        return newGO;
    }

    // MakeFromData defined somewhere down in the code...
}

This way your intentions become clear from the signature, if you won't passe the value, it'll fallback to the default value.


问:
Extending a struct. Using helper classes rather than composition
I have a struct which I want to add static methods to. Yes, you guessed right I'm talking about Datetime.

It's a pretty typical requirement to add MyCustomParse. It happens to return Datetime?, so it's not a constructor, but it's in that area, a static method that returns an instance. The content of this method has already been written and currently happy lives as a instance method of a class that uses it. I want to bring it out of that class so I can use it elsewhere.

Traditionally I would put it in a helper class (which is what I've done here), but apparently they're evil.

What I really want to do is tie Datetime.MyCustomParse(mystring). But the only way I can see is to make a new struct that composes Datetime. I then add in my method, write the implicit conversions and then put in all the other Datetime methods etc. This would be a pain to code (Being verbose also causes problems wrt xml docs  and naive code coverage metrics, if that counts for anything).

I have considered extension methods, but I don't think the methods make sense on instances.

What is the strict OO position? Do I get a pass on writing methods that should belong to classes in separate helper classes when I want to extend structs in this fashion?

What is the pragmatic position (I'm not saying OO isn't pragmatic), is this code you would write, or have I missed a trick?

```<code>internal static class DateTimeHelper
{

    public static DateTime? MyCustomParse(string utcDateTimeText, string[] formats)
    {
        DateTime utcDateTime;
        if (DateTime.TryParseExact(utcDateTimeText, formats, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out utcDateTime))
        {
            return utcDateTime;
        }

        return null;
    }
}
</code>```

PS I know there are more nuanced views on helper classes, but I still feel I need to justify my use here.

答:
What is the strict OO position?

"strict" is undefined in OO space?

What is the pragmatic position?
  I want to bring it out of that class so I can use it elsewhere.
  The content of this method has already been written and currently happy lives as a instance method of a class that uses it.

OO Rationalization

Well, one approach may be to think about creational design patterns. I see this as counterpoint to the "helper class" idea. I see the "helper" as a smorgasbord - incoherent in terms of domain object design.

But a Factory, Builder, etc. composes behavior within an object- a domain-coherent thing. How is this different from a helper class? Intent.

OO Pragmatism meets Intent

Refactor to turn the method into a delegate. You can declare the delegate at the namespace level if necessary.

Write a instance-building something that registers/binds/whatever the delegate method. I expect the method's implementation will be inside this something.

Somthing's purpose in life is to instantiate fully-realized objects of the class/struct. Something does not contain those "random" type-specific (but not instance-owned) helper methods.

And because of intent we do not want the pragmatic approach of a class static method - which you have already dismissed.

ContentLicense: CC BY-SA 4.0


问:
Rails Google Cloud Messaging with heroku
I'm looking at using GCM to send notifications from my rails app to an Android app. The getting started guide says:

```<code>In the resulting configuration dialog, supply your server's IP address.
</code>```

I'm using Heroku, so the IP address is changing frequently correct? Can I still use GCM? Was looking at using the rails gem and I couldn't find any documentation related to Heroku.

答: The answer to this is that you don't NEED to supply IP addresses. It's simply whitelisting those addresses so you can control which IP's use your GCM implementation. In the case of Heroku where the IP address isn't known ahead of time, you can just NOT enter any IP's when setting up GCM. I implemented GCM with Heroku and it's working beautifully.</p>


答:
Yes, it's very bad practice, for several reasons, including at least:

Global state is bad in general. By having code that only uses the global state when the argument is null, you allow it to be used correctly and to be tested, but any other code that uses your code with a null argument then becomes problematic, as it inherits this global state. If you have two or more components using your code with null argument and then decide you want to be able to use both at the same time, you're in trouble.

It's error-prone. If a caller accidentally passes null, perhaps as a result of a logic bug in the caller (often in the form of an unhandled error condition), your code acts on an unrelated object rather than producing an error.

It has cost. Perhaps low cost, but still some cost, in the form of (1) an extra branch to test for null and do something special, and (2) the cost of the extra object/state which well-written callers will never use, but which has to exist anyway at runtime because it might be referenced.


问:
Things developers do before the coding phase
I'm a new software developer, and in my internship my boss asked me to develop an application that allows him to manage his inventory. Something small but, for me, very enriching.

The application is running, he found some bugs and problems but I fixed them. This is not the problem. My problem is that when I was working on the application, I didn't know what I was doing, so everything was in disorder. The project took me 2 months and another developer said that he could do it in a month or less. This surprised me, so I want to know:

How does a professional developer plan a project before starting development?

答:
So you want to know, how to become an efficient developer?

1) You have to develop communication skills

Before you start any project, you have to talk to you customer (in your case your boss) about what he wants. The difficulty here is not only to understand, what your customer says, but what he really means - these are most of the time two different things. It helps if you get your requirements in plain sentences. The simpler the better. You could do this formalized with "user stories" or "story cards", but a simple ticket-system will do.

2) You have to develop a toolbelt and a skillset

Like every good craftsman, you have tools and skills. One part of the Tools are Frameworks in the language you work in. The more you know (whether hearsay or in depth doesn't matter) the better for you. Another part are real tools: buildtools, monitoring tools etc.

And then there are skills. At first: stay sharp in your language. The more you know about the language you are working in, the better you get at solving problems in this language. Knowing the syntax is not enough: you have to know how to express yourself in the language you are working in - like an author writing prose or poetry, you have to know your language.
This includes a major part - which I find often neglected by novices: knowledge of the datastructures, your language offers: what kind of structures are there? how do they work internally? how efficient are they?

Then you need to have a working knowledge of problems others solved already (Algorithms and Design Patterns). The better you understand, what others have already done, the faster you are going to develop your solution. Sometimes programming is like plumbing existing pipes together and the problem is solved.

3) Think about your problem

Analyze your problem from different perspectives: GUI, Backend, Database, Client, Server, whatever perspective you could take.

4) Write your specifications down into acceptance-tests

Only when your solution passes all acceptance-tests, you are sure, that you build the right product.

5) Begin writing small Units and testing those units

Whether you write tests first, as apologets of TDD say or write code and than test doesn't matter, as long as you have tests at all. You are your worst enemy and nothing happens more often than breaking your code. Writing tests helps detecting sloppiness.

6) Get early and frequent feedback.

After you've written small chunks of code and testing those bits and pieces
show the result to your customer. Talk about the results frequently and in depth. So you get a better feeling, for what the customer wants and an immediate feedback for what you are doing.

The project took me 2 months and another developer said that he could do it in a month or less.

So, when a fellow developer said this, that only means, that he has more experience (more problems already solved) and better knowledge, how to plumb such a solution.

Programming is a skill like every other. You have to train and soon get better.


答:
An aside: You have parameters default value set to null and then the first thing you do is null check them. Have you tried method overloading. Ie </p>

```<code>public static function MakeFromName(String mystring)
{
    MakeFromName(mystring, GameBaseClass.INSTANCE.currentAtlas, GameBaseClass.INSTANCE.currentData)
}
</code>```

Body:
An aside: You have parameters default value set to null and then the first thing you do is null check them. Have you tried method overloading. Ie

public static function MakeFromName(String mystring)
{
    MakeFromName(mystring, GameBaseClass.INSTANCE.currentAtlas, GameBaseClass.INSTANCE.currentData)
}


问:
What to do about "stopping point syndrome"?
I have noticed a behavior in myself that I call "stopping point syndrome"... it means I cannot stop working until I reach a "stopping point" (or I become exhausted).  In other words, if I am in the zone working on getting a feature completed, I won't stop until I get it done.   If it's a bug I'm working on, this effect is even more pronounced... I won't stop until it's fixed, or at the very least, understood.  Even though I work from a laptop and have VPN and could easily go home and pick up on the work later that evening, that fact does not help me leave work... it's like I'm afraid I will die before I find the bug.

I have a very hard time explaining this to family members who can't figure out why I never come home from work at the same time and sometimes come home at 11 pm.  Even managers have been mystified by this, and I've noticed that most of my colleagues have no trouble working the same hours every day.

Does anyone else have this problem?  Should I be worried about this and/or try to change it?  If so how?

答:
programming, especially debugging, consumes a lot of short-term memory. stopping before you're done wipes out the cache, and wastes a lot of time getting back to where you were.

so this is natural, efficient, and is not something to be "fought against" - though it should be planned for.

one thing that helps is to take notes while you're working, and when you stop make a note of the next thing to be done


答:
Why not use an extension method?

```<code>public static class DateTimeExtensions
{
   public static DateTime? AsDateTime(this string value, string[] formats)
   {
       DateTime utcDateTime;

       if (DateTime.TryParseExact(utcDateTimeText, formats,CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out utcDateTime))
       {
            return utcDateTime;
       }

       return null;
   }
 }
</code>```

This will extend the string type adding the method AsDateTime.

```<code>string[] formats= {"M/d/yyyy h:mm:ss tt", "MM/dd/yyyy h:mm:ss tt" };
string unParsedDateTime = "05/01/2009 6:32:05 PM";

DateTime parsed = unParsedDateTime.AsDateTime(formats);
// or
parsed = "05/01/2009 6:32:05 PM".AsDateTime(formats);
</code>```

Title: Extending a struct. Using helper classes rather than composition

Body:
I have a struct which I want to add static methods to. Yes, you guessed right I'm talking about Datetime.

It's a pretty typical requirement to add MyCustomParse. It happens to return Datetime?, so it's not a constructor, but it's in that area, a static method that returns an instance. The content of this method has already been written and currently happy lives as a instance method of a class that uses it. I want to bring it out of that class so I can use it elsewhere.

Traditionally I would put it in a helper class (which is what I've done here), but apparently they're evil.

What I really want to do is tie Datetime.MyCustomParse(mystring). But the only way I can see is to make a new struct that composes Datetime. I then add in my method, write the implicit conversions and then put in all the other Datetime methods etc. This would be a pain to code (Being verbose also causes problems wrt xml docs  and naive code coverage metrics, if that counts for anything).

I have considered extension methods, but I don't think the methods make sense on instances.

What is the strict OO position? Do I get a pass on writing methods that should belong to classes in separate helper classes when I want to extend structs in this fashion?

What is the pragmatic position (I'm not saying OO isn't pragmatic), is this code you would write, or have I missed a trick?

```<code>internal static class DateTimeHelper
{

    public static DateTime? MyCustomParse(string utcDateTimeText, string[] formats)
    {
        DateTime utcDateTime;
        if (DateTime.TryParseExact(utcDateTimeText, formats, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out utcDateTime))
        {
            return utcDateTime;
        }

        return null;
    }
}
</code>```

PS I know there are more nuanced views on helper classes, but I still feel I need to justify my use here.

Body:
Why not use an extension method?

public static class DateTimeExtensions
{
   public static DateTime? AsDateTime(this string value, string[] formats)
   {
       DateTime utcDateTime;

       if (DateTime.TryParseExact(utcDateTimeText, formats,CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out utcDateTime))
       {
            return utcDateTime;
       }

       return null;
   }
 }

This will extend the string type adding the method AsDateTime.

string[] formats= {"M/d/yyyy h:mm:ss tt", "MM/dd/yyyy h:mm:ss tt" };
string unParsedDateTime = "05/01/2009 6:32:05 PM";

DateTime parsed = unParsedDateTime.AsDateTime(formats);
// or
parsed = "05/01/2009 6:32:05 PM".AsDateTime(formats);


答:
Helper classes can be an organizational anti-pattern when you have some generic Helpers file where you dump every single miscellaneous static function all your projects have ever used. Don't do that. Regardless, they're not evil. A static method is the right place to put some frequently-used computation that don't need to look at any object's private state. Functions like MyCustomParse don't really belong in any class - it can get the job done without looking at anyone's implementation details, so it's not part of any given abstraction. It's just one of the many ways you could choose to convert between two representations of dates.

Creating wrapper classes just because it "feels" more OOP if the function is attached to an instance of something will just cause you and future code maintainers headaches. Besides having to convert back and forth between the wrapped and wrapper types, you'll either have to edit the wrapper or create new ones every time you need a new helper method - and in the latter case you'll have even more conversions. It doesn't scale.

Extension methods can let you use helper functions with the syntax of method calls, which can be nice for Intellisense or when a function call looks better in infix form. This is pure syntax sugar; semantically there's not much of a difference between extension methods and regular static methods.


问:
Domain model for a notification system
I'm trying to build a modular notification service in a ASP.NET MVC web application. The application generates notifications and the service is responsible for delivering the notifications to the right users. When creating a domain model for the notification service, inheritance naturally comes to mind.

One of the requirements for the notification service is that users can be subscribed to particular notification types. For example, User can subscribe to receive NewMessage notifications but not ProfileNotification notifications.

How would one represent a relationship where a User has a Subscription to a notification type, but the notification type is represented through inheritance. Of course, this could be possible via reflection, but I was wondering if there was a domain model that came naturally from my requirements since I couldn't think of one.

I'm using ASP.NET MVC and Entity Framework Code First, but I think the question is general enough for any object oriented programming language.

答:
From your description, it doesn't seem like you need to use inheritance at all - you can do this with a one-to-one and one-to-many relationship.

I would create three objects:

NotificationTypes

Notifications

Users

Notifications would be each tagged to a NotificationType, and Users would be subscribed to multiple NotificationTypes.

Here's a visual model:

```<code>Notification Types:

type name
-----------------------
group
profile

Notifications:

message   | type
-----------------------
message 1 | group
message 2 | group
message 3 | profile
message 4 | profile

Users:

user name  | subscribed types
------------------------------
john smith | group
jane smith | profile
jack smith | profile,group
</code>```

Title: Domain model for a notification system

Body:
From your description, it doesn't seem like you need to use inheritance at all - you can do this with a one-to-one and one-to-many relationship.

I would create three objects:

NotificationTypes

Notifications

Users

Notifications would be each tagged to a NotificationType, and Users would be subscribed to multiple NotificationTypes.

Here's a visual model:

Notification Types:

type name
-----------------------
group
profile

Notifications:

message   | type
-----------------------
message 1 | group
message 2 | group
message 3 | profile
message 4 | profile

Users:

user name  | subscribed types
------------------------------
john smith | group
jane smith | profile
jack smith | profile,group


问:
Distribute load evenly across many cycles
I am looking for a solution that is fast and still readable. I have to do this in C but the code will be static in the end, which mean I could use any tool to generate it.

I have a task which runs cyclically and calls different functions also cyclically

Main functions cycle is 1.

Function a has also cycle 1. So the main function calls it every time

Function b has cycle 2. Main function calls it every second cycle.

Function c has cycle 2.

Function d has cycle 4.

Function e has cycle 4.

Function f has cycle 4.

Function g has cycle 4.

... many more ....

Function X has cycle 500.

If we have many functions that run in the same cycle we try to distribute them.

So for function b we would call it in one cycle and c in the other. Distributing the load evenly.

Similar for d to g. Each one gets called in a different cycle.

My current implementation is very bad.

Every developer who had to add their task to main function calculates their on modulo and calls when needed. This leads to a very unreadable code.

I was thinking of doing something like:

```<code>uint32 mod4 = timer % 4;
bool fourth_1 = mod4 == 0;
bool fourth_2 = mod4 == 1;
bool fourth_3 = mod4 == 2;
bool fourth_4 = mod4 == 3;
bool second_1 = fourth_1 || fourth_3;
bool second_2 = fourth_2 || fourth_4;
/* and so on*/
</code>```

But this seems cumbersome and too error prone specially as the highest cycle time is too high.

How to approach this kind of problem?

-Edit-

As asked i have compiled some information about the number of functions that i have:

32 functions cycle 1

9 functions cycle 2

14 functions cycle 4

3 functions cycle 8

3 functions cycle 32

3 functions cycle 40

2 functions cycle 200

2 functions cycle 400

答:
I may have your definition of "cycle" wrong. If "Cycle N" means that a method should be called when "timer" modulo N is 0, why not put pointers to those functions into a list or array of structure instances, and include in each structure, the "N" you want to modulo? Then after you increment "timer", check each structure to see if modulo N is 0. If so, invoke the function pointer.

After reading the problem description, I see that "Cycle N" has the additional restriction that only one function can run at once for a given N. To satisfy this requirement, keep an additional flag, "last run", in the structure mentioned above. Put each structure for a given N value in a separate list or array. This way you can mark the last run function, then unmark that one, run the next one, mark it, and so on, each time through.


答:
You need to keep this under control. It seems to me that you are currently unable to break your work into manageable pieces or are unable to estimate how long something will take. So you work until it's done. Perhaps you are being too competitive or are afraid you might not get your work done on time.

This is a vicious circle and will not help you in the long run. It could lead to exhaustion, burnout, ...

So practice breaking your work up into smaller manageable achievable tasks. Try to estimate how long each task will take. No task should take longer than a couple of hours. Give yourself plenty of time to get this right. Give yourself time for breaks. And give yourself time to enjoy, learn, appreciate and experience other aspects of life, rather than programming.

Title: What to do about "stopping point syndrome"?

Body:
I have noticed a behavior in myself that I call "stopping point syndrome"... it means I cannot stop working until I reach a "stopping point" (or I become exhausted).  In other words, if I am in the zone working on getting a feature completed, I won't stop until I get it done.   If it's a bug I'm working on, this effect is even more pronounced... I won't stop until it's fixed, or at the very least, understood.  Even though I work from a laptop and have VPN and could easily go home and pick up on the work later that evening, that fact does not help me leave work... it's like I'm afraid I will die before I find the bug.

I have a very hard time explaining this to family members who can't figure out why I never come home from work at the same time and sometimes come home at 11 pm.  Even managers have been mystified by this, and I've noticed that most of my colleagues have no trouble working the same hours every day.

Does anyone else have this problem?  Should I be worried about this and/or try to change it?  If so how?


问:
Factory Design pattern in languages with class types
I was reading in Peter Norvig's Design Patterns presentation.  From slide 13:

Dynamic version needs only the Window classes.

The classes themselves serve as factories

This works because classes are first-class values We can say make(c)

Does it mean that Java and C# don't need the factory design pattern since they can pass around class type as a variable.

答:
Eh, you're missing the key part of the quote: We can say make(c).

While you can pass around types in Java and C#, you can't (nicely, always) then instantiate an object from that type you're passing around. The types aren't guaranteed to be classes (rather than interfaces, enums, delegates). The types aren't guaranteed to be concrete (how do you "make" an abstract class?). The types aren't guaranteed to have default constructors.

Even then, you can always pass around a delegate that fits the right signature and will build you the correct type. That's a perfectly good approach, and a welcome change to the overuse of factories in many places.

The problem is that factories aren't often just some variable type to spin up. More often than not, your factory needs to get some information in order to create the right instance. And very often, the place that specifies what factory to use doesn't know that information (or else it could just create the right instance and use that).


问:
What's a good Programming Metaphor?
I am referring to explaining to the non-programmer what programming is. I made sure to search for similar questions before creating this one, but the few ones I did find seemed to dodge the question, and I specifically would like to see some metaphors or analogies. I personally find it easier to explain something technical to someone through the use of metaphors or analogies.

The reason I'm interested in this is because many people encounter the work of a programmer on a daily basis, but if you ask the average person what a programmer is or does, they don't really know. This leads to certain situations of misunderstanding (ex. "[...] but I thought you were good with computers!")

I really would like to find the best one out there. I would like to be able to easily explain to someone what my career choice is about. Of course, at least the general idea.

I personally don't have a solid one, but I have long thought about it and I have usually gravitated towards the 'language' metaphor, where we happen to know a language that computers understand, and therefore we are able to tell computers what to do, or "teach" them, to solve our problems.

For example:

Imagine that in an alternate reality, humanoid robots with artificial intelligence exist, and some people are able to communicate with them through a common language, which is a variation of English. These people who can communicate with the robots are able to teach them how to solve certain problems or do certain tasks, like doing our chores.

Well, although robots like that don't exist yet, programmers of our time are like those people, but instead of communicating with the robots, they communicate with computers. Programmers "teach" the computers how to perform certain tasks or solve certain problems by means of software which they create by using this "common language".

Programmers and this "common language" are what give us things like email, websites, video games, word processors, smart phones (to put it simply), and many other things which we use on a daily basis.

I don't mean to put programming on the throne or anything, it's just the best metaphor I could come up with.

I'm sure someone will find some issue with this one, it's probably a bit contrived, but then again that's why I'm asking this question.

答:
It is sad but, programming is a work that can be understood only by learning how to do it.

Programming has several different levels of perception and different from different sides.

At low level it is "write very, very detailed instructions for a very, very dumb machine"

At next level it is dealing with complexity. Building new metaphor to simplify work. Like higher mathematics.

From different side its usage of auxiliary technologies like version control, self documented code, project building and testing.

From other side its building "user" interface (not literally, i mean API also UI), predict possible errors (done by user, data or even itself) and correct react on errors.

And finally.

Metaphor for programming is literature. First need to learn the alphabet. But writing a novel at this even not begins.

Title: What's a good Programming Metaphor?

OwnerDisplayName: mmv-ru


问:
In plain English, what is recursion?
The idea of recursion is not very common in real world. So, it seems a bit confusing to the novice programmers. Though, I guess, they become used to the concept gradually. So, what can be a nice explanation for them to grasp the idea easily?</p>

答:
In life (as opposed to in a computer programme) recursion rarely happens under our direct control, because it can be confusing to make happen. Also, perception tends to be about the side effects, rather than being functionally pure, so if recursion is happening you might not notice it.

Recursion does happen out here in the world though. A lot.

A good example is (a simplified version of) the water cycle:

The sun heats the lake

The water goes up into sky and forms clouds

The clouds drift over to a mountain

At the mountain the air becomes too cold for their moisture to be retained

Rain falls

A river forms

The water in the river runs into the lake

This is a cycle that causes its self to happen again. It is recursive.

Another place you can get recursion is in English (and human language in general). You might not recognise it at first, but the way we can generate a sentence is recursive, because the rules allow us to embed one instance of a symbol in side another instance of the same symbol.

From Steven Pinker's The Language Instinct:

if either the girl eats ice cream or the girl eats candy then the boy eats hot dogs

That is a whole sentence that contains other whole sentences:

the girl eats ice cream

the girl eats candy

the boy eats hot dogs

The act of understanding the full sentence involves understanding smaller sentences, which use the same set of mental trickery to be understood as the full sentence.

To understand recursion from a programming perspective it's easiest to look at a problem that can be solved with recursion, and understand why it should be and what that means you need to do.

For the example I will use the greatest common divisor function, or gcd for short.

You have your two numbers a and b. To find their gcd (assuming neither is 0) you need to check if a is evenly divisible into b. If it is then b is the gcd, otherwise you need to check for the gcd of b and the remainder of a/b.

You should already be able to see that this is a recursive function, as you have the gcd function calling the gcd function. Just to hammer it home, here it is in c# (again, assuming 0 never gets passed in as a parameter):

```<code>int gcd(int a, int b)
{
    if (a % b == 0) //this is a stopping condition
    {
        return b;
    }

    return (gcd(b, a % b)); //the call to gcd here makes this function recursive
}
</code>```

In a programme, it is important to have a stopping condition, otherwise you function will recur forever, which will eventually cause a stack overflow!

The reason to use recursion here, rather than a while loop or some other iterative construct, is that as you read the code it tells you what it is doing and what will happen next, so it is easier to figure out if it is working correctly.

Title: In plain English, what is recursion?

Body:
In life (as opposed to in a computer programme) recursion rarely happens under our direct control, because it can be confusing to make happen. Also, perception tends to be about the side effects, rather than being functionally pure, so if recursion is happening you might not notice it.

Recursion does happen out here in the world though. A lot.

A good example is (a simplified version of) the water cycle:

The sun heats the lake

The water goes up into sky and forms clouds

The clouds drift over to a mountain

At the mountain the air becomes too cold for their moisture to be retained

Rain falls

A river forms

The water in the river runs into the lake

This is a cycle that causes its self to happen again. It is recursive.

Another place you can get recursion is in English (and human language in general). You might not recognise it at first, but the way we can generate a sentence is recursive, because the rules allow us to embed one instance of a symbol in side another instance of the same symbol.

From Steven Pinker's The Language Instinct:

if either the girl eats ice cream or the girl eats candy then the boy eats hot dogs

That is a whole sentence that contains other whole sentences:

the girl eats ice cream

the girl eats candy

the boy eats hot dogs

The act of understanding the full sentence involves understanding smaller sentences, which use the same set of mental trickery to be understood as the full sentence.

To understand recursion from a programming perspective it's easiest to look at a problem that can be solved with recursion, and understand why it should be and what that means you need to do.

For the example I will use the greatest common divisor function, or gcd for short.

You have your two numbers a and b. To find their gcd (assuming neither is 0) you need to check if a is evenly divisible into b. If it is then b is the gcd, otherwise you need to check for the gcd of b and the remainder of a/b.

You should already be able to see that this is a recursive function, as you have the gcd function calling the gcd function. Just to hammer it home, here it is in c# (again, assuming 0 never gets passed in as a parameter):

int gcd(int a, int b)
{
    if (a % b == 0) //this is a stopping condition
    {
        return b;
    }

    return (gcd(b, a % b)); //the call to gcd here makes this function recursive
}

In a programme, it is important to have a stopping condition, otherwise you function will recur forever, which will eventually cause a stack overflow!

The reason to use recursion here, rather than a while loop or some other iterative construct, is that as you read the code it tells you what it is doing and what will happen next, so it is easier to figure out if it is working correctly.


问:
How to use Option Type Pattern in a language that doesn't support generics?
I've been interested to start using the Null Object / Option Type approach for replacing my old habits of null-checking multiple parts of my code. But, from the many examples I saw out there, it seems it's a pattern used in conjunction with generics.

Great for C#, Java, Haxe and a bunch of others I'm sure.

NOT so great for ActionScript 3.0 (which is what I was intending to use it for).

So, am I under the wrong impression that this won't be possible / worthwhile in a language that doesn't support Generics? Or is there a way to pull it off without them?

NOTE: It seems the "Null Object" pattern shown in this PatternCraft tutorial doesn't quite resemble the way Option Type was described in some of the other discussions in this stackexchange site. His way looks more like a factory class that spits out a Null??? derivative of some base-class. I was hoping there could be a way to create Null-Objects without needing to write a dedicated class for every single case scenarios where a null-check would typically be used.

EDIT: My apologies, I didn't realize "Null Object" and "Option Type" were two completely different beasts. For the sake of keeping the answers and feedback relevant to the question though, I only changed the title (was originally How to use Null Object / Option Type Pattern in a language that doesn't support generics?).

答:
There is major difference between Null Object pattern and Option types.

Null Object is pure OOP (thus no generics) pattern, where one object implements abstract class / interface in such a way, that calling the method through the interface is same as not calling the method at all. That means the caller has no idea that type of instance is a Null object. So these two cases are equivalent:

```<code>// without null object
IInterface obj = null;
if(obj != null)
    obj.method()

// with null object
IInterface obj = new NullObject();
obj.method()
</code>```

Option types on the other hand are type-safe way to ensure the caller of the method knows that there is possibility that variable might contain "no valid value". This gives compiler power to either warn or error when programmer tries to call method on variable, that might contain null.

```<code>[PSEUDOCODE (that looks like C#)]
// case A
Option<IInterface> obj = getObject();
obj.Method() // ERROR, possible "Null reference exception"

// case B
Option<IInterface> obj = getObject();
if (obj.HasValue)
    obj.Method() // OK, compiler knows that obj has valid value thanks to the if
</code>```

But I believe option types don't make much sense in language, that doesn't have them as language feature (eg. most OOP languages), because compiler is not implemented as to detect such things as the first case (unless you use some kind of static code correctness checking). So you gain nothing against normal null check. Null object pattern on the other hand is natural in all OOP languages. Even those without generics.

Good example of OOP language having support of Option type is C#' Nullable. You know value types always have valid value and Nullable allows you to specify cases where variable might not contain valid value. But this is only for value types.

Body:
There is major difference between Null Object pattern and Option types.

Null Object is pure OOP (thus no generics) pattern, where one object implements abstract class / interface in such a way, that calling the method through the interface is same as not calling the method at all. That means the caller has no idea that type of instance is a Null object. So these two cases are equivalent:

// without null object
IInterface obj = null;
if(obj != null)
    obj.method()

// with null object
IInterface obj = new NullObject();
obj.method()

Option types on the other hand are type-safe way to ensure the caller of the method knows that there is possibility that variable might contain "no valid value". This gives compiler power to either warn or error when programmer tries to call method on variable, that might contain null.

[PSEUDOCODE (that looks like C#)]
// case A
Option<IInterface> obj = getObject();
obj.Method() // ERROR, possible "Null reference exception"

// case B
Option<IInterface> obj = getObject();
if (obj.HasValue)
    obj.Method() // OK, compiler knows that obj has valid value thanks to the if

But I believe option types don't make much sense in language, that doesn't have them as language feature (eg. most OOP languages), because compiler is not implemented as to detect such things as the first case (unless you use some kind of static code correctness checking). So you gain nothing against normal null check. Null object pattern on the other hand is natural in all OOP languages. Even those without generics.

Good example of OOP language having support of Option type is C#' Nullable. You know value types always have valid value and Nullable allows you to specify cases where variable might not contain valid value. But this is only for value types.


问:
Managing 'done' but not releasable code in TFS
I am working in an organisation with 11 scrum teams developing on the same code base.  Currently, all development is done in trunk, and at the end of a sprint everything MUST be releasable, or it must be backed out (an arduous process) as a release is cut.

My opinion is that while work in a sprint is (ideally) 'done' at the end of the sprint, this doesn't necessarily mean ready for release. You may be at a point where you do not have a Minimum Viable Product to release, but have some stories complete. If a story is not done, or the story is only part of a larger feature, it should be easy to keep this separate from the release ready code.  At the moment it is all backed out, the release cut is taken, then it is checked back in. A huge waste of time!

We use continuous integration, which is the main argument for everyone developing on trunk.  Occasionally teams use a team branch, but this is currently frowned upon.

I've been considering simply having a 'dev' and 'release' branch, and pushing features to release when they are an MVP, or having a branch for each story or feature, but this is very admin heavy in TFS. Have other people dealt with similar issues in the past, and what are your thoughts on the best way forward?  Unfortunately, we are tied to TFS in the short term.

答:
What you could do is define epic stories with substories.

Create a branch for that epic story and then branch off that one for every substory. When each substory is done, merge its branch back to the epic story branch.
When the epic is fully finished, you can merge that branch back to master and release everything.

I have to agree with Derek Davidson though; it sounds like you are building your features one part at a time, instead of incrementally (which sounds like the same thing, I know).

It reminds me of a picture I saw on Twitter about how Spotify does things. Instead of immediately building a car one wheel at a time, they went from building a skateboard, to a kick scooter, to a moped, ...

I'm aware this is easier said than done, but keep in mind that there's always a way, even if you can't see it right now. You could start by asking what the report is for and trying to reason what the absolute easiest, simplest way would be to fullfill that goal.
 It could be something completely different than a report.


问:
Develop in trunk and then branch off, or in release branch and then merge back?
Say that we've decided on following a "release-based" branching strategy, so we'll have a branch for each release, and we can add maintenance updates as sub-branches from those.

Does it matter whether we:

develop and stabilize a new release in the trunk and then "save" that state in a new release branch; or

first create that release branch and only merge into the trunk when the branch is stable?

I find the former to be easier to deal with (less merging necessary), especially when we don't develop on multiple upcoming releases at the same time. Under normal circumstances we would all be working on the trunk, and only work on released branches if there are bugs to fix.

What is the trunk actually used for in the latter approach? It seems to be almost obsolete, because I could create a future release branch based on the most recent released branch rather than from the trunk.

Details based on comment below:

Our product consists of a base platform and a number of modules on top; each is developed and even distributed separately from each other.

Most team members work on several of these areas, so there's partial overlap between people.

We generally work only on 1 future release and not at all on existing releases. One or two might work on a bugfix for an existing release for short periods of time.

Our work isn't compiled and it's a mix of Unix shell scripts, XML configuration files, SQL packages, and more -- so there's no way to have push-button builds that can be tested. That's done manually, which is a bit laborious.

A release cycle is typically half a year or more for the base platform; often 1 month for the modules.

答:
That's true - if you have multiple 'trunks', each one representing a release, then you don't need a single trunk. In fact, trunk is an arbitrary name for a 'master' branch anyway (eg in the Microsoft docs for TFS they recommend using a thing called 'Main').

But there is a good reason for developing elsewhere and using the release branches just for 'finished' code. It increases the opportunities for quality, as you can develop independently and merge your final, tested, code to several release branches. For example, you decide to update a component to a later release (you've found a security bug in it, say). You can make the change on trunk and merge that change to all your release branches instead of making the same change repeatedly. Generally this approach works, though it will get awkward as your trunk moves further away from older releases.

If you use a single trunk, you can also use feature branches which are great. Make changes to a branch, get them reviewed, and when you consider them done, merge to trunk. Lots of development can be performed independently without interfering with other developers work.

So I tend to work in a single trunk, fed from feature branches, and tagged as a release periodically, with occasional patches applied to the release as needed.


答:
Looks like you are completely borked with that lack of branching. At the very least you should be developing on a Dev branch and merging completed code onto Main when your code is working and 'releasable'. This would stop the stupidity of reverting committed work if you failed to meet your deadline and re-committing it afterward. The days of using VSS are long gone!!

Every team should have their own dev branch, but I can understand if you all want to work on a single Dev branch.

CI should be applied to both Dev and Main branches, and extra analysis on Main too - we used to put some very long running static analysis, doc generation and testing on Main that would have slowed Dev down too much.

Microsoft recommends using a Main branch (or trunk) with Dev branches and Release branches in their TFS model. (the old docs are here, though they say they are outdated.. but neglect to link to their current views)

Title: Managing 'done' but not releasable code in TFS

Body:
I am working in an organisation with 11 scrum teams developing on the same code base.  Currently, all development is done in trunk, and at the end of a sprint everything MUST be releasable, or it must be backed out (an arduous process) as a release is cut.

My opinion is that while work in a sprint is (ideally) 'done' at the end of the sprint, this doesn't necessarily mean ready for release. You may be at a point where you do not have a Minimum Viable Product to release, but have some stories complete. If a story is not done, or the story is only part of a larger feature, it should be easy to keep this separate from the release ready code.  At the moment it is all backed out, the release cut is taken, then it is checked back in. A huge waste of time!

We use continuous integration, which is the main argument for everyone developing on trunk.  Occasionally teams use a team branch, but this is currently frowned upon.

I've been considering simply having a 'dev' and 'release' branch, and pushing features to release when they are an MVP, or having a branch for each story or feature, but this is very admin heavy in TFS. Have other people dealt with similar issues in the past, and what are your thoughts on the best way forward?  Unfortunately, we are tied to TFS in the short term.