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

A contrived example of a sequential cohesion:

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

Here is the exert:

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

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

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

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

答: In my opinion above is an simple example of the sequential cohesion. If you look at the function you will notice that it contains functions which depends on the inputs and outputs of the other functions(pipeline). I don't know why there is a confusion regarding this concept.


问:
How can a developer working alone respond to a spike in server demands?
Imagine this scenario:

You've created a multiplayer game app for a mobile platform such as Android. You successfully set it up with one server, you figured out how to do that. It works quite well.

To your surprise, the game TAKES OFF. Server demands explode. You need to scale, but you have hardly any experience with running a single server, let alone running multiple servers in tandem.

What do you do? Is there a service (Heroku-style) to help with such a thing? Anything? Or do you need to hire someone with a certain skill set and the necessary experience?

答:
The first three things you want to do are profile, profile, profile.

To be able to effectively scale, you need to know exactly what it is that needs to be scaled up.  Whats the bottleneck?  Is it concurrent connections?  database access?  Heavy processor usage due to your code?  Once you find out the problem, then you can make an informed decision about what to do next.  I've seen cases where the need for new servers was averted by simply adding a few new database indexes.  Make sure you are using your current resources as efficient as possible first before adding more servers into the mix.

ContentLicense: CC BY-SA 3.0


问:
Guid collisions
I have a product that lets game developers create games. Inside of their games they are required to give all the elements of their games GUIDs. I've told them that they need to generate their guids using a specific mechanism, but they seem to think that it won't cause any issues. What I'm concerned about is GUID collisions between games.

Some developers just sequentially increment the last digit of their GUID, others zero out the last block and increment other parts, well others just pull together a random armada of numbers and letters for each one.

My argument is that by doing this it dramatically increases the risk of colliding with other games that are both following the standard, and those that don't.

Just as a heads up there are potentially hundreds of thousands of GUIDs involved here.

Am I right in thinking this, or is it really improbable that this will really happen?

答:
I've told them that they need to generate their guids using a specific
  mechanism

Are you in power? Reject code not using your mechanism.

If using the mechanism is a requirement then it's bad developers don't use it. But you might want to give them an easy implementation.

Btw. if your product lets' programmers create games why not let your product generate the guids?

Title: Guid collisions


问:
DB connection Dependency Injection and static creator methods
I often use static "factory" methods to create objects from database.

```<code>class Job {
  protected $objDb;
  public function __construct($objDb) {
    $this->objDb = $objDb;
 }

 public static function LoadArrayByProjectId($intProjectId, $objDd) {
   //some code that loads the jobs
   $objJob = new Job($objDb);
   $arr[] = $objJob;
   //end of loop
   return $arr;
 }

 public static function LoadArrayByUserId($intUserId, $objDb) {
   //similar code
 }
</code>```

}

So I try to use Dependency Injection by passing into the constructor the $objDb. The problem is the $objDb param in the static functions. It's very annoying to pass the param around.

How do you handle this case? Are there better solutions?

答:
The fact that it looks odd to you may be a sign that it shouldn't be static. You can instead encapsulate the loader methods into a non-static class which also takes the database object in the constructor. To me this creates a more natural form of dependency injection (same way you did the Job class). The object asks for everything it needs to get the job done in the constructor and it doesn't have to be passed into each method.</p>

```<code>class Loader {
    protected $objDb;

    public function __construct($objDb) {
        $this->objDb = $objDb;
    }

    public function LoadArrayByUserId($intUserId) {
    }

    public function LoadArrayByProjectId($intProjectId) {
    }
 }
</code>```

Body:
The fact that it looks odd to you may be a sign that it shouldn't be static. You can instead encapsulate the loader methods into a non-static class which also takes the database object in the constructor. To me this creates a more natural form of dependency injection (same way you did the Job class). The object asks for everything it needs to get the job done in the constructor and it doesn't have to be passed into each method.

class Loader {
    protected $objDb;

    public function __construct($objDb) {
        $this->objDb = $objDb;
    }

    public function LoadArrayByUserId($intUserId) {
    }

    public function LoadArrayByProjectId($intProjectId) {
    }
 }


问:
Business issues in the issue tracker?
Most issue trackers are targeted towards developers.  But when working in a small team that includes business people: does it makes sense for them to put non-dev issues inside the tracker?

I must say I have never heard of that combination.  In my full-time job the business things are done somewhere else.  But in a startup where you have limited cash, why not put business todos and dev todos in the same tracker?

答:
I would keep a tracker to maintain issues raised by business users. This is especially useful when doing requirement gathering. You might want to use the same tracker when you do user acceptance testing to tick-off existing issues or gather feedback from users.
I have mostly used multiple excel sheets in same workgroup to maintain various issues(dev issues in one sheet, business issues in another). </p>

Title: Business issues in the issue tracker?


问:
Building a web application that is almost completely rendered by Javascript, while back end only delivers Json. Do or don't?
As a programmer, and taking into account the overall "funness" of the process, I'm tempted to start a project in Sinatra where the back end's sole concern is the logic, and returning a Json API, and then writing a javascript application that would interact with that API for rendering the actual content to the user.

I'm fairly new to programming and I've never done anything remotely like this before. What would be the pitfalls, advantages and disadvantages of completely separating logic from presentation in such a way? Any examples of this being done in the wild?

One concern off the top of my head is how would search engines respond to a site whose content is almost entirely served as Json...

答:
Most of the web apps I've written for my firm works this way -- a single page, javascript driven application making ajax calls to a back-end service.

So when I started my own website, my first implementation was done the same way. However, more than halfway through the development, I realized I made a big mistake.

My website offers content to my users, and this content needs to be available via search engines. I also need to monetize my website via ads. The problem is that both these requirements depend on the static content avaiable from the website.

Static content is required to index keywords for search and to display relevant ads. These keywords are fetched from the text found in the underlying HTML. If your content is fetched from a remote source and displayed via javascript, it's likely that your underlying HTML would be mostly blank.

Because they provide a rich client experience, dynamic pages are ideal for web-based applications. However, if you intend to deliver content, it's best to avoid dynamic pages.


答:
To me, as long as there are appropriate filters and queues (so developers are not overwhelmed with tickets about "call Bob about new contract") combining them makes sense.

In my line of work (financial software for external clients), most of the dev issues will require prioritisation from the business anyway. At the end-of-the-day, they are all issues with the client relationship (does the software do what the client wants or is there a bug? have we found an issue in the code which will make the code less maintainable and affect our ability to keep clients happy in future? does client need a new contract?)

The combined approach may also help find non-technical solutions to technical bugs

Title: Business issues in the issue tracker?

Body:
Most issue trackers are targeted towards developers.  But when working in a small team that includes business people: does it makes sense for them to put non-dev issues inside the tracker?

I must say I have never heard of that combination.  In my full-time job the business things are done somewhere else.  But in a startup where you have limited cash, why not put business todos and dev todos in the same tracker?


答:
By all means, it's worth trying out, but know that the learning curve can be a bit steep at times (Javascript is an easy language to hate.) Javascript web apps have some really nice features. For example, you can port your app to various mobile devices as native apps by wrapping the application with Phonegap.

There are a handful of options as far as frameworks go. I'd read over this article to get a high level overview of some of the more popular options: http://sporto.github.io/blog/2013/04/12/comparison-angular-backbone-can-ember/

As for search engine crawl-ability, I think (though I'm not 100% on this) that you can make some of the different "pages" of your app crawlable using what's called a "router" (that may be specific to Backbone.js though, and I could be wrong, I think that that's the case.) You can definitely use the Backbone "router" to make the different "pages" bookmarkable and linkable so it makes sense that they'd also be crawlable.

Title: Building a web application that is almost completely rendered by Javascript, while back end only delivers Json. Do or don't?

Body:
As a programmer, and taking into account the overall "funness" of the process, I'm tempted to start a project in Sinatra where the back end's sole concern is the logic, and returning a Json API, and then writing a javascript application that would interact with that API for rendering the actual content to the user.

I'm fairly new to programming and I've never done anything remotely like this before. What would be the pitfalls, advantages and disadvantages of completely separating logic from presentation in such a way? Any examples of this being done in the wild?

One concern off the top of my head is how would search engines respond to a site whose content is almost entirely served as Json...


答:
The absolute best approach would be to have a framework, cms or such where you store and access the same content with both ajax and entire page load. Have the same function run when on going into the site's frontpage aswell and navigating to the front's through javascript.

By clever use of .pushState(), overriding onclick through jQuery on links, you can have a site that has the right links, but often uses ajax for loading new pages. The fallback in case push state isn't supported is there aswell; the user simple navigates to the page instead of jQuery and ajax overriding the onclick effect.

This approach will also be loved by SEO since it can navigate your content freely aswell. To mention an example, consider my own gallery. You can navigate to the previous image by pressing on the image's left side. This will run a .pushState() and load the content through ajax. However you can take the "new" page, link it to me and it gives me the previous image. SEO also only see the correct link aswell and doesn't have to worry about ajax and such.


问:
Architecture for writing add-ins for closed-source software
currently I'm designing an add-in for the modelling tool Enterprise Architect. The general architecture is shown in the picture below.

Basically every action where the add-in can react to is triggered by PreDefinedEvents for which the add-in can provide callback functions. These callback functions are the starting point for building whatever application someone would like to put on top EA. One has access to the Model Database (.mdb file) through the API (which uses closed-source algorithms) or by direct access, which can cause of course inconsistencies and is not safe against DB structure changes.

The current approach from previous projects was to build monolithic classes called EA_XXX_Utilities containing a huge amount of static methods. All of these methods get as argument a reference to the model repository which is stored inside the Closed Source and work with it.

I think that this approach is not very handy related to maintainability and extendability, which will have high priority in future projects, so I'm trying to find the best way which let's me fulfill the requirements according to these quality aspects.

Every requirement basically consists of two parts:

modify the underlying model

present parts of the model in a custom way

This smells for me like a kind of MVC architecture, but my major problem is that if I stored the reference the the Model Repository somewhere in my application then I would have to somehow get notified of all changes which the closed source algorithms do to the database. But not all of them are forwarded to the add-in, so at some time the model stored in the add-in will get inconsistent.

This leads to the question:

How can I design the add-in, so that it has some architecture in it at all and even better satisfy the quality aspects?

答: I took the suggestion of Robert Harvey to organize the classes to functional areas. What I came up with as an overall structure is the following:


问:
How can I quickly weed out "copy & paste" coders?
I need a way to filter out resumes of folks who just copy-and-paste code then hope it works, and check it in if it does.  All this happens without having an understanding (or care) to understand the rest of the code in the system.

Sure I know that copying and pasting code is part of learning a new object, control, etc... but how can one tell if that accounts for 70% (or more) of their development career?

I've come across some senior level guys perhaps whose skills are so outdated or irrelevant for the project, that all they do is google, copy-then-paste some code without thinking about the solution as a whole.  As a result we have a mismash of JSON, AJAX, callbacks, ASMX, WCF and postbacks in the same project.  It is clear there is no consistency or logic behind where each technology is being used.

In the worst case, this type of developer creates security issues and vectors for attack.

Question

How would you recommend I filter out people who have a poor programming background?  Can I do it at the resume level?  If not, how do I do this during the interview.

答:
The way to weed out programmers who cannot program is to set them a practical programming exercise as part of the screening phase or interview phase.  (The latter is probably better because you can control the environment to prevent cheating.)

But I don't think that is really going to address your problem.

... we have a mismash of JSON, AJAX, callbacks, ASMX, WCF and postbacks in the same project. It is clear there is no consistency or logic behind where each technology is being used.

IMO, the real problem here is that your team is not doing enough internal code review, and not developing a "play book" of preferred solutions to known problems.  This is partly a culture issue, partly a communication issue, and (probably) partly an issue with project deadlines.

Another issue is that project typically has a long lifespan, and during that lifespan, new technologies / techniques will appear, and old ones are likely to fall out of favor.  If you want to avoid a "dogs breakfast" use of technologies / techniques, you need to either:

set and enforce a list of technologies / techniques that may be used per project, or

invest effort in refreshing the technologies used by a project.

ContentLicense: CC BY-SA 2.5


问:
How can I quantify the amount of technical debt that exists in a project?
Does anyone know if there is some kind of tool to put a number on technical debt of a code base, as a kind of code metric?  If not, is anyone aware of an algorithm or set of heuristics for it?

If neither of those things exists so far, I'd be interested in ideas for how to get started with such a thing.  That is, how can I quantify the technical debt incurred by a method, a class, a namespace, an assembly, etc.

I'm most interested in analyzing and assessing a C# code base, but please feel free to chime in for other languages as well, particularly if the concepts are language transcendent.

答:
Here is a Webinar out of MIT describing research on technical debt in large software systems:
http://sdm.mit.edu/news/news_articles/webinar_050613/sturtevant-webinar-technical-debt.html

The authors wrote code to analyze a project and pull out 'architectural complexity' metrics.  These metrics were shown to have a strong relationship with defect density, developer productivity, and development staff turnover.

The work described in the Webinar builds on modularity research done by Alan MacCormack and Carliss Baldwin at Harvard Business School.  I would look at their papers as well.  Their  'propagation cost' might be what you are looking for.


问:
Unit-Testing functions which have parameters of classes where source code is not accessible
Relating to this question, I have another question regarding unit testing functions in the utility classes:

Assume you have function signatures like this:

```<code>public function void doSomething(InternalClass obj, InternalElement element)
</code>```

where InternalClass and InternalElement are both Classes which source code are not available, because they are hidden in the API. Additionally, doSomething only operates on obj and element. I thought about mocking those classes away but this option is not possible due to the fact that they do not implement an interface at all which I could use for my Mocking classes.

However, I need to fill obj with defined data to test doSomething.

How can this problem be solved?

答:
Here is a trick that sometimes works in cases like that: in your testing assembly, do not reference the assembly containing doSomething. Instead, reference the source code file containg doSomething, and provide your own InternalClass / InternalElement implementation (which serves as a mock) in that testing assembly . Of course, your InternalClass must expose exactly the same public method signatures as the original one, at least to the degree that you can compile the test code. It should be obvious that you also have to use the same namespace as the original class.

I have used this technique sucessfully for testing legacy code even though I had the source code available, but did not want to touch it.


问:
Lazy loading if collection would have any entries
I often see model classes with properties like this:

```<code>public IList<Note> Notes { get; set; }
public bool HasNotes { get; set; }
</code>```

Where the list is initialized lazy, but the boolean property is loaded directly.
This has the benefit, that only the count is loaded, when the collection is not needed, but the caveat is that the value for the boolean property is always calculated.

This made me think and I came up with a solution like this:

```<code>public IList<Note> Notes { get; set; }
public bool HasNotes
{
  get
  {
    if (Notes != null) return Notes.Any();
    else // calculate (e.g. sql exists)
  }
}
</code>```

This way the calculation would only happen if the collection is not loaded.

Would this be a good approach?
Does there already exist different best practices unknown to me?

答:
You can never know how users plan to use your code. In your proposal, if a caller first looks up HasNotes and only later Notes, you'll have one SQL call too many as well: first the COUNT, and then the entire SELECT to populate Notes.

If you do know that users will never call HasNotes before Notes, then your implementation make sense, but in that case, I'd suggest going all the way in that direction.

For instance, instead of trying to be smart about queries by guessing usage patterns in a model, you could make an explicit data access layer that performs exactly the right queries that are needed, and populates the model classes. The model classes are then reduced to simple data-holder classes. They might contain domain logic and validation logic and all that, but certainly no knowledge of the DB.

This is really the ORM vs DAO debate. Fowler has a nice short discussion of this debate here.

In general, I'd choose a clear approach:

Try to be as automatically-smart as possible in the model classes. This is the NHibernate way. It yields an easy-to-use model layer that generates just a few queries too many. In that case, leave the smart stuff up to NHibernate and don't try to optimize your model classes prematurely.

Don't even try to be smart, but leave it to the "user" to call the right methods that populate the model.

I feel that the approach you suggest is somewhere in the middle ("It's an optimization, but only if you call things this and this way"). This will confuse other developers, and yourself in a few months. Better to take a clear stance.


答:
Hire people on 3 month probation. Fire them if they suck.

If you don't INSPECT you can't EXPECT. Code reviews, audit tools. A CI server can run these automatically.

Ask real questions in your interviews, as in questions from real code.

Get them to write code on the whiteboard.

If you are a non-technical manager, you are unqualified to judge this.

If you are unqualified, get a reputable senior professional consultant to do the testing.
Ask your existing people, and business competitors if they know a 100x productive person.
Pay them to do the interviewing.

If you want to run a hospital without a head of surgery, go right ahead.

Title: How can I quickly weed out "copy & paste" coders?

Body:
I need a way to filter out resumes of folks who just copy-and-paste code then hope it works, and check it in if it does.  All this happens without having an understanding (or care) to understand the rest of the code in the system.

Sure I know that copying and pasting code is part of learning a new object, control, etc... but how can one tell if that accounts for 70% (or more) of their development career?

I've come across some senior level guys perhaps whose skills are so outdated or irrelevant for the project, that all they do is google, copy-then-paste some code without thinking about the solution as a whole.  As a result we have a mismash of JSON, AJAX, callbacks, ASMX, WCF and postbacks in the same project.  It is clear there is no consistency or logic behind where each technology is being used.

In the worst case, this type of developer creates security issues and vectors for attack.

Question

How would you recommend I filter out people who have a poor programming background?  Can I do it at the resume level?  If not, how do I do this during the interview.


问:
What were the Design Patterns of the procedural programming era?
Similar: How was programming done 20 years ago?

OOP is quite fashionable nowadays, having its roots in Simula 67 in the 1960s, and later made popular by Smalltalk and C++. We have DRY, SOLID, many books about design patterns in the object-oriented world.

But what were the main principles in programming prior to the OOP paradigm wide adoption? And what were the major design patterns?

答:
"Design patterns" in software didn't exist in the era you talk about, because the concept hadn't been invented. This is not me being flippant - it actually is the reason; being called a recognizable name is what makes a Design pattern a "Design pattern" rather than just code that you keep using in one form or another (e.g. a "Factory" rather than "the kind of static class that I like to use rather than an assortment of constructors") and the concept itself is no exception.

That said, of course there were things that fulfilled exactly the same role in the work of practitioners as design patterns do now. But you'll be disappointed in hearing about them: typical "trick of the gurus" in those days were things that are quite boring to us now - e.g. singly-linked lists, loops controlled by an index incremented on each iteration, clever "accessor" methods that seem to do nothing but give you leeway in changing your mind about implementation details later.

That's right, things that we now take for granted - that are sometimes even part of the languages we use - used to be advanced (and sometimes jealously guarded) concepts known only by more experienced coders. Chances are, almost everything not utterly trivial that you learn in a basic programming course today went through a phase where it was the moral equivalent to a "Design pattern" to the practitioners of the age. Software construction may not be a rigorous engineering discipline yet, but if you study the state of the art of the 50s and 60s, you can't deny that it has come an enormous way since its beginnings.


答:
I suppose one large one (besides structured programming itself) was the concept of passing a handle around - in OO you have an object and it contains state and functionality. Back before OO, you'd have a load of independent functions, and you'd pass a handle to some state between them - a cookie if you like. This gave you OO principles without actually having OO.

You can see this a lot in old Win32 code, you'd pass in a HANDLE which would be an opaque type representing some state allocated in the Windows kernel. You could it yourself by passing a pointer to a struct you'd previously allocated as the first parameter to functions that operated on that data.

Title: What were the Design Patterns of the procedural programming era?

Body:
Similar: How was programming done 20 years ago?

OOP is quite fashionable nowadays, having its roots in Simula 67 in the 1960s, and later made popular by Smalltalk and C++. We have DRY, SOLID, many books about design patterns in the object-oriented world.

But what were the main principles in programming prior to the OOP paradigm wide adoption? And what were the major design patterns?


答:
why not. Redmine (for example) comes with 3 trackers out of the box and allows you to create more. The 3 are bug, feature and support.

bug is obvious, but is feature request a developer thing, or more a design/management issue? What of support - it might not be a bug but a configuration issue.

You can easily add Requirement to the list.

The benefit of adding all these to the same tracker tool is that you can then link them together. Imagine someone creates a feature request that goes through several modificatons through discussion with architects or designers. When management decides to implement this, it can be associated with a 'work' tracker item for you to check your source against, and then associate it with a 'test' tracker as it goes through QA, and then can be associated with support or bug items in the future.

This is called 'traceability' and is huge thing with large scale or very controlled software projects. As long as you don't add onerous workflows to it (ie only a team lead can create a work item, etc) then its a very good thing.

Title: Business issues in the issue tracker?


问:
What is the exact meaning of Platform independence?
What is the meaning of platform independence?

I am taking the case of Java. Can I run a Java application on Linux that built on Windows platform? Or the reverse?

Can I use a same (or exact) programming algorithm on both operating systems?

In my view File Types are platform independent like Videos, Images, Documents etc.

答:
JAVA is an object oriented platform independant programming language.
The javac compiler compiles source code and produces Byte code language (universal language).

This language is not understandable by any operating system, it has to be processed first, and this is where a special executable program (JVM) enters the scene. An interpreter of the JVM reads the bytecode line by line and converts the byte code instructions into machine-specific understandable language (ultimately binary code). So, the byte code is platform independent but the interpreted code is machine-specific and will execute on the environment the JVM is installed on. JAVA programs are platform-independant means that JAVA is platform independant.

Sun MicroSystems slogan was WORA: Write Once Run Anywhere.


答:
If it's not too late to change some of your own code you could wrap the InternalClass and InternalElement and provide an interface for the wrapper so that the wrapped object can be easily mocked (essentially the adapter pattern).

If you don't control these classes it's probably a good idea to wrap them anyway to isolate changes in them from your code.

Title: Unit-Testing functions which have parameters of classes where source code is not accessible

Body:
Relating to this question, I have another question regarding unit testing functions in the utility classes:

Assume you have function signatures like this:

```<code>public function void doSomething(InternalClass obj, InternalElement element)
</code>```

where InternalClass and InternalElement are both Classes which source code are not available, because they are hidden in the API. Additionally, doSomething only operates on obj and element. I thought about mocking those classes away but this option is not possible due to the fact that they do not implement an interface at all which I could use for my Mocking classes.

However, I need to fill obj with defined data to test doSomething.

How can this problem be solved?


问:
Is a CPU a computer?
I read that a computer is made up of the CPU and the memory. I also read that the CPU itself contains a cache which is memory. So if the CPU itself contains the memory, isn't the CPU a computer?

Please clarify, thanks.

EDIT: I read here: http://www.dwightsilverman.com/future.htm it says:

A processor is, itself, a computer, and they now are small enough that they are embedded in everything from car engines to toasters. Although these processors are relatively dumb, designed to do just one thing, smarter processors that are more versatile also are finding their way into tiny places.

答:
This really all depends on how you are defining a CPU. If you are talking about the embedded CPUs found in many of the devices you use, then yes, they often contain both the RAM and the processing units that would make up a common computer. If you are talking about a CPU that you would find in a consumer desktop/laptop you would see that the cache you are referring to is usually very small and only used to buffer instructions to the core, thereby reducing downtime, as calls to the main memory (RAM) are very expensive. They would be very very limited in what you could do if you ONLY had the cache on those cpus, but they could technically still be called whole computers.

This all comes from the fact that in the days of old, the mathematical units were separate from the memory manager, which was separate from the memory, which was separate from the logic units. each of these units by itself was incapable of doing the whole job itself, and thus was not a 'computer.' as we think of it today. Without memory, your logic and mathematical units wouldn't have anyone to get instructions from. Today's computers are very far removed from being a collection of separate entities on a chip, as the more integrated you make them, the more performance you can achieve.

Title: Is a CPU a computer?


答: If you have a good history via a bugtracker or some sort of agile software you can keep it simple. Time spent completing basic tasks. Also, reliability of estimates when the project was young vs. now.</p>

Title: How can I quantify the amount of technical debt that exists in a project?

Body:
Does anyone know if there is some kind of tool to put a number on technical debt of a code base, as a kind of code metric?  If not, is anyone aware of an algorithm or set of heuristics for it?

If neither of those things exists so far, I'd be interested in ideas for how to get started with such a thing.  That is, how can I quantify the technical debt incurred by a method, a class, a namespace, an assembly, etc.

I'm most interested in analyzing and assessing a C# code base, but please feel free to chime in for other languages as well, particularly if the concepts are language transcendent.


问:
Is browser fingerprinting a viable technique for identifying anonymous users?
Is browser fingerprinting a sufficient method for uniquely identifying anonymous users? What if you incorporate biometric data like mouse gestures or typing patterns?

The other day I ran into the Panopticlick experiment EFF is running on browser fingerprints.

Of course I immediately thought of the privacy repercussions and how it could be used for evil. But on the other hand, this could be used for great good and, at the very least, it's a tempting problem to work on.

While researching the topic I found a few companies using browser fingerprinting to attack fraud. And after sending out a few emails I can confirm at least one major dating site is using browser fingerprinting as but one mechanism to detect fake accounts. (Note: They have found it's not unique enough to act as an identity when scaling up to millions of users. But, my programmer brain doesn't want to believe them).

Here is one company using browser fingerprints for fraud detection and prevention:

http://www.bluecava.com/

Here is a pretty comprehensive list of stuff you can use as unique identifiers in a browser:

http://browserspy.dk/

答:
Javascript is not mandatory a there are many other parameters to sniff from PHP.
That said, 99% of the user have JS so why bother

Can fingerprinting provide a unique-enough identification ? I believe so.
And so says www.visitor-intelligence.com with its successive screening philosophy .
Think about it.

Your personal private galaxy is not as large as our whole planet.

How many tall, brown hair, blue eyes girl with a French accent walks in your street ?
On a planet scale, millions. But I bet she would be pretty unique in your street (or visiting your shop).

Unless you live in Champs Elysees. Then look closer. Is she slim and walks like a model ? Does she wear an expensive handbag ? All right, she is totally unique now :-)

Looking purely at headers is wrong because it includes the version number of browser and more very variable parameters.

We are now at Chrome 27 and Firefox 21. We are updating browsers version without even noticing.

Now, looking at full plugin list is also quite wrong. Try that : install firefox, install acrobat reader, then install Chrome. I bet acrobat reader won't show in your Chrome plugin list :-)

So... Bottom line is : if you look for a decent identification sytem for a standard-size shop, then fingerprinting is way enough, and even more stable than cookies (I personally delete all my cookies almost every day).

Just my 2 cents


答:
Would this be a good approach?

I think a better approach would be to always load HasNotes together with the rest of the entity. That way, the property is basically free (one more returned column should be much cheaper than making another SQL query for each entity).

Title: Lazy loading if collection would have any entries

Body:
I often see model classes with properties like this:

```<code>public IList<Note> Notes { get; set; }
public bool HasNotes { get; set; }
</code>```

Where the list is initialized lazy, but the boolean property is loaded directly.
This has the benefit, that only the count is loaded, when the collection is not needed, but the caveat is that the value for the boolean property is always calculated.

This made me think and I came up with a solution like this:

```<code>public IList<Note> Notes { get; set; }
public bool HasNotes
{
  get
  {
    if (Notes != null) return Notes.Any();
    else // calculate (e.g. sql exists)
  }
}
</code>```

This way the calculation would only happen if the collection is not loaded.

Would this be a good approach?
Does there already exist different best practices unknown to me?


问:
Use ILmerge for NuGet libraries?
I'm making an open source C# library (http://github.com/eteeselink/fakethat if you must). Like is fashionable these days, I plan to spread it via NuGet.

My library depends on another library (Castle.Core). Before the NuGet days, I'd use a tool such as ILMerge to merge my library and Castle.Core into a single assembly, so that the distribution is simpler. This significantly increases the size of my assembly (from 50kb to 450kb), but it's only a single DLL, which is handy for users.

Now that there's NuGet, however, I can simply add Castle.Core as a dependency and NuGet will resolve it for my users. This has a few advantages:

It is simpler and less error prone for me

If my users use another library that depends on Castle.Core, we save disk space

It somehow feels more "honest" - all the hard work is done by Castle.Core, all I added is a pretty API.

There's a few disadvantages, too, however:

If Castle.Core somehow gets removed from NuGet, my library will stop working

If someone still wants to use my library without NuGet, it's a bigger hassle because multiple DLLs need to be copied around

If a developer looks through the list of project references, she will see some weird "Castle.Core" reference that she never remembers having added. This might be confusing.

What would you do?

答:
There is at least one advantage you didn't mention:

If Castle is updated with a bug-fix release on NuGet, the user is going to get that updated version.

If you combine all the advantages together, I think they outweigh the disadvantages. So, I think you should just add the reference to the Castle package to your package and be done with it.

Title: Use ILmerge for NuGet libraries?


问:
What is "short-circuiting" in C like languages?
I have heard of the term "short-circuiting" being used in C, C++, C#, Java, and many others. What does this mean and in what scenario would it be used?</p>

答:
Short ciruit evaluation can lead to some parts of a condition not be evaluated.

For example:

```<code>if (true || f()) { ... }
</code>```

will not exectue f.

Body:
Short ciruit evaluation can lead to some parts of a condition not be evaluated.

For example:

if (true || f()) { ... }

will not exectue f.


答:
Short circuiting in C is when a logical operator doesn't evaluate all its arguments.

Take for example and &&, it's pretty obvious that 0 && WhoCares is going to be false no matter what WhoCares is. Because of this, C just skips evaluating WhoCares. Same goes for 1 || WhoCares, it'll always be true. Because of this, we can write code like

```<code>CanFireMissiles && FireMissiles()
</code>```

This way we avoid doing some potentially impossible operation. If we can't fire the missiles we certainly don't want to try to. This is commonly used with pointers, especially file pointers.

```<code> bool isN(int* ptr, int n){
     return ptr && *ptr == n;
 }
</code>```

This plays out in lots of other useful ways to avoid unnecessary computing

```<code> isFileReady() || getFileReady()
</code>```

This avoids doing extra work if we don't need to.

Title: What is "short-circuiting" in C like languages?

Body: I have heard of the term "short-circuiting" being used in C, C++, C#, Java, and many others. What does this mean and in what scenario would it be used?</p>

Body:
Short circuiting in C is when a logical operator doesn't evaluate all its arguments.

Take for example and &&, it's pretty obvious that 0 && WhoCares is going to be false no matter what WhoCares is. Because of this, C just skips evaluating WhoCares. Same goes for 1 || WhoCares, it'll always be true. Because of this, we can write code like

CanFireMissiles && FireMissiles()

This way we avoid doing some potentially impossible operation. If we can't fire the missiles we certainly don't want to try to. This is commonly used with pointers, especially file pointers.

 bool isN(int* ptr, int n){
     return ptr && *ptr == n;
 }

This plays out in lots of other useful ways to avoid unnecessary computing

 isFileReady() || getFileReady()

This avoids doing extra work if we don't need to.


问:
embedding programming languages into other languages
In C/C++, there is a keyword that allows you to enter assembly language directly into a method.

Example

```<code>int Main()
{
    __asm // notify the compiler that this block is assembly language.
    {
        push ax;
        xor ax, ax;
        int 33h;
        mov ax, 1;
        int 33h;
        pop ax;
        retf;
    }

    return 0;
}
</code>```

Believe it or not, my memory has this little snippet of assembly language imprinted for life, or at least until I become senile! It's a little old-school DOS command that calls the mouse interrupt and shows the mouse cursor. That aside, depending on the C/C++ compiler in question, this would be compiled to run on execution of the Main() method.

A few years on, I am a C# and JavaScript developer...can you guess where I'm going with this?

In ASP.NET, We can develop the server-side functionality of a web application with C# (or other .NET languages), and the client-side functionality with JavaScript.

Sometimes we need to be able to pass JavaScript scripts to the client, from the server, because the server is going to provide some information which will be required by the script. Currently these need to be written as strings, which can cause  a headache when it comes to debugging!

Example

```<code>string js = "function test() { alert(\"" + message + "\"); }";
aspLiteral.Text = ScriptWrapper.Wrap(js); //assume this just wraps a script into a <script> tag.
</code>```

What if we could enter JavaScript directly into the server-side code, thus giving more exposure to the debugger,  intellisense, code-completion etc.

Example

```<code>DateTime x = DateTime.Now;
string message = "Hello World";
var script = javascript //special keyword notifies the compiler that this block is JavaScript.
{
    function test() {
        alert(@message); //Tell the compiler to evaluate C# message to JS message
        var x = @x; //Tell the compiler to evaluate C# x to JS x
    }
}

aspLiteral.Content = ScriptWrapper.Wrap(script);

// output

<script type="text/javascript">
    function test() {
        alert("Hello World");
        var x = \/Date(1371561853440)\/;
    }
</script>
</code>```

I know this seems like a monumental mountain to climb, possibly to the point of insanity...Am I the only one who thinks this could be useful, or, does its, somewhat limited use, just not warrant the implementation of this into future compilers / IDEs?

答:
You're clearly not the only one who finds this useful, as it is done all over the place as you've shown above. From putting compiler optimized code into methods for speed, to using scripting languages for their simplicity, people have been co-mingling code for quite a while. The real trick here though, is getting the compiler to know what the heck you're trying to do.

Most compilers are made to interpret 1 language, that is the one they are designed for. The reason that the ASM keyword works so well in C is that ASM is an intermediary step for the C compiler, that is it puts all the C code it finds into ASM equivalents, so when you specify with the __asm keyword, you're saying "Hey compiler, don't worry about turning this into assembly, I've done that for you!" and the compiler goes on its merry way inserting your premade code wherever it needs it before converting it to binary.

When you're doing things like assembling javascript inside of java, that gets more complicated. Why? Because javascript is NOT an intermediary step from java to binary. This means that not only does the compiler have to be able to read java, it has to be able to read javascript as well! On top of that, it has to know how to integrate the two of them when their only common step is binary! As you can see, this gets a little more tricky. That's often the reason that the javascript is put into strings, as it is often passed off to another method that will interpret the javascript and then turn that into java, which the compiler then recognizes and compiles.

So to sum it up, if you want to be able to do this, every compiler would need to be able to successful interpret N languages, where N is the number of different languages you would use in each source file. It'll work for 1 or 2 languages, but when you start getting into 3+ you're looking at exponential code growth. What happens if language 2 is nested in language 3 which is nested in language 1? How does the compiler interpret that? It seems simple on a case by case basis, but coming up with some pre-defined algorithm to automatically sort those kinds of problems out is no small task.


答:
"Short Circuiting" typically refers to "Short Circuit Evaluation" which is a general concept, not just C specific.

Boolean operators evaluation left to right, so any terms that will render the other terms unnecessary are useful. So you might check for a condition that excludes other conditions later on, thus allowing a partial evaluation of the logical operations rather than evaluating the whole thing.

Example:

while((x && y) == 1) {
    //This bit will not execute if x is 0 or y is 0 but y won't even be
    //evaluated due to short circuit evaluation if x is 0.
}
```

<p>A more complex example:</p>

<pre class="lang-c prettyprint-override"><code>if((a || b || c || d || e || f || g || h || i || j || k) == 1) {
    /* If any of these are equal to 1 the whole expression is equal to 1,
     * thus doesn't it make sense to short circuit evaluate this?
     * Saves a bunch of time.
     */
}
</code>```

Body:
"Short Circuiting" typically refers to "Short Circuit Evaluation" which is a general concept, not just C specific.

Boolean operators evaluation left to right, so any terms that will render the other terms unnecessary are useful. So you might check for a condition that excludes other conditions later on, thus allowing a partial evaluation of the logical operations rather than evaluating the whole thing.

Example:

while((x && y) == 1) {
    //This bit will not execute if x is 0 or y is 0 but y won't even be
    //evaluated due to short circuit evaluation if x is 0.
}

A more complex example:

if((a || b || c || d || e || f || g || h || i || j || k) == 1) {
    /* If any of these are equal to 1 the whole expression is equal to 1,
     * thus doesn't it make sense to short circuit evaluate this?
     * Saves a bunch of time.
     */
}


答: This is exactly what ASP.NET (or the more modern Razor) already does, only in reverse. So, you can't easily have C# with inline JS, but you can have JS/HTML with inline C#, which I think will work just as well.</p>

Title: embedding programming languages into other languages

Body:
In C/C++, there is a keyword that allows you to enter assembly language directly into a method.

Example

```<code>int Main()
{
    __asm // notify the compiler that this block is assembly language.
    {
        push ax;
        xor ax, ax;
        int 33h;
        mov ax, 1;
        int 33h;
        pop ax;
        retf;
    }

    return 0;
}
</code>```

Believe it or not, my memory has this little snippet of assembly language imprinted for life, or at least until I become senile! It's a little old-school DOS command that calls the mouse interrupt and shows the mouse cursor. That aside, depending on the C/C++ compiler in question, this would be compiled to run on execution of the Main() method.

A few years on, I am a C# and JavaScript developer...can you guess where I'm going with this?

In ASP.NET, We can develop the server-side functionality of a web application with C# (or other .NET languages), and the client-side functionality with JavaScript.

Sometimes we need to be able to pass JavaScript scripts to the client, from the server, because the server is going to provide some information which will be required by the script. Currently these need to be written as strings, which can cause  a headache when it comes to debugging!

Example

```<code>string js = "function test() { alert(\"" + message + "\"); }";
aspLiteral.Text = ScriptWrapper.Wrap(js); //assume this just wraps a script into a <script> tag.
</code>```

What if we could enter JavaScript directly into the server-side code, thus giving more exposure to the debugger,  intellisense, code-completion etc.

Example

```<code>DateTime x = DateTime.Now;
string message = "Hello World";
var script = javascript //special keyword notifies the compiler that this block is JavaScript.
{
    function test() {
        alert(@message); //Tell the compiler to evaluate C# message to JS message
        var x = @x; //Tell the compiler to evaluate C# x to JS x
    }
}

aspLiteral.Content = ScriptWrapper.Wrap(script);

// output

<script type="text/javascript">
    function test() {
        alert("Hello World");
        var x = \/Date(1371561853440)\/;
    }
</script>
</code>```

I know this seems like a monumental mountain to climb, possibly to the point of insanity...Am I the only one who thinks this could be useful, or, does its, somewhat limited use, just not warrant the implementation of this into future compilers / IDEs?


答:
I was a Cobol developer before I learned Java.  I've developed for over 35 years.

Back in the days of procedural languages, most of the processing was done in batch.  Go back far enough in history, and even program compilation was done with a deck of punch cards in batch.

Contrary to Kilian Foth's assertion, we had design patterns back in the 1970's and 1980's.  There was a certain way to code a multi-file match/merge in Cobol.  There was a certain way to code adding transactions to the master (tape) file in Cobol.  There was a certain way to code report generation in Cobol.  That's why IBM's Report Writer never really gained traction in a lot of Cobol shops.

There was an early application of the DRY principle. Create lots of paragraphs so you don't repeat yourself.  Structured coding techniques were developed in the 1970's and Cobol added structured words (verbs) to the language in 1985.

Generally, when we wrote a new Cobol program, we copied an old Cobol program and changed the names to protect the innocent.  We almost never coded a Cobol program from a blank sheet of paper or a blank screen.  That's a big design pattern when you can copy and paste entire programs.

There were so many Cobol design patterns that it took years for a Cobol programmer to learn them all.  That's one reason that the Cobol programmers today are, for the most part, still using 1985 syntax.


问:
How to sync clocks over networking for game development?
I'm writing a game that has a lot of time based aspects. I use time to help estimate player positions when the network stalls and packets aren't going through (and the time between packet's being received and not). It's a pacman type game in the sense that a player picks a direction and can't stop moving, so that system makes sense (or at least I think it does).

So I have two questions: 1) How do I sync the clocks of the games at the start since there is delay in the network. 2) Is it okay NOT to sync them and just assume that they are the same (my code is time-zone independent). It's not a super competitive game where people would change their clocks to cheat, but still.

The game is being programmed in Java and Python (parallel development as a project)

答:
How do you know which player's clock is correct? You don't, so use a reference clock.

NTP is overkill here - you only need ~1 second accuracy - so use rdate or pick something from one of many clock synchronisation algorithms.

One you've chosen a method, get each player's machine to pick up the time per that method (without changing their system clock). Whatever difference there is between the reference UTC time and the players' system clock UTC time is their effective offset. Any time you do time-related calculations to e.g. extrapolate bot movements or ray-trace bullets, you factor in this offset after getting the system time. Using UTC will eliminate timezone factors.


答:
The previous big paradigm was structured programming.  Instead of UML, there were a variety of different diagrams (flow charts, data-flow diagrams, structure charts, etc).  Development was mostly top-down, and followed a process of functional decomposition.  One of the basic ideas was that your program structure should resemble a diamond: The main module at the top, fanning out into high-level control modules, which invoked routines in lower-level modules.  These lower-level modules built on still lower-level modules, all of which (theoretically) eventually converged on a handful of basic I/O routines.  High-level modules were supposed to contain the program logic, lower-level ones were more concerned with data integrity and error handling.

Important concepts introduced during this time were information hiding, modularity and high cohesion/low coupling.  See the works of Dave Parnas for some seminal papers on these topics.  Also check out the work of Larry Constantine, Tom DeMarco and Ed Yourdon.


答:
I second statements that you should not be using NTP or going near the system clock for this.  If you actually examine this requirement, you're going to find that you have the following needs:

How much time has elapsed since the previous frame so that you can advance any time-based stuff.  This may be different on client and server if both tick at different rates (e.g. you may sometimes see servers that run at a fixed 20Hz (or whatever) but clients that are allowed to run as fast as they wish).

How much time has elapsed since the current map started.  This is a zero-based timer (just init it to 0 on both client and server when they start up) and the server time is considered the "master", so the server sends it's current view of this time to the client for each frame that runs on the server.  This can be got by either taking the current server time and subtracting the time at which the server started, or by accumulating the per-frame times above.  The client-side per-frame time above can also be used to generate interpolation points between any two consecutive server frames.

A reference "base time" from which all other time advances; this can be (but does not absolutely need to be for all game types) the same on both client and server and is initialized at the start of the game (or current map) but never changed after (unless a new game - or new map - is started).

This is a simplified outline - I don't attempt to deal with issues such as latency/dropped packets/etc - but it is the basic framework on which the whole thing should be based.

None of this needs to go near the system clock or be concerned with matters such as different time zones, although the last item may use a time zone if desired.  The important thing is that the actual elapsed times are measured using a high-resolution zero-based timer, so they're completely agnostic to time-zone differences.  Want to find actual current time on the server?  Just add it's elapsed time to it's reference base time and you've got it.  Likewise for the client.

Title: How to sync clocks over networking for game development?

Body:
I'm writing a game that has a lot of time based aspects. I use time to help estimate player positions when the network stalls and packets aren't going through (and the time between packet's being received and not). It's a pacman type game in the sense that a player picks a direction and can't stop moving, so that system makes sense (or at least I think it does).

So I have two questions: 1) How do I sync the clocks of the games at the start since there is delay in the network. 2) Is it okay NOT to sync them and just assume that they are the same (my code is time-zone independent). It's not a super competitive game where people would change their clocks to cheat, but still.

The game is being programmed in Java and Python (parallel development as a project)


问:
What is the best way of storing date?
I am a new to storing dates based on time zones.

Need to know the standard way to store the date in the datastore.

My requirements are

Easy to query the date based on the date range.

show the date with the client appropriate time zone selected by him(I am having a table maintained for the timezone separately)

Able to query using the datastore Admin console also.

Any suggestions/ideas regarding this will be a great help in proceeding further.

答:
Use the Java standard timezones for all settings.

I would recommend storing the dates and times in the database in the time zone that the server is configured in.
i.e. if your server is in London, use GMT to store all dates and times

Each user could potentially have their own timezone. i.e. users in Eastern US, users in Auckland.

You can then convert from any user time zone to the known server time zone to the user time zone.

You can store the server time zone in some sort of application configuration file for ease of reference.

Easy to query the date based on a date range:

If the users timezone is know, you can just do a conversion to the server timezone in your application when the query is being completed. Pass through the converted date and time to your query.

Show the date with the client appropriate time zone:

Once the queries are returned, you can convert them to the user time zone and display in their own time.

The java docs have sample code on how to do the conversion between time zones.

Title: What is the best way of storing date?


问:
How do I convert a list of Requirements into Constraints?
I am trying to prepare my first software design document. I am self-taught and have no formal training in CS. Having done a wee bit of reading up on it beforehand, I have created a list of Requirements, Qualities and Non-Qualities for the system, which provide an overview from a managerial viewpoint on what the project is tasked with providing. The intent was for these to be convertible into design Constraints, which in turn would guide justifiable design decisions. So far they do not get into many specifics of what resources are to be provided, but are general in that they should apply to all resources present in the system.

I am having difficulty, however, in proceeding to the next step. What exactly is a Design Constraint supposed to look like? How specific or general should it be? How do I convert domain Requirements into Constraints? Have I already gone nuts and over-specified things? :-)

Background

I am the only programmer at a small service company. We have a current HTML with PHP PIs application which grew organically and has no test infrastructure. Editing one bit has repercussions and unintended consequences in far flung parts of the app. I want to replace it with a more professionally designed (in fact, any kind of designed) one, object-based with a test suite. Management doesn't know about programming and I need to know which of the current features are cruft, which workflows are bogged down, etc. This is intended to be my guidance both during a perpetually postponed design meeting and during implementation.

So far, I have the following:

Terminology

"Owner" refers to a company or division running their own deployment of the Software, with data independent of any other deployments.

"Developer" means an individual who is either a programmer with write access to the source code, or a database admin working for an Owner.

"User" means an individual who has authenticated access to a deployment.

"Staff" means a User who works for an Owner.

"Client" refers to a User who is a customer of an Owner.

REQUIREMENTS

What features must the service exhibit?

Platforms: Access to the service must be available via a variety of recent-to-modern, general business computing devices. (i.e. desktop, laptop, tablet and smartphones as of 2013).

Mobility: Reasonable efforts at providing access to the service for all Users must be made, regardless of their physical location.

Secure: All data must require authentication and authorization to access, and non-safe requests must come with sufficient confirmation that they were initiated by user intent.

Access Controls: Resources and sets of resources must have variable authorization permissions.

Admin Powers: Read and write authorization to individual resources and sets of resources must be seperate.

Unbreakable: The system must not be able to be put into a "broken" state by Users.

No Clobber: A User should not be allowed to overwrite another user's changes unknowingly.

Off-line: A User's scheduled events for the current day must be readable off-line.

Rapid Bootstrap: New Staff must be able to get up to speed on the internal side of the system quickly.

Owner Agnostic: Nothing specific to one Owner should be present in a new, clean deployment for another Owner.

Brandable: An Owner must be able to configure the system to exhibit their branding and corporate specifics.

Safe Data: A frequent and reliable back-up of all data must be easily scheduled.

QUALITIES

What other features would we like the end product to exhibit?

Fast developer turn-around for bug fixes.

Fast prototyping for new features.

Error-free implementation of new features.

Regression-free changes.

Attractive Client UI.

Efficient Staff UI.

Widest device and OS support reasonably achievable.

All accountability/blame data (who did what, when?) should be involatile.

All other data should be editable by a user with sufficient authorization, without needing a Developer.

Data back-ups should be creatable on demand by a sufficiently authorized user.

Data back-ups should be restorable on demand by a sufficiently authorized user.

NON-QUALITIES

What features are not important and will allow flexibility of design?

Programming language choice

UI monolingualism

We do not need a generic resource import or export system.

[this list is incomplete]

答:
As Robert noted in a comment, I really don't think you can fully encompass all your design constraints in one place.  Since you mention that you're intending to document your design constraints to assist with your design decisions, I'm assuming you are working in a waterfall-style development environment.  See the Criticism section on Wikipedia regarding waterfall development - while waterfall development may be justified in some cases, there's a reason why agile development is catching on.  Since you are free to start developing a product in small increments, as soon as you find that something doesn't work, you throw out that piece and then try a different approach.  It's also much more reactive to changing requirements over the course of a project.

Waterfall development often wastes lots of administrative time up front - how many of us have had to deal with a requirements document that is many dozens of pages long, only for it to be essentially useless towards the end of the project, since the requirements have changed over the course of its development?

So far, I haven't directly answer your question regarding how to document a design constraint; rather, I'm suggesting that you don't do it all up front.  You don't describe what your development environment is like (meaning, if it's in a large company, you're self-employeed, etc.), but if you can change the expectations of what needs to be delivered up front before any development is done, I think that will help you enormously.  If I can twist your question into, "What should I document up front?", then I would suggest you look into formulating user stories instead, which should better document the true needs that should be known up front.

(By the way, if you are working on a solo or small team, you would also benefit from reading up on lean development, which emerged from the Agile movement, and further focuses on removing waste from the development process).

Edit, based on Nicholas' comment:

It sounds like you are probably in a tough spot.  The above links in my answer cover each of those areas that you're not familiar with (jump to the top of the Criticism link to see the full scoop on Waterfall development - if you're not familiar with Waterfall versus Agile development, it's almost certain you are doing the former).

Do you have a feeling for how flexible your management's expectations are for what a development project entails?  If you feel comfortable bringing the idea up to them, I think you would really benefit from a lean technique, though admittedly, without having a person experienced in lean development there to guide you along, you might find it daunting at first.

If, by chance, you have a Pluralsight subscription (or don't mind signing up for the free trial), their course called "Best Practices for Software Startups" covers the principles behind lean development and would give you arguments to bring to your management as to why you shouldn't try to plan all these design constraints right from the start of a project.  (Alternatively, there are a number of presentations you can watch on YouTube).


问:
Is it normal that I can't keep in my head more than three bugs assigned to me, nor can I understand a thousand lines of spaghetti code?
I'm working on an old codebase which is... not perfect, in an environment which isn't either. It's not the worst codebase I've seen in my life, but there are still lots of issues: zero unit tests; methods with thousand+ lines of code; misunderstanding of basic object oriented principles; etc.

It hurts to maintain the code.

Every time I have to debug a thousand lines of a badly written method with variables reused all over, I'm totally lost.

Some modifications or refactoring I've done introduced bugs in other places of the application.

Lacking any documentation, tests, or an observable architecture and combined with badly named methods, I feel that I fill up all of my available working memory. There is no room left over for all the other things I have to remember in order to understand the code I should modify.

Constant interruptions at the workplace disturb me and slow me down.

I can't remember more than two or three tasks at a time without a bug tracking system, and I forget all of them over the weekend.

My colleagues don't seem to have similar issues.

They manage to debug badly written methods much faster than me.

They introduce fewer bugs than I do when changing the codebase.

They seem to remember very well all they need to in order to change the code, even when it requires reading thousands of lines of code in twenty different files.

They don't appear to be disturbed by emails, ringing phones, people talking all around, and other people asking them questions.

They don't want to use the bug tracking system that we already have since we use TFS. They prefer to just remember every task they should do.

Why does this happen? Is it a particular skill developers acquire when working with badly written code for a long time? Does my relative lack of experience with bad code contribute to these problems / feelings? Do I have issues with my memory?

答:
I have been through a situation like that before and based on that experience I can say that your problem is not memory related and that there is something on your mind (most certainly not work related) that is making you stressful and keeping you from focusing 100% on the task at hand.

So the first step is to clear your mind from that stuff when you are in your desk.

That stress might also be increased because you feel like you are getting behind in terms of productivity, so try talking with your coworkers and ask them for tips on their approaches to the refactoring.

Finally don't feel embarassed if you have to write down the issues you have solved and/or are working right now (it desn't have to be a sophisticated bug tracking system) it's better to be certain of something because you read it from your notes than stating it off the top of your head while not being 100% certain of it


问:
Is this really necessary for solving this problem?
I came across the following article which presents the problem:

A group of people walk into a restaurant and want to spend exactly
  $15.05 on appetizers. They also want them as fast as possible. This
  leaves waiter with an NP-hard problem to solve, a variation of
  knapsack problem.

The article goes on to create some sort of "genetic algorithm" to solve the problem.  My question is, is that really necessary?

First of all, no programming solution would be possible if no combination of existing appetizers could equal $15.05.  Right?

Also, if I were approached with this problem, I would do something like this:

```<code>// loop through appetizers
  // deduct price from total amount ($15.05) until the difference <= zero
  // add to new array of appetizers

// sort the new appetizers array by "time to make the appetizer"
// return new appetizers array
</code>```

Isn't it that simple?  Thanks for your review.

答:
As others have mentioned, the trick is that they must spend exactly $15.05, which does indeed make this an NP-hard problem similar to the knapsack problem. However, "NP-hard" doesn't necessarily mean "hard to solve in practice" -- if the number of appetizers is small, then a brute force solution is relatively easy to code up and will work just fine. We can say with some degree of certainty that we don't think there is any algorithm possible that can quickly solve the problem as the number of appetizers on the menu increases. If you want to handle the problem for arbitrarily sized menus, then you have two choices:

Approximation methods (usually deterministic) that are often guaranteed to find a solution within some constant factor of the best solution in polynomial time.

Heuristics (we usually call them metaheuristics) that simply try their best to come up with the best thing they can find.

Genetic algorithms are an example of the latter approach. You have no guarantees at all about what a GA will do, but empirically, they usually work reasonably well. You probably won't get the best solution, but you'll likely get something decent.

Each approach has advantages and disadvantages, but unless P=NP, which essentially all computer scientists doubt, but for which providing a proof is one of the foremost unsolved problems in mathematics, then we know you'll need to do something clever to try and find a solution via some method that will likely fail to find the perfect solution, or perhaps even any solution at all. Such is life in NP-hard land.

The very basics of complexity theory

Suppose you are given a problem with a yes/no answer. For instance, "Given these menu items, is there a subset that adds up to exactly $15.05 in cost?" We call these decision problems, and we can classify them according to how hard they are to solve. (For technical reasons, we tend to consider only decision problems, but optimization problems can be converted to an equivalent decision problem easily enough, so the basic principles are the same).

Let the set P be the set of all such problems for which we can find a solution "easily". OK...seems simple enough. We just need to define what we mean by "easily". The basic distinction here is between polynomial and exponential time. Note that so far, we've only considered a general class of problems -- problems where there's a menu and items on it. Any particular instance of the problem might be trivial. Suppose the menu only has one item and it costs $16. Then that instance is easy. What we're after here is a general notion of difficulty based on the size of the problem instance. If the menu has K items, how long will the best algorithm take to solve it as a function of K? If that function has K in an exponent, then we say the algorithm requires exponential time. Otherwise, we have a polynomial time algorithm.

Back to the class P now. P is the class of problems for which we know of an algorithm that can solve any instance of any problem in P in polynomial time.

This brings us to the class NP. You'd think this meant "non-polynomial" time, but that's not actually right. In fact, it's the class of problems that can solved in polynomial time by an algorithm that can use a non-deterministic oracle. That's a fancy way of saying, "if there's a magic 8-ball that could tell you the answer, could you at least prove the answer was correct in polynomial time?"

Take that appetizer menu problem again. We don't see an obvious algorithm for solving it in polynomial time, but if I tell you that taking items A, B, and C is a valid solution, it's really easy to add up their prices and verify that. Problems for which this is true make up the class NP.

It should be easy to see that any problem in P is also in NP (remember these are sets, so notions of "in" just mean that there's a subset relationship). However, we don't know whether P is a proper subset of NP. If not, then P = NP; if so, then P!=NP.

This has still been fairly academic, but we can translate this to simple English. The question of whether P=*NP* is the question of whether any problem for which a solution can be recognized quickly also has the property that the solution can be found quickly. Mathematicians would state this as "is finding a proof harder than verifying a proof that is given to you?"

No one knows the answer to this question, but it is almost universally believed that P!=NP -- that is, that there are problems for which there exists no efficient way of finding the solution, even if a solution can be verified quickly.

We can go further than this. One very useful idea is that of NP-completeness. NP-Complete is another class, just like P and NP. In fact, it is a subset of NP that contains only problems that are at least as hard as every problem in NP. What that means is that if you have an unknown problem and you want to know whether there's a polynomial time algorithm for it, one thing you can do is to try to reduce any problem in NP-complete to your problem (with the reduction being capable of being done in polynomial time as well). If you can find a way of transforming your problem into, say the traveling salesperson problem (which we know to be in NP-complete) then any algorithm that could solve your problem could also solve the TSP. And by the definition of NP-complete, could therefore solve every problem in NP. Because we by now think this is extraordinarily unlikely to happen, it's very strong evidence that your problem is not efficiently solvable.

This is I think the most practically applicable thing to know about complexity theory. There are hundreds, maybe thousands, of known NP-hard and NP-complete problems (note: NP-hard is like NP-complete, only the problems don't have to be in NP themselves) . Knowing a little bit about these ideas can be a really useful trigger. If your boss wants you to solve some problem and you're aware of these basic ideas, you may be able to say, "Hang on, this looks an awful lot like the subset-sum problem, and I think that was NP-complete. Maybe I need to look at heuristic approaches," instead of bailing right in and trying something that's doomed to fail.


问:
Redis & MongoDB for Metrics Platform
I'm in the process of writing an app that will ultimately display analytics to the user. I've written a service that collects data from an API. This data will then be processed, stored, then when the user requests the data, pulls it from the store and displays it. Fairly straightforward. We plan on using MongoDB for the app database (storing users, settings, etc.). I've read that Redis is good for storing metric information because of the key/value pair nature.

My question is, what would be the best way to go about interchanging how the data comes from the API service to the user being able to request it? I've initially come up with storing the API data in another MongoDB store, seperate from the app. Then having another service that runs at a longer interval than the API service that aggregates the raw data in Mongo, moves it into Redis, then archives the parsed Mongo data into either some log file or something. The app would then be able to reach into Redis to grab the metrics based on predetermined keys.

Is Redis even the right option for something like this? I've also considered swapping out MongoDB with Postgres or MySQL since operations like SUM run well on a relational platform.

答: I'm not sure how much redis will help here -- it can do some fancy tricks for sure, but you probably need to work out getting this thing built and running and have some baseline performance before sticking in a caching layer. Personally I would start with just using MongoDb's map reduce functions and take it from there. </p>

Title: Redis & MongoDB for Metrics Platform


问:
Woes of a Junior Developer - is it possible to not be cut out for programming?
(Let me start off by asking - please be gentle, I know this is subjective, but it's meant to incite discussion and provide information for others. If needed it can be converted to community wiki.)

I recently was hired as a junior developer at a company I really like. I started out in the field doing QA and transitioned into more and more development work, which is what I really want to end up doing. I enjoy it, but more and more I am questioning whether I am really any good at it or not. Part of this is still growing into the junior developer role, I know, but how much? What are junior developers to expect, what should they be doing and not doing? What can I do to improve and show my company I am serious about this opportunity? I hate that I am costing them time by getting up to speed. I've been told by others that companies make investments in Junior devs and don't expect them to pay off for a while, but how much of this is true? There's got to be a point when it's apparent whether the investment will pay off or not.

So far I've been trying to ask as many questions I can, but I've you've been obsessing over a simple problem for some time and the others know that, there comes a time when it's pretty embarrassing to have to get help after struggling so long. I've also tried to be as open to suggestion as possible and work with others to try to refactor my code, but sometimes this can be hard clashing with various team members' personal opinions (being told by someone to write it one way, and then having someone else make you rewrite it).

I often get over-stressed and judge myself too harshly, but I just don't want to have to struggle the rest of my life trying to get things work if I just don't have the talent. In your experience, is programming something that almost everyone can learn, or something that some people just don't get? Do others feel this way, or did you feel that way when starting out? It scares me that I have no other job skills should I be unsuited for having the skills necessary to code well.

答:
"If you focus on the things you're doing wrong, you'll never get anywhere."

Be weary of this advice. In my experience I have found the exact opposite. Bad code and bad design can often be attributed to a programmer simply avoiding an approach they are uncomfortable with.

Rather than spending time improving their skills across the board, creating a collection of tools, they have their one hammer and try to turn everything into a nail. Don't fall into this trap.

Find the things you are bad at and practice precisely those things.


问:
Where to store web application custom configuration settings
I'm currently working on an internal web application for my company in node.js

We want to have certain configuration settings be changeable by management.  For example, we pre-print some labels automatically during receiving if the quantity is less than 5 so the user doesn't have to stop to confirm a print dialog.  What if we wanted to shift this to any quantities less than 10 because it is found to be more efficient?

My question is this:  What's the best approach to save custom configuration settings if I was to create an area for changing these params on their dashboard?  Would saving this information in a json formatted text file on the server and then just parsing it using fs every time be the best way? or is there something I'm not thinking of?

Thank you in advance.

答:
I'd put them them in your application's database, the reasoning being:

Your regular backup and restore procedures (you do have one, right?  Just checking) will catch these options too without needing additional configuration.

The database can be moved to a new server (e.g. during a regular hardware upgrade) and the options will move with it without needing to handle them separately too.

Business logic that depends on the values of some of these options can be constructed more easily (e.g. with SQL statements).

The table of configuration options can be secured using the same security model that the rest of your application uses.  No special handling needed.

You can make use of your databases logging and auditing facilities for an additional layer of security - you'll get a better historical record of values, who changed them, when, etc.

Of these, the first two are more "nice to have" reasons; they support my recommendation but they're not really totally compelling enough to swing the decision.  The middle one is very useful, but the last two I would consider to be utterly essential.  If this is an application that the businesses income depends on (or that has bearing on income), if decisions are made based on the information managed by the application, then it's just common sense (and you're also protecting yourself if the worst does happen and something goes wrong).


问:
When inheriting from a base class, should you retest constructor arguments?
Say I have something like this:

```<code>public class BaseClass
{
    public BaseClass(string someString)
    {
        if(someString == null)
            throw new ArgumentException();
    }
}

public class ChildClass : BaseClass
{
    public ChildClass(string someString)
        : base(someString)
    {
        // Should I do this??
        if(someString == null)
            throw new ArgumentException();
    }
}
</code>```

Also, what if I'm inheriting a class that I do not have the source for. Should I recheck constructor arguments?

答:
No. If your base class validates something you don't have to. As for your second question: Yes and No. Yes if you're going to use the argument, no if only the base class uses the argument.

It's the base classes job to be sure that value is good enough for its purpose, you can't however expect the base class to ensure the value is good enough for your purpose. For all you know the base class is completely happy with a null value and can function fine in that scenario when you can't.

Also when null checking your strings, you usually want string.IsNullOrWhitespace(someString) or string.IsNullOrEmpty(someString) depending on whether or not "  " is valid, or "" is valid, or neither.


答: Since nobody has mentioned the obvious one yet: one big design pattern in the procedural era was Object. Like many popular design patterns before (e.g. Subroutine) and after (e.g. Iterator), it became so popular that it even got language support.</p>


问:
How can a developer working alone respond to a spike in server demands?
Imagine this scenario:

You've created a multiplayer game app for a mobile platform such as Android. You successfully set it up with one server, you figured out how to do that. It works quite well.

To your surprise, the game TAKES OFF. Server demands explode. You need to scale, but you have hardly any experience with running a single server, let alone running multiple servers in tandem.

What do you do? Is there a service (Heroku-style) to help with such a thing? Anything? Or do you need to hire someone with a certain skill set and the necessary experience?

答:
First off, it's a nice problem to have, try not to spend too much time mitigating it upfront though.

Start with working with two load balanced machines early on, if you can spread load across two you can across many. With two servers you can make a head start getting vertical scaling down.

If need be you could start out with two small VPS'es to save on hosting costs. Added benefit is some redundancy and you can lean on one while you update/reboot the other etc. Plenty of benefits!


问:
Unit-Testing functions which have parameters of classes where source code is not accessible
Relating to this question, I have another question regarding unit testing functions in the utility classes:

Assume you have function signatures like this:

```<code>public function void doSomething(InternalClass obj, InternalElement element)
</code>```

where InternalClass and InternalElement are both Classes which source code are not available, because they are hidden in the API. Additionally, doSomething only operates on obj and element. I thought about mocking those classes away but this option is not possible due to the fact that they do not implement an interface at all which I could use for my Mocking classes.

However, I need to fill obj with defined data to test doSomething.

How can this problem be solved?

答:
You probably already tried this option, but you don't specifically state so in your question:

Can you instantiate the objects and set them to a certain state? Perhaps calling doSomething results in a some new state that is enough to verify it has properly operated on the objects?

Of course if one of the objects launches a nuclear missile touches a lot of external state it may be a no-no.


答:
You’ve got a few options.

Engage, or partner with someone who knows how to do this.

Move your server to Amazon AWS/EC2 or similar type services.

It’s pretty likely that whoever you engage with for option 1, will probably just do 2 for you.

These "cloud" type hosted solutions are pretty awesome, typically you pay for what you use and usually include the option of being able to spin up extra servers on demand to handle load (ala EC2). Combined with sufficient bandwidth and uptime these providers are a far better option than hosting the server locally. Which is more than likely against the Toss of your home internet connection ;)?

Profiling your server will get you so far, but if you saturate your connection you're still dead in the water.

Title: How can a developer working alone respond to a spike in server demands?

Body:
Imagine this scenario:

You've created a multiplayer game app for a mobile platform such as Android. You successfully set it up with one server, you figured out how to do that. It works quite well.

To your surprise, the game TAKES OFF. Server demands explode. You need to scale, but you have hardly any experience with running a single server, let alone running multiple servers in tandem.

What do you do? Is there a service (Heroku-style) to help with such a thing? Anything? Or do you need to hire someone with a certain skill set and the necessary experience?


问:
Design pattern for complex view creation in sheet music
I've got a bunch of Note-Models with properties like pitchand duration. In music notation, these notes must now be placed into a certain bar on a certain line on a certain page, and so on. Many more factors influence the positioning of these notes like the notes that are placed in the same bar before them.

Also, style-properties influence many different view-elements.

The positioning of notes is affected by the "line-height" of the music lines, whether the bar is justified to the width of the page or not, and so on.

I'm looking for a design pattern that can help me cleanly position all these views relative to each other.

Can anybody help me out?

I'm using SVG with JavaScript for my current project, if this is important.

Thank you so much for helping out! :)

答:
Why do you want a design pattern?
What you really want is an algorithm.

Musical notes derive their "height" on the stave by the note which they represent.
They derive their position on the stave relative to the time at which they are played within the bar. Additional information may change how notes are draw, such as triplets, or other rules regarding ties, and groups of 8th notes.

My advice would be to work out all the rules. And then look at your data structure, and work out how to turn the data, with the help of the rules, into something you need to render.

It might help to think of each bar as a tree of notes of varying lengths. The first level would be a semibreve, which has two children (minims) each which have to children (semiquavers) and so on. You’d only fill out the nodes in the tree if those notes exist, or if there is a rest for that period. Then you could traverse the tree for each bar to apply the rules associated with position, and note grouping, and what not.

You may have to change this slightly to handle triplets (perhaps a notification on the parent node which contains the triplets).

Using an M-way tree you could represent any time signature this way as well.

There’s a few open source note tablature (guitar notation) renderers which also draw note staves, go and have a look at how they do this too.


问:
Is it ever ok to have an empty catch statement?
I thought about it and could not come up with an example. Why would somebody want to catch an exception and do nothing about it? Can you give an example? Maybe it is just something that should never be done.</p>

答:
Closing out system resources gracefully to recover from an error

For instance. If you're running a service in the background that doesn't provide feedback to the user, you may not want to push an indication of the error to the user but you do need to close out the resources being used in a graceful manner.

```<code>try
{
    // execution code here
}
catch(Exception e)
{
    // do nothing here
}
finally
{
    // close db connection
    // close file io resource
    // close memory stream
    // etc...
}
</code>```

Ideally, you'd use the catch in debug mode to catch errors and print them to the console or to a log file for testing. In a production environment, background services generally are expected to not interrupt the user when an error is thrown so the error output should be suppressed.

Body:
Closing out system resources gracefully to recover from an error

For instance. If you're running a service in the background that doesn't provide feedback to the user, you may not want to push an indication of the error to the user but you do need to close out the resources being used in a graceful manner.

try
{
    // execution code here
}
catch(Exception e)
{
    // do nothing here
}
finally
{
    // close db connection
    // close file io resource
    // close memory stream
    // etc...
}

Ideally, you'd use the catch in debug mode to catch errors and print them to the console or to a log file for testing. In a production environment, background services generally are expected to not interrupt the user when an error is thrown so the error output should be suppressed.


答:
One of the fastest ways a small startup can burn profit is by spending it all on trying to meet demand. There are good reasons why companies like AE charge $10 per mobile app and that's because the infrastructure is expensive.

You might have stumbled across a mobile app that is a great idea, and no one else has done it. When you release it you realize the reason no one has done it is because the cost of IT resources exceeds what people are willing to spend for the app.

Cloud storage is a great example. The majority of people use free accounts, and that means the small percentage that buy storage also pay the coverage so everyone else can have a free account.

You need to figure out how much to charge to cover the cost of upgrading your infrastructure to support sudden success, but also avoid the mistake of spending all your money to just break even.

One of the big problems with mobile development compared to other platforms is the very low expectation of how much apps cost. An app that sells for $1.99 and moves over 100,000 units might sound like the developer is making a lot of money, but might cost over $50k to develop and server costs run above $10k+ per month.

Wise developers create apps that are loosely coupled to data servers, and offer high user value with the lowest development efforts. Sadly, this is often difficult or impractical for most projects.

I'm not sure if I answered the question, but I'm trying to warn you to budget your business expenses first. Don't assume that because you can run it on a cheap server and no one else is doing it. That this will translate into profits if you scale up, because the odds are it might be an idea that is difficult to profit from at a larger scale.


问:
How to detect achievements in gaming?
I mistakenly posted this to stackoverflow and now posting here based on a suggestion in on that site ...

This is a very high level conceptual question. Say in a software application I have 4 different actions, for example: Upload, Share, Comment, and like

And I want to give achievement badges to users like:

Rookie - Upload your first 5 files

Upload Junkie - Upload 20 files in 1 day

Night Crawler - Upload a file after midnight

Share-a-holic - Share 10 different files

Likes-everything - Like 20 different files

you get the idea. What is he best way to check and see if a user has achieved a particular achievement without having to compile the logic for achievement into my code? And .. - Retain the ability to Add new achievements post compile (xml or db) - Achievements must track specific actions, number of times, and additional criteria (like time of day) - Detection should be near real-time so the user notified almost instantly when an achievement is completed

My biggest questions is, how do I detect these achievements being achieved? Do I:

1) Check after every action to see if ... (Most real time) 2) Have another program check the DB at all times against a set of rules? (Easiest)

Is there another paradigm that I'm missing? I feel there definitely is because in many games (like jetpack for iOS for example), I'm notified of the achievement I have unlocked in the instant in which I unlock it which I found pretty impressive.

Thank you

答:
What you generally do is have an "achievement" system. Any action which happens calls the achievement system and says "hey this thing just happened".

The achievement system is then usually a set of rules, usually made up of simple combinatinatorial logic and counters for various "events". It’s then the achievement system's responsibility for working out, with the help of the rules and counters, whets happened, and what achievements to give out.

The reason you do this is twofold.

You don’t want to spread your state logic all over your codebase.

sometimes achievements will require combinations of "stuff" which may happen in completely different systems / times / etc and spreading the logic for this around your code base would result in large amounts of unneeded complexity.

The way I've done it in the past is to use a scriptable rules system (where scriptable is a very loose term, usually just some kind of data driven comparator). So you can say something akin to:

When "the user pressed something" happens "increment" the "pressed" variable.

Then you could have another rule which is

When the "pressed" variable is "greater" than “some value" hand out achievement "blah"

Or perhaps

When "the user kills the boss" happens "hand out" achievement "blah".

The achievement system will also be tasked with maintaining the state of which achievements have already been handed out, so you don't get duplicates.

Title: How to detect achievements in gaming?