答:
It pretty much boils down to don't guess.  Mostly new programmers do it, but I've seen veterans do it too, because they think it saves research time.  Something doesn't work, so you add a +1 or a -1, change a true to a false or vice versa, reorder some statements, add or change delays, change thread priorities, and other small transformations, basically testing random permutations until it works.

That mostly applies to changing existing code, but also is a factor in brand new code, because no one truly starts from scratch.  You're always building on top of standard libraries, operating systems, or at least processor architectures.

In other words, you're not done until you know why your fix works.  The path you take to get there doesn't matter so much.  Even random permutations can sometimes be helpful to narrow down a bug that's difficult to diagnose, as long as you take the time afterward to ask yourself, "Okay, changing true to false fixed it, but why?"


问:
Should I be worried about overengineering programming assignments given during interview process?
I recently had a phone interview with a company. After that phone interview, I was told to complete a short programming assignment (a small program; shouldn't take more than three hours). I'm only directly instructed to complete the assignment and turn in the code. I was given complete freedom to use any language I wished and was not told exactly how to turn in the code.

Immediately I planned on throwing it on Github, writing a test suite for it, using Travis-CI (free continuous integration for public Github repositories) to run the test suites, and using CMake to build the Linux makefiles for Travis-CI. That way, not only can I demonstrate that I understand how to use Git, CMake, Travis-CI, and how to write tests, but I can also simply link to the Travis-CI page so they can see the output of the tests. I figured that'd make it a tiny bit more convenient for the interviewer.

Since I know those technologies well, it would add essentially no time to the assignment.

However, I'm a bit worried that doing all this for a relatively simple task would look bad. Although it wouldn't add much more time at all for me, I don't want them thinking I spend too much time on things that should be simple.

答:
Another view to consider is that your approach is neither good nor bad. I can imagine interviewers who would consider it too much and I can imagine interviewers who would love even more engineering.

Don't worry so much. Instead, solve the problem in the way you consider best and you'll likely receive job offers from people who agree with you. That's a great first step toward a productive work environment. Remember, interviews go two ways. The interviewer's response to your solution will tell you a lot about them as well. Do you really want to work with people who believe your development instincts and philosophy are wrong?

ContentLicense: CC BY-SA 3.0


问:
What are the pros and cons of HTML5, native and hybrid mobile app approaches?
I want to develop a mobile application. I recently read an article on Telerik Forum, which compares among three types of mobile application and I don't know which one should I select to begin with. Here is an image describing the pros and cons of different mobile design choices

To decide between these design choices, I would like to better understand the pros and cons of each architecture choice listed in the diagram.  What are the pros and cons of each architecture approach?

答:
I'm a mobile developer who has spent a great deal of time considering this issue.

Why do you ask?

Most likely, you hope to reduce app development costs by:

Using existing HTML5/Javascript development skills

Targetting multiple platforms without writing multiple apps from scratch

Not having to maintain multiple codebases in the future

Reasons may also include:

HTML5/Javascript development perceived as "easier" than native platform development

Avoiding payment of developer programme registration fees

Avoiding appstore content restrictions (gambling etc)

Avoiding purchase of development hardware (e.g. Mac for iPhone development)

Definitions

Let's establish exactly what we mean by each of the three approaches mentioned:

Native

An app that is installed on a device, usually from its app store (although can sometimes be sideloaded).  For the purposes of this discussion, the UI of a native app does not usually consist of a full-screen webview only.

Mobile web

This can in fact be any web page at all, however for this discussion let's consider a single-page web app which attempts to imitate the look and feel of a native app.  It is not a native app, it runs in the device's browser.

Hybrid

Hybrid app instanceof native app.

Most people probably understand a hybrid app to be a single-page mobile web app (again most likely imitating the look and feel of a native app), but packaged as a native app with access to native services (à la Phonegap).

However there is in fact a spectrum between the Phonegap model and fully native which I'll come to later.

Mobile web

Technical restrictions

Let's first list some technical restrictions on mobile web apps which could in themselves be deal-breakers depending on what you're doing:

HTML/canvas UI only

No access to certain device events and services (these are widely documented)

Cannot be listed in app stores (affecting discoverability)

Can become full screen and have homescreen icon on iOS, however this is an unusual and unfamiliar experience for most users

If you can live with all the above, then read on for more about the challenges of single-page native-style web apps.  However this section wouldn't be complete without reference to the FT app.

Financial Times

The FT web app is a famous example of this style of app.  Here's an interesting feature from the UK Guardian newspaper about it.

It's certainly a remarkable feat of engineering.  Note that it is currently still only available on iOS only -- this tells me that they are finding that resolving the challenges of advanced cross-browser development to be very difficult indeed.

Single-page native-style web apps

This section applies to both mobile web and Phonegap-style apps.

Native-style look and feel within a web app is usually achieved with a framework such as Sencha Touch which provides a suite of UI components for you to use.

Such frameworks are fine for very simple UIs.  However they lack flexibility.  You won't be able to implement any native app design using Sencha, you'll need to adapt your design to what the framework can accommodate.

The main way in which these frameworks suffer is in trying to emulate the platform's own UI intricacies.  That nice little bouncing effect you get when you've scrolled to the end of a list on the iPhone?  Your framework needs to emulate that in Javascript.  It's impossible to recreate it completely, it will be prone to slow down, and your users will be stuck in the the "uncanny valley" of an app which looks sort-of like native, but clearly isn't, and a non-technical user won't be able to put their finger on exactly why.

The "HTML5/Javascript is easy" myth

Device fragmentation within web browsers is rife, and when you get beyond the most basic HTML and CSS you'll notice things don't quite work as you'd expect.  You might find yourself spending more time solving fiddly UI issues than you'd have saved doing it natively twice over.  If you're going native, note that native app webviews are not the same as device browsers and have their own fragmentation issues.

And as your app gets more functionally complex, you'll find that you need more than basic jquery skills to keep your Javascript clean and maintainable.

That said, it's perfectly possible to create simple, functional apps pretty quickly with this approach.  But it's pretty obvious when an app is doing it.

Further along the spectrum

So, we want a better UX than Phonegap-style apps can offer, without writing absolutely everything from scratch multiple times.  What can we do?

Share non-UI code

There are a range of techniques available for sharing business logic across multiple native platforms.  Google have launched J2ObjC which translates Java into Objective-C.  With careful factoring of code, a Java library could be used on both Android and iOS.

Libraries such as Calatrava and Kirin allow codebases written in Javascript (and therefore anything that can be compiled to Javascript) to be manipulated from native code.  Disclaimer: I work for Future Platforms who created Kirin;  we have had great success using it on iOS with Javascript generated from Java with GWT, with  Java code also being run natively on Android.

Use webviews...  where appropriate

Full screen webviews have a lot of work to do to be able to imitate screen transitions and bounce effects.  But a webview inside native app chrome can be indistinguishable from native.

There are standard and well documented methods for native apps and webviews to communicate.

Lists and tables can work particularly well when done in this way, however text entry is an example of something best handled natively (for full control over keyboard).

In summary

The approach that's right for you depends on how complicated your app is, and what level of UI polish you'll be satisfied with.

My motto: use webviews wherever you can, but make sure your users can't tell.


问:
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]

答:
Narrow it WAY done and use an Agile methodology to do it piece by piece.

Given the situation you describe (basically a mess) and the system you desire (cleaned up) I would recommend you tackle this one small piece at a time.

I would also remove these 'qualities'

Fast developer turn-around for bug fixes.

Error-free implementation of new features.

Regression-free changes.

Attractive Client UI.

Efficient Staff UI.

Widest device and OS support reasonably achievable.

because everyone always want these.  It may help to think of the opposite for any requirement you have, as this would show that you don't want Slow developer turnaround, errors, Unattractive client UI, Inefficient UI, etc.  As no-one really want any of those things, making them a requirement doesn't help a lot (though they are worthy principles).  They are also very general and non-specific.  Each one of them begs the question "but what does that actually mean in practice" as the devil's in the details.

I would take the requirements you have listed and focus on them one by 1.  You have 12 which is convenient for a 1 year effort with 1 month on each as a primary focus.

The biggest things are too avoid are traps of getting overwhelmed by the volume and of generating too much detail in the planning.

You will also need a great deal of patience as at each step you will encounter difficulties and problems to overcome.  In these situations it's often the tortoise that wins.


答:
In reality, nobody cares if the candidate can whip up a git repo or create makefiles in a hurry, because that is just recall of what he or she learned by rote. These are secondary skills to the actual problem solving and design aspect of the interview question.

So yes, your intuition is spot on that it potentially looks bad, because it may look as if the candidate believes that someone who can regurgitate a few memorized commands and patterns to create a project skeleton has impressive software skills.

The test suite aspect of the solution is good though. Delivering an answer with a regression test suite will probably earn your points. All the more so if your test suite exercises the salient cases in the code. The test suite doesn't have to have a lot of formal trappings and rely on tools; just the fact that you somehow have one in there is good enough for an interview. It's more or less obvious that if you can put together some ad hoc unit tests in an interview quiz, you can do that with tools on a real project.

Title: Should I be worried about overengineering programming assignments given during interview process?

Body:
I recently had a phone interview with a company. After that phone interview, I was told to complete a short programming assignment (a small program; shouldn't take more than three hours). I'm only directly instructed to complete the assignment and turn in the code. I was given complete freedom to use any language I wished and was not told exactly how to turn in the code.

Immediately I planned on throwing it on Github, writing a test suite for it, using Travis-CI (free continuous integration for public Github repositories) to run the test suites, and using CMake to build the Linux makefiles for Travis-CI. That way, not only can I demonstrate that I understand how to use Git, CMake, Travis-CI, and how to write tests, but I can also simply link to the Travis-CI page so they can see the output of the tests. I figured that'd make it a tiny bit more convenient for the interviewer.

Since I know those technologies well, it would add essentially no time to the assignment.

However, I'm a bit worried that doing all this for a relatively simple task would look bad. Although it wouldn't add much more time at all for me, I don't want them thinking I spend too much time on things that should be simple.


问:
What is the reason for using lowercase for the first word in a local variable (eg, employeeCount, firstName)
I take a good deal of criticism from other programmers due to my use of full proper casing for all my variables.  For example, your typical programmer will use employeeCount for a variable name, but I use EmployeeCount.  I use full proper casing for everything, be it a void method, return method, variable, property, or constant.  I even follow this convention in Javascript.  That last one really rustles people's jimmies.

The typical reason given as to why I shouldn't follow this "non-standard" casing convention is because full proper case should be reserved for properties and void methods.  Local variable and methods that return a value should have the first word in lowercase like int employeeCount = getEmployeeCount().

However, I don't understand why.

When I question this, it seems that I just get an arbitrary answer of that's the standard.  Whatever the answer is, it usually always boils down to That's just the way it is and I don't question it.  I just follow it..  Arbitrary answers are never good enough for me.

Ever since my early days of programming Excel 97 macros with the Office IDE, I've never needed a casing convention to tell me whether or not something is a local variable or property.  This is because I've always used a very intuitive naming convention.  For example, GetNuggetCount() clearly suggests a method that goes somewhere an gets a count of all the nuggets.  SetNuggetCount(x) suggests that you are assigning a new value to the count of nuggets.  NuggetCount all by itself suggests a property or local variable that is simply holding a value.  To that last one, one may be tempted to say, "Ah ha!  That is the question.  Property or variable?  WHICH IS IT?"  To that, I'd reply with, "Does it really matter?"

So here's the tl;dr;:  What are the objective, logical, non-arbitrary reasons to use lowercase for the first word in your variable or return method?

Edit:  For MainMa

Replace this code with the first code sample in your answer and see how well your argument holds up:

```<code>public void ComputeMetrics()
{
    const int MaxSnapshots = 20;

    var Snapshots = this.LiveMeasurements.IsEnabled ?
        this.GrabSnapshots(MaxSnapshots, this.cache) :
        this.LoadFromMemoryStorage();

    if (!Snapshots.Any())
    {
        this.Report(LogMessage.SnapshotsAreEmpty);
        return;
    }

    var MeasurementCount = Measurements.Count();
    this.Chart.Initialize((count + 1) * 2);

    foreach (var s in Snapshots)
    {
        this.Chart.AppendSnapshot(s);
    }
}
</code>```

答:
There isn't any.  It is what most people do, so it has become the standard because that is what everyone does.  A lot of literature follows this convention so people picked up the habit.

The convention isn't as important as the consistency across the code.  As long as everything is named in a consistent manner so that I can tell what things are from looking at them, it doesn't really matter whether or not the first letter is capitalized or not.

I would find it jarring to come across code written in your manner and would say that I don't like it.  But that is a matter of style.

Now if you are doing this in the workplace, it would be better to code in the style of the team so that the code remains consistent everywhere.  Rather than having your code be different than everyone elses.

http://thecodelesscode.com/case/94


问:
Is this a Single Responsibility Principle violation?
I'm designing an OO graph library and at the moment I'm trying to figure out the design for a GraphEdge class. I've added setters and getters for it's nodes, direction and weight. This seemes perfectly reasonable.

Then I've started working on the Graph class and I've come to the need of knowing if the particular edge is adjacent to the particular node.

And now I doubt if I should add a isAdjacentTo(Node) method to the GraphEdge class or I should create a GraphUtil class(*) and add static edgeIsAdjacentToNode(Edge,Node) method to it.

On the one hand, I can not see any additional reasons for changing GraphEdge if I stick to the first option. On the other hand, this seems to me like kind of second responsibility added to the class.

Also if I stick to the first option this will probably violate the Open-Close Principle. The GraphEdge is not closed for changes, since later I will need to add linksNodes(Node,Node) method to it and maybe some others later.

The questions are:

Does adding isAdjacentTo(Node) method to the GraphEdge class violates the SRP?

Why?

(*) I stick to pure OO style with no free functions

答:
The answer is "neither." The problem with both your proposed solutions is that neither is an Information Expert for what it needs to know (how a single node relates to all the other nodes).

The only way you can have a free function that could calculate this information is by passing in all the nodes as an argument to the function. Otherwise, you do not have a free function, but brittle global state. If you already have all the nodes at your fingertips, do you really need the function?

More importantly, why doesn't the object that has all the nodes at its fingertips have this method? <--hint, hint

Now, you could conceivably have nodes that have access to this information, if they're implemented something like a doubly-linked-list, but with more directions than just next and previous. In this case, it would be trivial for a node to tell you if a given node is in its nextNode, previousNode, upNode, or downNode. But I suspect that you didn't code your nodes this way, or you wouldn't be asking the question. So go with the hint ;).


答:
"because full proper case should be reserved for properties and void methods. Local variable and methods that return a value should have the first word in lowercase" and becuase it is standard convention.

Other programmers are pulling up your code right now and thinking this is a property and it is really a local variable, your making their job harder.

Title: What is the reason for using lowercase for the first word in a local variable (eg, employeeCount, firstName)

Body:
I take a good deal of criticism from other programmers due to my use of full proper casing for all my variables.  For example, your typical programmer will use employeeCount for a variable name, but I use EmployeeCount.  I use full proper casing for everything, be it a void method, return method, variable, property, or constant.  I even follow this convention in Javascript.  That last one really rustles people's jimmies.

The typical reason given as to why I shouldn't follow this "non-standard" casing convention is because full proper case should be reserved for properties and void methods.  Local variable and methods that return a value should have the first word in lowercase like int employeeCount = getEmployeeCount().

However, I don't understand why.

When I question this, it seems that I just get an arbitrary answer of that's the standard.  Whatever the answer is, it usually always boils down to That's just the way it is and I don't question it.  I just follow it..  Arbitrary answers are never good enough for me.

Ever since my early days of programming Excel 97 macros with the Office IDE, I've never needed a casing convention to tell me whether or not something is a local variable or property.  This is because I've always used a very intuitive naming convention.  For example, GetNuggetCount() clearly suggests a method that goes somewhere an gets a count of all the nuggets.  SetNuggetCount(x) suggests that you are assigning a new value to the count of nuggets.  NuggetCount all by itself suggests a property or local variable that is simply holding a value.  To that last one, one may be tempted to say, "Ah ha!  That is the question.  Property or variable?  WHICH IS IT?"  To that, I'd reply with, "Does it really matter?"

So here's the tl;dr;:  What are the objective, logical, non-arbitrary reasons to use lowercase for the first word in your variable or return method?

Edit:  For MainMa

Replace this code with the first code sample in your answer and see how well your argument holds up:

```<code>public void ComputeMetrics()
{
    const int MaxSnapshots = 20;

    var Snapshots = this.LiveMeasurements.IsEnabled ?
        this.GrabSnapshots(MaxSnapshots, this.cache) :
        this.LoadFromMemoryStorage();

    if (!Snapshots.Any())
    {
        this.Report(LogMessage.SnapshotsAreEmpty);
        return;
    }

    var MeasurementCount = Measurements.Count();
    this.Chart.Initialize((count + 1) * 2);

    foreach (var s in Snapshots)
    {
        this.Chart.AppendSnapshot(s);
    }
}
</code>```


答:
1. Why the standard exists?

After all, wouldn't it be better to let everyone write the code according to personal preference, and stop talking about which standard is better?

The fact is that when you're habituated to one style, it is more difficult to read code which uses a different style. Your brain spends more time trying to understand the convention (if there is any), instead of understanding what the code does.

What is more readable between those two pieces of code?

```<code>public void comp_metrics ()
{
  int Count;
  List<snapshot> measurements=fromMemoryStorage();
  if (_liveMeasurements.enabled)
    measurements = GrabSnapshots(20, _cache);
    if( !measurements.Any() ) {
        this.Report(LogMessage.Measurements_Are_Empty); return;
    }

    Count = measurements.Count ();

    this.Chart.initialize(( Count + 1 )*2);

    foreach(snapshot S in measurements) {
      this.Chart.append_Snapshot ( S );
    }
}
</code>```

or:

```<code>public void ComputeMetrics()
{
    const int MaxSnapshots = 20;

    var snapshots = this.liveMeasurements.isEnabled ?
        this.GrabSnapshots(MaxSnapshots, this.cache) :
        this.LoadFromMemoryStorage();

    if (!snapshots.Any())
    {
        this.Report(LogMessage.SnapshotsAreEmpty);
        return;
    }

    var count = measurements.Count();
    this.Chart.Initialize((count + 1) * 2);

    foreach (var s in snapshots)
    {
        this.Chart.AppendSnapshot(s);
    }
}
</code>```

Both pieces of code execute similarly. The only difference is that in the first case, each developer who worked on the project used his own style. This made the code inconsistent, unreadable and hazardous. The fact that members of the team were unable to agree about the indent size, coupled with the fact that one of them was refusing to use curly braces after every if made the code extremely error prone: looking at it, we may believe that the second if is executed only when the first if is true, which is not the case.

In the second case, all developers followed the same standard. Some of them were maybe unhappy, because they preferred two spaces indentation or because they were used to methods which start with a small letter. The fact is that the code is still much more readable this way, and still would be if they were using any different standard.

By having a strict, uniform standard, it makes the code easier to read.

2. Why their standard is better than the one I invented right now?

If a standard is used by hundreds of thousands of developers around the world, just stick with it. Don't invent your own: even if it's better, it's easier for you to migrate to the global standard rather than to those hundreds of thousands of developers to start using yours.

Example: in my own company, I have a specific convention for naming primary and foreign keys and indexes in the database. Those names look like:

[FK for Application: CreatedByApplicationId],

[IX for SessionIPAddress: SessionId] or

[PK for RoleOfPassword: RoleId, PasswordId].

Personally, I find this convention excellent and extremely clear. For me. But it totally sucks. It sucks, because it's mine, and because no one of thousands of database administrators never used it. This means that:

When I will hire a DBA, he will be forced to learn the new convention, instead of starting his work right now,

I can't share pieces of code on the internet as is: those strangely looking names will disrupt people who will read my code,

If I take code from the outside in order to use it in my own, I would be forced to modify the names in order to make it uniform,

If one day I decide to use some well-known standard, I will be forced to go and modify every of the few hundred names.

3. So, what about capitalization?

Properties have a larger scope or visibility than fields or local variables. Making properties start with a capital letter, and fields and variables - with a small one goes in this direction.

If you consider C#, this logic is consistent enough.

If you consider Java, methods start with small letters, which doesn't follow the logic.

So no, there is no definitive proof that this convention is better then yours. It's just that the one is used globally, and yours is not. None is better.

In JavaScript, functions start with a small letter, unless they require a new before them. Wouldn't it better the other way? Maybe. The fact is that for years, JavaScript developers used this standard, and not the opposite. Rewrite every book and force every developer to change the style now would be slightly complicated.

Body:
1. Why the standard exists?

After all, wouldn't it be better to let everyone write the code according to personal preference, and stop talking about which standard is better?

The fact is that when you're habituated to one style, it is more difficult to read code which uses a different style. Your brain spends more time trying to understand the convention (if there is any), instead of understanding what the code does.

What is more readable between those two pieces of code?

public void comp_metrics ()
{
  int Count;
  List<snapshot> measurements=fromMemoryStorage();
  if (_liveMeasurements.enabled)
    measurements = GrabSnapshots(20, _cache);
    if( !measurements.Any() ) {
        this.Report(LogMessage.Measurements_Are_Empty); return;
    }

    Count = measurements.Count ();

    this.Chart.initialize(( Count + 1 )*2);

    foreach(snapshot S in measurements) {
      this.Chart.append_Snapshot ( S );
    }
}

or:

public void ComputeMetrics()
{
    const int MaxSnapshots = 20;

    var snapshots = this.liveMeasurements.isEnabled ?
        this.GrabSnapshots(MaxSnapshots, this.cache) :
        this.LoadFromMemoryStorage();

    if (!snapshots.Any())
    {
        this.Report(LogMessage.SnapshotsAreEmpty);
        return;
    }

    var count = measurements.Count();
    this.Chart.Initialize((count + 1) * 2);

    foreach (var s in snapshots)
    {
        this.Chart.AppendSnapshot(s);
    }
}

Both pieces of code execute similarly. The only difference is that in the first case, each developer who worked on the project used his own style. This made the code inconsistent, unreadable and hazardous. The fact that members of the team were unable to agree about the indent size, coupled with the fact that one of them was refusing to use curly braces after every if made the code extremely error prone: looking at it, we may believe that the second if is executed only when the first if is true, which is not the case.

In the second case, all developers followed the same standard. Some of them were maybe unhappy, because they preferred two spaces indentation or because they were used to methods which start with a small letter. The fact is that the code is still much more readable this way, and still would be if they were using any different standard.

By having a strict, uniform standard, it makes the code easier to read.

2. Why their standard is better than the one I invented right now?

If a standard is used by hundreds of thousands of developers around the world, just stick with it. Don't invent your own: even if it's better, it's easier for you to migrate to the global standard rather than to those hundreds of thousands of developers to start using yours.

Example: in my own company, I have a specific convention for naming primary and foreign keys and indexes in the database. Those names look like:

[FK for Application: CreatedByApplicationId],

[IX for SessionIPAddress: SessionId] or

[PK for RoleOfPassword: RoleId, PasswordId].

Personally, I find this convention excellent and extremely clear. For me. But it totally sucks. It sucks, because it's mine, and because no one of thousands of database administrators never used it. This means that:

When I will hire a DBA, he will be forced to learn the new convention, instead of starting his work right now,

I can't share pieces of code on the internet as is: those strangely looking names will disrupt people who will read my code,

If I take code from the outside in order to use it in my own, I would be forced to modify the names in order to make it uniform,

If one day I decide to use some well-known standard, I will be forced to go and modify every of the few hundred names.

3. So, what about capitalization?

Properties have a larger scope or visibility than fields or local variables. Making properties start with a capital letter, and fields and variables - with a small one goes in this direction.

If you consider C#, this logic is consistent enough.

If you consider Java, methods start with small letters, which doesn't follow the logic.

So no, there is no definitive proof that this convention is better then yours. It's just that the one is used globally, and yours is not. None is better.

In JavaScript, functions start with a small letter, unless they require a new before them. Wouldn't it better the other way? Maybe. The fact is that for years, JavaScript developers used this standard, and not the opposite. Rewrite every book and force every developer to change the style now would be slightly complicated.


答:
That naming convention is often used when people want to be able to give a variable the same name as its type.  For example:

```<code>Employee employee;
</code>```

Some languages even enforce that capitalization.  This prevents having to use annoying variable names like MyEmployee, CurrentEmployee, EmployeeVar, etc.  You can always tell if something is a type or a variable, just from the capitalization.  That prevents confusion in situations like:

```<code>employee.function(); // instance method
Employee.function(); // static method
</code>```

Also, in English, nouns are not generally capitalized, so you can't really claim your capitalization is "proper."

So what does that have to do with your situation?  You obviously have no trouble reading your own code, but by keeping things as consistent as possible, you reduce the mental workload of anyone else needing to read your code.  In coding as in writing, you adjust your style to match the readers.

Body:
That naming convention is often used when people want to be able to give a variable the same name as its type.  For example:

Employee employee;

Some languages even enforce that capitalization.  This prevents having to use annoying variable names like MyEmployee, CurrentEmployee, EmployeeVar, etc.  You can always tell if something is a type or a variable, just from the capitalization.  That prevents confusion in situations like:

employee.function(); // instance method
Employee.function(); // static method

Also, in English, nouns are not generally capitalized, so you can't really claim your capitalization is "proper."

So what does that have to do with your situation?  You obviously have no trouble reading your own code, but by keeping things as consistent as possible, you reduce the mental workload of anyone else needing to read your code.  In coding as in writing, you adjust your style to match the readers.


问:
Are there any benefits to removing unused using statements in a VS project?
Are there any benefits to removing unused using statements in a VS project (such as can be done using Resharper), or will VS automatically take care of that when building/deploying?</p>

答:
There aren't any performance benefits, if that's what you mean.

All references in an assembly are fully qualified; the compiler merely uses the references you provide in your code to fully qualify identifiers, so the only impact of unused references in your source code is a slight decrease in readability (why is this reference here?), and a trivial increase in compile time.

To put it another way, the generated IL is exactly the same whether you remove the unused references or not.


问:
Is it good practice to catch a checked exception and throw a RuntimeException?
I read some code of a colleague and found that he often catches various exceptions and then always throws a 'RuntimeException' instead. I always thought this is very bad practice. Am I wrong?</p>

答:
This might depend on case to case basis. In certain scenarios it is wise to do what your friend is doing, for example when you are exposing an api for some clients and you want the client to be least aware of the implementation details, where you know that certain implementation exceptions may be specific to implementation details and not exposable to the client.

By keeping the checked exceptions out of the way, you can expose api's that would enable the client to write cleaner code as the client itself might be pre-validating the exceptional conditions.

For example Integer.parseInt(String) takes a string and returns the integer equivalent of it and throws NumberFormatException in case the string is not numeric. Now imagine a form submission with a field age is converted through this method but the client would have already ensured validation on its part, so there's no point forcing the check of exception.


问:
What stops HTML5 and JS apps to perform as good as native apps?
From what I understand,

HTML is a mark-up language, so is the content of XAML, XIB and
whatever Android uses and other native UI development frameworks.

JavaScript is a programming language used along with it to handle
client side scripting which will include things like event handling,
client side validations and anything else C#,Java,Objective-C or C++
do in various such frameworks.

There are MVC/MVVM patterns available in form frameworks like Sencha's, Angular etc.

We have localStorage in form of both sqlite and key-value store as other frameworks have and you have API specification for almost everything that it missing.

Whenever a native UI frameworks has to render UI , it has to parse a similar the markup and render the UI.

Question break-down

What stops from doing the same in HTML and JS itself ?

Instead of having a web-control or browser as a layer in between why can't HTML(along with CSS) and JS be made to perform the same way ?

Even if there is a layer,so does .net runtime and JVM are in other cases where C++,C are not being used.

So Lets take the case of Android, like Dalvik, why Can't Chromium be another option(along with dalvik and NDK) where HTML does what android markup does and JavaScript is used to do what Java does ?

So the Question is,

Even if current implementations aren't as good, but theoretically is it possible to get HTML5 based applications to work as other native apps specially on mobile ?

答:
A lack of a Javascript standard library is a horrible inhibitor. There are great frameworks like jQuery, Dojo, YUI, to name a few, but all of them are solely focused on the presentation layer and XHR.

Do you want configurable logging, cryptographic tools, graph algorithms, UUID generators, Maps, Sets, Trees, templates, dependency management, date manipulation, localization/internationalization, matrix operations, dependency injection, unit tests, map-reduce, XML processing? Trivial for JVM or .NET languages - in Javascript you often have to roll your own implementation.


答:
This is common practice in many frameworks. E.g. Hibernate does exactly this. The idea is that the APIs should not be intrusive for client side and Exception are intrusive since you must explicitly write code to handle them at that place where you call the api. But that place might not be the right place to handle the exception in the first place.

Actually to be honest this is a "hot" topic and many dispute so I will not take a side but I will say that what your friend does/proposes is not un-ordinary or uncommon.

Title: Is it good practice to catch a checked exception and throw a RuntimeException?

Body: I read some code of a colleague and found that he often catches various exceptions and then always throws a 'RuntimeException' instead. I always thought this is very bad practice. Am I wrong?</p>


问:
What determines which Javascript functions are blocking vs non-blocking?
I have been doing web-based Javascript (vanilla JS, jQuery, Backbone, etc.) for a few years now, and recently I've been doing some work with Node.js. It took me a while to get the hang of "non-blocking" programming, but I've now gotten used to using callbacks for IO operations and whatnot.

I understand that Javascript is single-threaded by nature. I understand the concept of the Node "event queue". What I DON'T understand is what determines whether an individual javascript operation is "blocking" vs. "non-blocking". How do I know which operations I can depend on to produce an output synchronously for me to use in later code, and which ones I'll need to pass callbacks to so I can process the output after the initial operation has completed? Is there a list of Javascript functions somewhere that are asynchronous/non-blocking, and a list of ones that are synchronous/blocking? What is preventing my Javascript app from being one giant race condition?

I know that operations that take a long time, like IO operations in Node and AJAX operations on the web, require them to be asynchronous and therefore use callbacks - but who is determining what qualifies as "a long time"? Is there some sort of trigger within these operations that removes them from the normal "event queue"? If not, what makes them different from simple operations like assigning values to variables or looping through arrays, which it seems we can depend on to finish in a synchronous manner?

Perhaps I'm not even thinking of this correctly - hoping someone can set me straight. Thanks!

答:
In general, any function that does networking or uses timers to do things over a period of time will be asynchronous.

If the function takes a callback, you can look at what the callback is used for and usually it will be obvious whether is is asynchronous or not.  If the function does not offer a callback, then it has no way of communicating asynchronous results so it is probably not asynchronous.

There's no ironclad way to tell for sure.  It has to either be spelled out in the doc for a function or obvious from the way the interface works.

Asynchronous operations are different under the covers than synchronous operations in that asynch operations have the notion of setting up an operation, starting the operation and then getting notified later of progress, completion or errors in the operation.  Iterating an array is a synchronous operation.  It has none of these issues.  The code just runs synchronously.  Issuing an ajax call consists of registering a callback for state notifications, then starting the ajax call, then continuing to run other javascript and then some time later, the callback is called with a state change on the ajax call (such as completion).


答:
From what I understand you're not asking about what you should make asynchronous but how to tell if a function is asynchronous.

You check the documentation. Seriously - that's what it's for. You don't guess what a function does based on its name or its context just like that. If you're not sure and have access to its source code you check that.

That's the only completely reliable way.

Now for guesstimating.

If it accepts a callback or returns a promise it's probably asynchronous (I've seen exceptions for that rule)

Generally everything that is I/O related in node.js and more generally in JavaScript is done asynchronously (I've seen exceptions to that rule too)

Title: What determines which Javascript functions are blocking vs non-blocking?

Body:
I have been doing web-based Javascript (vanilla JS, jQuery, Backbone, etc.) for a few years now, and recently I've been doing some work with Node.js. It took me a while to get the hang of "non-blocking" programming, but I've now gotten used to using callbacks for IO operations and whatnot.

I understand that Javascript is single-threaded by nature. I understand the concept of the Node "event queue". What I DON'T understand is what determines whether an individual javascript operation is "blocking" vs. "non-blocking". How do I know which operations I can depend on to produce an output synchronously for me to use in later code, and which ones I'll need to pass callbacks to so I can process the output after the initial operation has completed? Is there a list of Javascript functions somewhere that are asynchronous/non-blocking, and a list of ones that are synchronous/blocking? What is preventing my Javascript app from being one giant race condition?

I know that operations that take a long time, like IO operations in Node and AJAX operations on the web, require them to be asynchronous and therefore use callbacks - but who is determining what qualifies as "a long time"? Is there some sort of trigger within these operations that removes them from the normal "event queue"? If not, what makes them different from simple operations like assigning values to variables or looping through arrays, which it seems we can depend on to finish in a synchronous manner?

Perhaps I'm not even thinking of this correctly - hoping someone can set me straight. Thanks!


问:
Working for free?
I came across this article Work for Free that got me thinking.

The goal of every employer is to gain
  more value from workers than the firm
  pays out in wages; otherwise, there is
  no growth, no advance, and no
  advantage for the employer.
  Conversely, the goal of every employee
  should be to contribute more to the
  firm than he or she receives in wages,
  and thereby provide a solid rationale
  for receiving raises and advancement
  in the firm.

I don't need to tell you that the
  refusenik didn't last long in this
  job.

In contrast, here is a story from last
  week. My phone rang. It was the
  employment division of a major
  university. The man on the phone was
  inquiring about the performance of a
  person who did some site work on
  Mises.org last year. I was able to
  tell him about a remarkable young man
  who swung into action during a crisis,
  and how he worked three 19-hour days,
  three days in a row, how he learned
  new software with diligence, how he
  kept his cool, how he navigated his
  way with grace and expertise amidst
  some 80 different third-party plug-ins
  and databases, how he saw his way
  around the inevitable problems, how he
  assumed responsibility for the
  results, and much more.

What I didn't tell the interviewer was
  that this person did all this without
  asking for any payment. Did that fact
  influence my report on his
  performance? I'm not entirely sure,
  but the interviewer probably sensed in
  my voice my sense of awe toward what
  this person had done for the Mises
  Institute. The interviewer told me
  that he had written down 15 different
  questions to ask me but that I had
  answered them all already in the
  course of my monologue, and that he
  was thrilled to hear all these
  specifics.

The person was offered the job. He had
  done a very wise thing; he had earned
  a devotee for life.

The harder the economic times, the
  more employers need to know what they
  are getting when they hire someone.
  The job applications pour in by the
  buckets, all padded with degrees and
  made to look as impressive as
  possible. It's all just paper. What
  matters today is what a person can do
  for a firm. The resume becomes pro
  forma but not decisive under these
  conditions. But for a former boss or
  manager to rave about you to a
  potential employer? That's worth
  everything.

What do you think? Has anyone here worked for free? If so, has it benefited you in any way? Why should(nt) you work for free (presuming you have the money from other means to keep you going)? Can you share your experience?

Me, I am taking a year out of college and haven't gotten a degree yet so that's probably why most of my job applications are getting ignored. So im thinking about working for free for the experience?

答:
work for free for the experience and for the reference if you're desperate

better, work for free on your stuff so that you own it

ContentLicense: CC BY-SA 2.5

Title: Working for free?


答:
Since JavaScript is single threaded all processing blocks until one of the following occurs

1) The current execution requests an external service such as an I/O or networking request, or a webworker request

2) A function call is put on a timer to be executed at a later time

There's no list of blocking/non-blocking functions. You should check the documentation.

Your app can encounter a race condition if multiple external services have a lock on the javascript thread and try to access it at the same time.  Modern browsers and the V8 engine handle this, but you may encounter this race condition if you use phonegap and write javascript apps for mobile devices. The support isn't there to handle these race conditions.

In general, assume the code blocks unless there's a callback.  And even if there's a callback, that doesn't mean it won't block.


答:
Technically, it doesn't matter (or at least, in most languages it doesn't).

However, most programming communities (whether those are world-wide communities that have formed around one particular language, sub-groups of such communities, groups that have formed around some popular library or toolkit, or just individual teams) have developed established coding standards. The exact details are relatively unimportant (though in many cases, a good argument can be made for them), what is important is that you stick to them.

Not because they're the best, but because they are what everyone else uses; if you stick with the standard, your code will be consistent with most of the other code that you will eventually end up using - libraries, teammates' code, language built-ins. Consistent naming is one powerful productivity weapon, because it means that when you guess the name of something, you will usually guess right. Is it file.SaveTo(), File.saveTo(), file.save_to(), FILE.save_to()? The naming convention will tell you.

Carrying your personal preferences into every language you encounter is particularly hazardous, because first of all, every language has its own culture, and the naming conventions are often incompatible; and second, there are many subtle differences between languages as far as naming is concerned.

Just one example: in C#, types and variables live in separate namespaces; the compiler is smart enough to know the difference. In C, however, both kinds of names share a namespace, so you can't have a type and a variable of the same name within the same scope. Because of this, C needs a naming convention that distinguishes types from variables, while C# doesn't.


问:
What should I include in my repositiory from IDE projects
I want to add a project which in this case is created in Netbeans but this question is general for most IDE's. It's simply, what should I include in my repository. For example Netbeans creates a nbproject folder, eclipse creates a .settings folder etc. should I include these in my repository, what are the advantages/disadvantages of including or not including project specific settings. </p>

<p>In this case it's a personal project so I don't imagine that other people will start working on it, but it would be nice to add the bare minimum of project settings so the project itself will be easy to start work on different machines. </p>

答:
This really depends on what kind of information you would like to have on the repository. If you want everything right down to which files you had open and were editing at the time of the commit, and you're the only one using the repository, go ahead and commit it all, but know that it may not work on another machine.

If you want to be able to share your code with other people who might not be using the same IDE, then just commit the code itself without any project specific implementation.

If you know that everyone uses the same IDE, then you can probably include anything which isn't computer specific, that is any setting files/folders for just the IDE itself, that way they can already have the ability to import the project as the IDE expects it.


答:
I'm surprised no one else has said this, but I think the capitalization difference is amazingly helpful for one reason: it's nice and convenient to be able to know whether a variable is only locally scoped or not. If the variable is local than I don't worry as much about side effects of changing it, such as refactoring the name. So I like a convention that distinguishes class members versus private class variables versus local variables.

With modern Intellisense, this matters less and less, but it still gives me some landmarks as I read code to know where I should look to find the definition.

And a fair bit of this may be left over from my worse style years ago, when methods weren't as likely to fit on one screen.


答:
This seems more like a question of conventions rather than your specific convention.

For every convention you break, you're just adding more work for everyone else. Perhaps in a perfect world, the entire company works on a single product their entire lives... however, in reality, this is not true. People jump between projects, sometimes across companies or even for fun. The more random the code is, the harder and more expensive it is to work on. As a business owner or stakeholder, I wouldn't want to hire developers who think selfishly rather than for the good of the project.

This boils down to professionalism: sometimes we need to put our personal styles aside and go with what is more efficient for mass adoption. This encourages collaboration and removes extraneous barriers that shouldn't be there in the first place.

As for your actual convention, CapitalCamelCase is usually reserved for class names (or in Javascript, constructors). If I see a capitalized variable, an educated guess will dictate I'll need to instantiate it to use it. If that's wrong, I'm going to be pissed off that the code isn't following community standards. Even with most other languages, everybody else looking at it for the first time is instantly being misled. I want code to be obvious, not misleading.


问:
Are there elements common to nearly every SRS?
An SRS is a staple of any serious contract work, and it can be incredibly dull for those who've never had the misfortune of needing to read one through in one go.

I'm writing a series of document classes with LaTeX (markup language for profession-quality documents; see these questions and this answer on TeX.SE) and, in so doing, I need to define the core tenets and common logical structures evident through any reasonable SRS.

I have unfortunately never had the opportunity to participate in the creation of an SRS from scratch save a simplified, somewhat contrived example during college, so I don't think I know the breadth of what goes into a Software Requirements Specification (SRS).  I do know it consists of at least the changelog and the requirements themselves, but beyond that... ?

What are the indispensable parts of the document that every SRS should have?

I'm still pretty new here, but I'm open to making this CW if Programmers.SE is all about this kind of stuff.

答:
If you can find it, the old DOD-STD-2167A Software Requirements (SRS) Specification Data Item Description (DID) tells you what the DoD wanted in an SRS, and how they wanted it.  This will give you a very good start.

From memory, the SRS DID calls for a (boilerplate) Scope section, a Referenced Documents section, the Requirements section(s), and the Requirements Traceability Matrix.  That last usually traces software requirements back to system requirements, and includes at least perfunctory information FOR EACH INDIVIDUAL REQUIREMENT about how you plan to test the system to determine whether it does or does not meet that requirement.  (These are usually just one word: Inspection, Demonstration, Test, Analysis.)

If you have beaucoup money to waste, you could buy the IEEE software standards.  They basically boil down to "The contractor will deliver whatever the *bleep* he feels like, and call it an SRS."

The changelog is not absolutely critical, as you are going to be maintaining your SRS in some kind of configuration management system, preferably a Requirements Management System like DOORS.  (You are a fool if you don't.)

It should go without saying that requirements and ONLY requirements go in the SRS.  If it ain't a requirement, it don't belong in the SRS.  Period.


答:
As others have said no real reason, except for getting a naming convention down pat. If you can get your whole team on the same page you can probably save yourself some time. For instance personally I started a coding standards thing which went into this and we used camelCase for all private varials as well as things passed byVal, whereas we used PascalCase for things that are public as well as things passed by Ref.

Lines get a little blurry when dealing with things like protected or Out or something.


答:
Artifacts that help your development and are of no use to the build/release or the project itself should not be included. The repo should be clean and tidy and only have those things which are relevant to the project not your environment. The repo should be incognizant of your habits. And secondly it will unnecessarily bug you when do something akin to git status ... but hey I never made any changes...ahh ignore that.

Let me give a more practical example (I'll use githere as a tool):

You would never want a (recursive)submodule inside your main repo to have an IDE specific stuff(it might interfere with main project environment as well) because all you care about is the code that was written by someone else(or you) and is of use inside the current project. Not the environment in which it was developed. You probably don't want to do that to someone else either.

To be able to use your setting on different machine I suggest digging inside your IDE and see what support it provides for such things. Emacs has init and Emacs server too. Or you could make your custom macro or script(.sh) which does the setup automatically.

Title: What should I include in my repositiory from IDE projects

Body:
I want to add a project which in this case is created in Netbeans but this question is general for most IDE's. It's simply, what should I include in my repository. For example Netbeans creates a nbproject folder, eclipse creates a .settings folder etc. should I include these in my repository, what are the advantages/disadvantages of including or not including project specific settings. </p>

<p>In this case it's a personal project so I don't imagine that other people will start working on it, but it would be nice to add the bare minimum of project settings so the project itself will be easy to start work on different machines. </p>


答: Lower case should be used for local variables for ease of typing (speed / no shift key). Upper case is used to help readability by separating the words within a name. Code with single-word local variable names (which should be common) are fast and easy to type. The use of upper case for each new word in the name is also faster (and less space) than using underscores which add another character - this is also known as camel-case.</p>


答:
It really depends on what data it is and should be decided on a case by case basis, perhaps even for individual files. Take a look at the contents of those files. More often than not you can tell what they mean. Stuff like the position and size of the IDE's windows is something you do not want in source control.

But some of the IDE project files are vital project metadata. I don't know Netbeans well, but for eclipse, the .project file tells the IDE  what the project's name is, that it's a Java web project, etc. and the .classpath file contains information about source folders and libraries. Some files in the .settings directory can be equally important, e.g. org.eclipse.core.resources.prefs contains information about what encoding should be used for which files.

As project metadata, this stuff very much deserves to be versioned in source control.

Some IDEs can import project metadata from other IDEs. It would be even better to have it in a form that is not tied to a specific IDE.

For Java, there is such a thing: Maven. It imposes strong conventions on the project's structure and allows you to specify project metadata (such as library dependencies) in one point (a file called pom.xml which is in the project's main directory and, of course, in source control). There are plugins which then create IDE project files from the Maven configuration, and others which can automate the project build process, or do just about anything. Sometimes it feels like it makes things unneccessarily complex and it takes some time to learn, but the benefits are generally worth it.


问:
Wouldn't Layer Supertype pattern corrupt our domain model?
a) To my knowledge Domain Objects should for the most part be oblivious to technical aspects of a design. Since I view class inheritance as being a technical solution, wouldn't introducing a Layer Supertype pattern into our domain corrupt it?

b) If you disagree, please elaborate why

Thanks

答:
The idea behind the Layer Supertype pattern is that there might be attributes or methods that every object in the layer must have by virtue of being in that layer.  Fowler uses the example of Domain Objects (in Patterns of Enterprise Architecture) all having an ID, which makes some sense--if you are a domain entity, you must have some sort of identity.  So, the pattern is to extract those shared attributes into a super type, and then have all the classes in that layer extend that type.

This really isn't a case of corrupting the domain model, in that we're not adding anything "technical" to the domain objects--we are simply abstracting out the common attributes.

It's a design pattern because people have found that it's a useful thing to do.


问:
Is this considered an implementation of a Layer Supertype pattern?
1. According to Fowler's definition this pattern is implemented by having all classes in a layer inherit from a superclass. But after some googling it appears all of the following are considered as implementations of a Layer Supertype pattern:

a - all classes in a layer inheriting from the same superclass

b - having only some ( thus not all ) of classes in a layer inheriting from a superclass

c - layer having superclasses S1 and S2, where classes A and B inherit from S1, while C inherits from S2

So which of above are considered as implementations of a Layer Supertype?

2. If a,b and c are all considered implementations of a Layer SuperType, then I fail to see how this pattern is any different from a regular class inheritance. In other words, couldn't we then claim we're using Layer Supertype any time some class inherits from another class?

thanks

答:
As defined by Fowler, only a would be a Layer Supertype.  However, people consider the others Layer Supertypes in that they are specific to a layer--all of the subtypes of the supertype must exist and be relavant to the same layer.

Consider, for example, the view layer in an MVC application.  You might have the windows or pages all extend a single supertype, but also have helper classes or strategy classes that also live in the layer to support the view.  The supertype is very much tied to the layer, in this case, even though it does not underlie everything.  I don't think it's wrong to call this a layer superclass.


问:
What's the career path for a developer who doesn't like management?
If you're developer (Senior or Lead Developer) and you'd rather stay with code/design than pursue a management career, what are the available career paths at your company, or any you've heard of? How far can you go?

Is it possible to continue being a geek until you bite the dust or is that too naive?

Are people like Uncle Bob for example still considered developers, as they claim?

答:
Texas Instruments had a dual ladder when I was there.

Engineer Associate

Engineer

Senior Engineer

---- from here on, you had to be nominated in by someone already higher up

Member of the Group Technical Staff

Senior Member of the Technical Staff

(maybe) Distinguished Member of the Technical Staff

TI Fellow

TI Senior Fellow

TI Principal Fellow (there was only one of these in the company,
as far as I know)


问:
Are my method or variable names too long?
So I was currently in the middle of coding, unfortunately for me, I was in "The Zone" then I thought to myself, are my method/variable names to long?

POP out of the Zone I go!

So I came here to ask, are my method/variable names too long? You be the Judge! Bonus points to anyone who can figure out what I'm writing, although I'm sure a guru will figure it out fast!

Anyway, here are some of my method and variable names.

Methods :

searchBlockedListForBlockedSquares(),

isCurrentSquareNextToAtLeastOneBlockedSquare(),

searchBlockedListForBlockedSquares()

Variables:

isNextToBlockedSquares

I guess there was only one variable that seemed too long.

答:
I believe in descriptive variable names even if that means long variable names. And with  intellisense getting more popular, I don't believe it affects much in terms of productivity.

I hate abbreviations because they are nearly impossible to consistently use. Plus, they can be ambiguous and they do make things more difficult to read. Even when they are part of a standard, I don't like them. Plus, when it comes down to it, they don't remove that many letters unless you abbreviate a lot. And abbreviating a lot kills readability.

The biggest problem long names introduces though is how long lines of code can become. Calling a function with a long name and passing it two or three long variable names can make for one long line of code. Because of that, I do try to keep my names as short as possible though again, I'd rather have descriptive names even if it means wrapping lines or scrolling.

Looking at your example names though, the fact that all end with BlockedSquares makes me think that part of the name might be redundant. In fact, it might also mean that these items can be encapsulated into their own class, probably named BlockedSquares. That change that makes the  names quite  a bit shorter.

ContentLicense: CC BY-SA 4.0


问:
Array Multiplication and Division
I came across a question that (eventually) landed me wondering about array arithmetic. I'm thinking specifically in Ruby, but I think the concepts are language independent.

So, addition and subtraction are defined, in Ruby, as such:

```<code>[1,6,8,3,6] + [5,6,7] == [1,6,8,3,6,5,6,7] # All the elements of the first, then all the elements of the second
[1,6,8,3,6] - [5,6,7] == [1,8,3] # From the first, remove anything found in the second
</code>```

and array * scalar is defined:

```<code>[1,2,3] * 2 == [1,2,3,1,2,3]
</code>```

But

What, conceptually, should the following be? None of these are (as far as I can find) defined:

Array x Array: [1,2,3] * [1,2,3] #=> ?

Array / Scalar: [1,2,3,4,5] / 2 #=> ?

Array / Scalar: [1,2,3,4,5] % 2 #=> ?

Array / Array: [1,2,3,4,5] / [1,2] #=> ?

Array / Array: [1,2,3,4,5] % [1,2] #=> ?

I've found some mathematical descriptions of these operations for set theory, but I couldn't really follow them, and sets don't have duplicates (arrays do).

Edit: Note, I do not mean vector (matrix) arithmetic, which is completely defined.

Edit2: If this is the wrong stack exchange, tell me which is the right one and I'll move it.

Edit 3: Add mod operators to the list.

Edit 4:

I figure array / scalar is derivable from array * scalar:

```<code>a * b = c
=> a = b / c

[1,2,3] * 3 = [1,2,3]+[1,2,3]+[1,2,3] = [1,2,3,1,2,3,1,2,3]
=> [1,2,3] = [1,2,3,1,2,3,1,2,3] / 3
</code>```

Which, given that programmer's division ignore the remained and has modulus:

```<code>[1,2,3,4,5] / 2 = [[1,2], [3,4]]
[1,2,3,4,5] % 2 = [5]
</code>```

Except that these are pretty clearly non-reversible operations (not that modulus ever is), which is non-ideal.

Edit: I asked a question over on Math that led me to Multisets. I think maybe extensible arrays are "multisets", but I'm not sure yet.

答:
In my opinion, there is no reason that arithmetic operators ought to apply to arrays. Attempting to force arrays to have meaningful semantics with arithmetic operators is confusing, and confusion is the source of bugs. Even the Ruby semantics you name are not as obvious as you might think.

For example, notice the behavior of multiplication by a scalar. It might be reasonable to assume that multiplication by an integer will be equivalent to repeated addition, but that isn't the case:

```<code>[1, 2, 3] * 2 == [2, 4, 6]
[1, 2, 3] + [1, 2, 3] == [1, 2, 3, 1, 2, 3]
</code>```

(I haven't checked this, but am going on what you posted.) As such, it can be argued that multiplication by a scalar behaves non-intuitively. (On the other hand, it behaves exactly like vector multiplication by a scalar, so in that sense it is intuitive. Still, notice that vector multiplication by a scalar is not an arithmetic operation.)

What should the behavior of these other operators be? In my opinion, it was a mistake to provide operator+ etc. for arrays, precisely because these operators cannot behave similarly to the usual arithmetic operators - it would have been better to either expand the set of available operators (to define unique operators that make sense with arrays -- to borrow an example, Haskell uses ++ for array concatenation), OR to use non-operator functions to implement these semantics (for example, [1, 2, 3].append [4, 5, 6] may behave similarly to [1, 2, 3] + [4, 5, 6]).

In any case, I would not overload the meanings of operator symbols across unrelated types like this.

Title: Array Multiplication and Division

Body:
In my opinion, there is no reason that arithmetic operators ought to apply to arrays. Attempting to force arrays to have meaningful semantics with arithmetic operators is confusing, and confusion is the source of bugs. Even the Ruby semantics you name are not as obvious as you might think.

For example, notice the behavior of multiplication by a scalar. It might be reasonable to assume that multiplication by an integer will be equivalent to repeated addition, but that isn't the case:

[1, 2, 3] * 2 == [2, 4, 6]
[1, 2, 3] + [1, 2, 3] == [1, 2, 3, 1, 2, 3]

(I haven't checked this, but am going on what you posted.) As such, it can be argued that multiplication by a scalar behaves non-intuitively. (On the other hand, it behaves exactly like vector multiplication by a scalar, so in that sense it is intuitive. Still, notice that vector multiplication by a scalar is not an arithmetic operation.)

What should the behavior of these other operators be? In my opinion, it was a mistake to provide operator+ etc. for arrays, precisely because these operators cannot behave similarly to the usual arithmetic operators - it would have been better to either expand the set of available operators (to define unique operators that make sense with arrays -- to borrow an example, Haskell uses ++ for array concatenation), OR to use non-operator functions to implement these semantics (for example, [1, 2, 3].append [4, 5, 6] may behave similarly to [1, 2, 3] + [4, 5, 6]).

In any case, I would not overload the meanings of operator symbols across unrelated types like this.


问:
Refactoring classes with ref to themselves
How can I refactor this code?

```<code>class Node
{
   public Node Parent { get; set; }
}

class AVLNode
{
   public AVLNode Parent { get; set; }
}
</code>```

I tried to use inheritance, but then I have to use type casting:

```<code>class AVLNode : Node
{
}

class Program
{
   void Main()
   {
      AVLNode a = new AVLNode();
      AVLNode b = a.Parent **as AVLNode**;
   }
}
</code>```

答:
Try creating a generic interface (INode<out T>). You code will change into something like this:

```<code>interface INode<out T>
{
  T Parent { get; set; }
}

class Node : INode<Node>
{
  public Node Parent { get; set; }
}

class AVLNode : INode<AVLNode>
{
  public AVLNode Parent { get; set; }
}
</code>```

Your calling code is simply:

```<code>AVLNode a = new AVLNode();
AVLNode b = a.Parent;
</code>```

Body:
Try creating a generic interface (INode<out T>). You code will change into something like this:

interface INode<out T>
{
  T Parent { get; set; }
}

class Node : INode<Node>
{
  public Node Parent { get; set; }
}

class AVLNode : INode<AVLNode>
{
  public AVLNode Parent { get; set; }
}

Your calling code is simply:

AVLNode a = new AVLNode();
AVLNode b = a.Parent;


问:
Do preprocessor defines slow down build times?
I have a very large c++ project and I'm trying to decrease build times. I've been religious about forward declaring and only including files which are used. However I have many preprocessor defines which are setup in the project files (ie not in cpp or header files) so that I can keep them all in a central location for my different build configurations. Is it possible that this could increase build times? Would moving the preprocessor defines to a header file so they will only be included where needed speedup the build time?

It seems like the build time would be faster if the preprocessor didn't need to scan and replace the defines for files that don't use any of them, but I'm not sure if it's worth the effort.

答:
My experience with build time is pretty simple: it's about linear with number of translation units. So if you want to reduce it, either paste some sources together, or do "unity compile". the latter means you #include groups of .cpp files, and compile that instead of the originals. Certainly it means static symbols get shared. For variables it's not that hard to detect, for functions might be trickier.

A source that may be just 100 LOC, or a few thousands at most normally picks up 100k to 1M LOC in included headers. What explains the figures.

Other things to explore are obviously precompiled headers and parallel builds. With PCH rules change significantly, fight to not include stuff and stick to forwards can be dropped.

I doubt the #defines themselves would cause any measurable impact.

Certainly all depends much on what compiler you use.


答:
Ruby’s model is provided more for convenience than correctness, and is inconsistent:

array + array is array concatenation, allowing duplicates, but array - array is set difference, removing duplicates: [1, 1] - [1] is [], not [1].

- is not the inverse of +, because it’s not the case that a + b - c == a for all Array instances a, b, and c: take [1] + [1] - [1].

array * fixnum is defined as iterated array concatenation, but fixnum * array is not defined at all.

For purely array-based operations, I would expect + and - to be inverses:

```<code>[1, 2] + [3, 1] == [1, 2, 3, 1]
[1, 2, 3, 1] - [3, 1] == [1, 2]
</code>```

- would remove elements from the tail just as + added them. Similarly for * and /:

```<code>[1, 2] * 3 == [1, 2, 1, 2, 1, 2]
[1, 2, 1, 2, 1, 2] / 3 == [1, 2]
[5, 1, 2, 1, 2] / 2 == [1, 2]
</code>```

/ would first discard elements from the left until a.size % b == 0. Why from the left? Well, I would expect an array modulus operator to satisfy the law:

```<code>a % b == a - (b * (a / b))
</code>```

And that rule seems to work if you go through a few examples:

[1, 1] % 2 == [1, 1] - (2 * ([1, 1] / 2)) == []

[5, 1, 1] % 2 == [5, 1, 1] - (2 * ([5, 1, 1] / 2)) == [5]

This is basically defining division as iterated subtraction.

There are a couple of consistent and reasonably intuitive interpretations of array ♦ array:

Cartesian product: [1, 2] ♦ [3, 4] == [1 ♦ 3, 1 ♦ 4, 2 ♦ 3, 2 ♦ 4]

Pairwise product: [1, 2] ♦ [3, 4] == [1 ♦ 3, 2 ♦ 4]

With a Cartesian product, the size of the result is the product of the size of the inputs. This is how list comprehensions and the list monad work in Haskell:

```<code>[x ♦ y | x <- [1, 2], y <- [3, 4]]

do
  x <- [1, 2]
  y <- [3, 4]
  return (x ♦ y)
</code>```

A pairwise product also makes sense, in that ([x1, y1, z1] * [x2, y2, z2]).reduce(:+) would be the dot product of the vectors [x1, y1, z1] and [x2, y2, z2]. Of course, you would need to define the result when the inputs are of different lengths; in Haskell, the zipWith function takes the shorter of the two input lists:

```<code>   zipWith (♦) [1, 2] [3, 4, 5]
== zipWith (♦) [1, 2] [3, 4]
</code>```

So the answer is that there are several possible interpretations, the choice of which is up to the designers of languages and libraries. As long as they’re self-consistent, none of them is strictly more “right” or “intuitive” than any other. The established convention in array languages is for array * array to refer to pairwise product, because this generalises well to higher dimensions of array, and from promoting scalars to arrays of appropriate dimension.

Title: Array Multiplication and Division

Body:
I came across a question that (eventually) landed me wondering about array arithmetic. I'm thinking specifically in Ruby, but I think the concepts are language independent.

So, addition and subtraction are defined, in Ruby, as such:

```<code>[1,6,8,3,6] + [5,6,7] == [1,6,8,3,6,5,6,7] # All the elements of the first, then all the elements of the second
[1,6,8,3,6] - [5,6,7] == [1,8,3] # From the first, remove anything found in the second
</code>```

and array * scalar is defined:

```<code>[1,2,3] * 2 == [1,2,3,1,2,3]
</code>```

But

What, conceptually, should the following be? None of these are (as far as I can find) defined:

Array x Array: [1,2,3] * [1,2,3] #=> ?

Array / Scalar: [1,2,3,4,5] / 2 #=> ?

Array / Scalar: [1,2,3,4,5] % 2 #=> ?

Array / Array: [1,2,3,4,5] / [1,2] #=> ?

Array / Array: [1,2,3,4,5] % [1,2] #=> ?

I've found some mathematical descriptions of these operations for set theory, but I couldn't really follow them, and sets don't have duplicates (arrays do).

Edit: Note, I do not mean vector (matrix) arithmetic, which is completely defined.

Edit2: If this is the wrong stack exchange, tell me which is the right one and I'll move it.

Edit 3: Add mod operators to the list.

Edit 4:

I figure array / scalar is derivable from array * scalar:

```<code>a * b = c
=> a = b / c

[1,2,3] * 3 = [1,2,3]+[1,2,3]+[1,2,3] = [1,2,3,1,2,3,1,2,3]
=> [1,2,3] = [1,2,3,1,2,3,1,2,3] / 3
</code>```

Which, given that programmer's division ignore the remained and has modulus:

```<code>[1,2,3,4,5] / 2 = [[1,2], [3,4]]
[1,2,3,4,5] % 2 = [5]
</code>```

Except that these are pretty clearly non-reversible operations (not that modulus ever is), which is non-ideal.

Edit: I asked a question over on Math that led me to Multisets. I think maybe extensible arrays are "multisets", but I'm not sure yet.

Body:
Ruby’s model is provided more for convenience than correctness, and is inconsistent:

array + array is array concatenation, allowing duplicates, but array - array is set difference, removing duplicates: [1, 1] - [1] is [], not [1].

- is not the inverse of +, because it’s not the case that a + b - c == a for all Array instances a, b, and c: take [1] + [1] - [1].

array * fixnum is defined as iterated array concatenation, but fixnum * array is not defined at all.

For purely array-based operations, I would expect + and - to be inverses:

[1, 2] + [3, 1] == [1, 2, 3, 1]
[1, 2, 3, 1] - [3, 1] == [1, 2]

- would remove elements from the tail just as + added them. Similarly for * and /:

[1, 2] * 3 == [1, 2, 1, 2, 1, 2]
[1, 2, 1, 2, 1, 2] / 3 == [1, 2]
[5, 1, 2, 1, 2] / 2 == [1, 2]

/ would first discard elements from the left until a.size % b == 0. Why from the left? Well, I would expect an array modulus operator to satisfy the law:

a % b == a - (b * (a / b))

And that rule seems to work if you go through a few examples:

[1, 1] % 2 == [1, 1] - (2 * ([1, 1] / 2)) == []

[5, 1, 1] % 2 == [5, 1, 1] - (2 * ([5, 1, 1] / 2)) == [5]

This is basically defining division as iterated subtraction.

There are a couple of consistent and reasonably intuitive interpretations of array ♦ array:

Cartesian product: [1, 2] ♦ [3, 4] == [1 ♦ 3, 1 ♦ 4, 2 ♦ 3, 2 ♦ 4]

Pairwise product: [1, 2] ♦ [3, 4] == [1 ♦ 3, 2 ♦ 4]

With a Cartesian product, the size of the result is the product of the size of the inputs. This is how list comprehensions and the list monad work in Haskell:

[x ♦ y | x <- [1, 2], y <- [3, 4]]

do
  x <- [1, 2]
  y <- [3, 4]
  return (x ♦ y)

A pairwise product also makes sense, in that ([x1, y1, z1] * [x2, y2, z2]).reduce(:+) would be the dot product of the vectors [x1, y1, z1] and [x2, y2, z2]. Of course, you would need to define the result when the inputs are of different lengths; in Haskell, the zipWith function takes the shorter of the two input lists:

   zipWith (♦) [1, 2] [3, 4, 5]
== zipWith (♦) [1, 2] [3, 4]

So the answer is that there are several possible interpretations, the choice of which is up to the designers of languages and libraries. As long as they’re self-consistent, none of them is strictly more “right” or “intuitive” than any other. The established convention in array languages is for array * array to refer to pairwise product, because this generalises well to higher dimensions of array, and from promoting scalars to arrays of appropriate dimension.


问:
"Is" prefix and "On" suffix as reasonable exceptions to a "non-hungarian" naming standard?
First, I believe I've seen this question discussed here before, but I cannot find it. My apologies if you do find it.

I'm starting a new project, and trying to figure out why IsResolved and/or ResolvedOn make more sense to me than Resolved. Obviously, when something is named "CompanyName" (for example), I'm fairly confident I'll test it as a string. However, when I see "Resolved", and I know the object it describes may not have a valid value for a resolution date, it bothers me that I have to inspect the type to determine how to test it: for undefined/null/etc. (as a date), or as a boolean value.

Is it reasonable to claim that Is and On typically do more than declare the variable type; they declare the intent? Or perhaps simply that it makes the code clearer for some other reason I'm not quite able to codify?

Arguing the other side, if I look at the type of Resolved, and see that it is a boolean, I will have my answer. Perhaps this is no different than knowing that I'll need to inspect a "Feasibility" variable to determine if it is an int, enum, or something else. (Although perhaps just that means "Feasbility" would be a sub-optimal name also.) And regardless, in the case of "ResolvedOn", I still have to inspect whether it is nullable to determine if I additionally need to inspect an "IsResolved" value. What is the point of the verbosity, encoding a second time in the variable name that which can be deduced from the type?

Please give me a hand understanding why Is[Property] and [Property]On make sense to me, although Hungarian in general does not. Or, explain why an exception like this wouldn't make sense?

Note: I primarily work with SQL, C#, and JavaScript.

答:
I'd say that neither of your examples actually involve hungarian notation, which is why you find them acceptable.  blnResolved or dtResolved would be using hungarian notation.  IsResolved and ResolvedOn are simply descriptive names.  You could make IsResolved into HasBeenResolved if you like, but it's considerably longer and will not convey any additional information.

That said, don't let your dislike for hungarian notation get in the way of good names, DateResolved or ResolvedOnDate are again, just descriptive names.  It just so happens that it includes what on some systems are an approximation of the data type -- note that for TSQL 2000 it isn't the exact data type as it doesn't have a date datatype.


答:
Your names seem okay to me in terms of length. However, the way they are named suggests that maybe some new classes are in order?

For example, instead of searchBlockedListForBlockedSquares() you could have blockedList.getBlockedSquares(). Similarly, isCurrentSquareNextToAtLeastOneBlockedSquare() becomes currentSquare.isAdjacentToABlockedSquare().

Title: Are my method or variable names too long?

Body:
So I was currently in the middle of coding, unfortunately for me, I was in "The Zone" then I thought to myself, are my method/variable names to long?

POP out of the Zone I go!

So I came here to ask, are my method/variable names too long? You be the Judge! Bonus points to anyone who can figure out what I'm writing, although I'm sure a guru will figure it out fast!

Anyway, here are some of my method and variable names.

Methods :

searchBlockedListForBlockedSquares(),

isCurrentSquareNextToAtLeastOneBlockedSquare(),

searchBlockedListForBlockedSquares()

Variables:

isNextToBlockedSquares

I guess there was only one variable that seemed too long.


问:
Why these attempts to water down Scala with Xtend and Kotlin?
So now Eclipse has offered Xtend and JetBrains is offering Kotlin - both of which seem to be watered down versions of Scala. My question is why?  I've played with Scala a bit and it's not that hard.  Is this just a reaction to the inherent difficulty of the leap from imperative to functional or is there something else at work here?

EDIT: Apologies.  Rereading the question as I originally posted it I can see where it sounds a bit like trolling.  The way I phrased the question just seemed to be the best way to ask the question.  I have seen blog postings to the effect "Scala is too hard/Scala is too complex" and also "Kotlin is an attempt to do Scala but simpler".  I'll leave the phrasing as it was originally but I honestly wasn't trying to troll.

答:
Don't know about Kotlin, but Scala and Xtend are two very different beasts.

Contrary to common sayings, Scala is NOT a better Java. Scala is much more featured language than Java, with its own syntax and semantics, and its own pack of base libraries.

Xtend IS a better Java. It keeps Java semantics and enhances its syntax. Every line of Xtend code can be directly translated to a bunch of java lines of code. There's no additional runtime, neither.

I think that both approaches are right, although different. I don't dislike Scala (as a language), but don't like having Scala jars added to my projects. I can't use Scala properly in Android, neither (it adds weight and performance issues). Xtend is not as much featured, but it's Ok for me (much worth using it than Java language) and it works on every platform as if I were writing directly in Java.

I believe both languages cover different niches and can coexist without interferring one to each other. IMHO, Scala is just too complex, adding nothing new. Iif you want to go more functional and less OO, just pick one of many simpler functional languages, like Clojure or JHaskell. If you just want Java with some better syntax and a bit of functional programming, Fantom would be as great as Scala (it resembles C# a lot).

But I find Xtend being in a sweet point in between all those languages. It adds all those syntactic patterns I wanted for Java, keeping the good parts of Java (its semantics). Think about it as Coffescript for Java.

And Eclipse support is superb...


问:
I want to sell my application in Google Play Store, but I want the code to be open-source. Which license should I use?
I would like to sell the compiled binary of my android application in the Google Play Store when it reaches production.

Which license can I use to prevent people from downloading my source code from the open-source page and selling an exact copy of my work on the play store?

I want the code to be free and open for geeks/hackers to download and play with, but I don't want people who check out my source code to have the ability to use it for commercial use.

答:
You're asking for something impossible.  Part of the open source definition is that people can use the software as they wish.  This includes "their own commercial efforts."  There are no open-source licenses that would give you what you want.  However, if you don't want other people building and selling your program, you could do this by publishing the code freely, but not the resources (artwork, etc.)  However, such an approach could hinder the ability of "geeks and hackers" to do anything useful with your code.

If you want to sell open-source software, you have to be able to live with the fact that it's not exclusive to you.  That's the way it works.  You entice people to pay you for it by providing value above and beyond what they can get with a compiler.  For example, you could run a server that provides services that your application uses.  You could provide support for your program, with priority support going to paid users.  You could run closed betas for updated versions that only paid users have access to.  And that's just off the top of my head.

You have to change your mindset.  In this modern day, you don't get people to pay for software by forcing them to.  It doesn't work for proprietary software and it works even less so for open source.  You get people to pay for software by convincing them that the value they would receive by paying for it exceeds the price you're asking.


答:
See this excellent answer on SO. If your question is "how can I provide source but restrict commercial use", you have the following options:

GPL or similar copy-left licenses. In practice, this tends to work against commercial selling of of the software by anybody, including yourself. The reason is that since anyone can rebuild the software, anyone can - relatively easily - provide free binaries, undercutting anyone selling it, including yourself. On the plus side, GPL is very well understood and accepted, including the practice of having the original author selling copies without others selling it too. Another option is to provide the software free but sell something that others don't get just from the source: your expertise and support.

Don't provide important assets or some other form of crippling the source distribution. This is a very common practice, usually done to protect companies' IP, but also adhering to most of the spirit of open source, that of allowing hobbyists to tinker and study. Omitting the assets (or using a non-commercial license for them) is just one of the most convenient ways of crippling the distribution so others can't easily or legally reproduce your software.

Creative Commons Non-commercial or roll-your-own license. These explicitly forbid others from reselling your software, but this isn't recommended as it's unclear how well CC applies to software, and if you roll your own license always consult a lawyer.

No license (all rights reserved). If you distribute source code with no license, copyright law defaults to all rights reserved, which means people can look at and use the source privately for any purpose (you gave it to them after all), but they have no rights whatsoever for distribution or license transfer.

Having said that, there are a few points to clarify:

Restricting commercial use is NOT Open Source, as per (most people's) definition.

Commercial use covers more than just selling. Do you want people to host your game on their ad-supported page? To bundle it with some other package that earns money? To take parts of it to incorporate into a larger commercial work? That also falls under commercial use.

Title: I want to sell my application in Google Play Store, but I want the code to be open-source. Which license should I use?

Body:
I would like to sell the compiled binary of my android application in the Google Play Store when it reaches production.

Which license can I use to prevent people from downloading my source code from the open-source page and selling an exact copy of my work on the play store?

I want the code to be free and open for geeks/hackers to download and play with, but I don't want people who check out my source code to have the ability to use it for commercial use.


答:
A variable name is the wrong length when it is not clearly describing it's purpose. That applies to being too short or too long.

Short and terse variable names can be ambiguous, or worse have no relationship to what the variable is. In the days of interpreted BASIC, we were limited by the interpreter to two character names. It was very difficult to come up with meaningful names in a large program. Single letter variable names are often used for for-loops and counters, but I think they should be avoided otherwise. for (i = 0; i < 10; i++) {...} uses i and that's pretty common. j is a secondary variable name.

Long variable names are too long when they become long-winded or full of empty words, making them longer than necessary. If I have a bunch of similarly named variables I'll try to remove the common parts that are dispensable and keep the uniquely identifying parts of the names.

I'd have named "isCurrentSquareNextToAtLeastOneBlockedSquare" to currentSquareNextToBlockedSquare?, if I was doing it in Ruby.


问:
When to write tests for a new class using BDD?
I've been practicing behaviour driven development (BDD). I understand that you have to write tests that test the behaviour of the code, and this will allow the design of your code to evolve and take shape.

When doing BDD and I find I need to refactor my code into a better design, and that refactor happens to involve extracting some code into a new class, when do I start writing tests for that new class?

Or are tests not needed for that class at all since it's a implementation detail and the behaviour of it should already be tested with the existing test coverage?

答:
When doing BDD and I find I need to refactor my code into a better design, and that refactor happens to involve extracting some code into a new class, when do I start writing tests for that new class?

Start refactoring as soon as you identify the problem. If you see that you can extract some functionality into new class, do it right away, but first make sure all tests are passing.

Or are tests not needed for that class at all since it's a implementation detail and the behaviour of it should already be tested with the existing test coverage?

Yes, you do need to test that class as well. Extra tests will not do harm, and may catch possible bugs that got through in old tests.

If you are following SOLID, and using mock classes to test behaviour, then you'll need to change the existing tests. If not, then just leave tests as they are.


问:
How do I create a mutually-incompatible type library in Java?
Folks, this seems like it should be straightforward, but I'm drawing a blank here.

As a simplified example, consider an abstract class called Number with an abstract method add(). I want to create two concrete subclasses, Integer and Float, with method signatures Integer.add(Integer other) and Float.add(Float  other). A Float can NOT be added to an Integer. What should the method signature of the abstract add() method in the Number class be in order to enforce this constraint at compile-time?

答:
Number should not have an add() method.

Declaring a method in a base class (Or in an interface, for that matter), is a promise to implement this method. If your base class has add(Integer i), that's a promise that each instance of Number - be it a Float or an Integer - will have that method.

You can use generics, as jozefg commented - but then your two classes do not share a common superclass: Integer extends Number<Integer>, and Float extends Number<Float>. These are two different classes, that share their code. At runtime (In Java), erasure makes it look like it's the same class, but that's a technicality; When it comes to static  (compile-time) terms, the two classes are distinct.

Another dynamic solution is to have Number define either add(Number), or both add(Integer) and add(Float), and throw an exception when the wrong method is invoked; This is certainly not what you're after, and is not generally considered a good use of Object-Oriented features.


问:
How do I reduce the number of WCF config files in a SOA?
After embracing the whole SOA thing, I've found that I'm gradually drowning in a sea of web.config and app.config files.

As an example, one system has 2 services that it interacts with. Each service has 3 config files - one for dev, one for staging and one for production. That's 6 config files. Then each application (3 different ones) that use these services needs three config files again, that's another 9. So that's 15 config files just for a relatively simple system.

How can I go about simplifying my configuration? Is there a better way of doing this? Should I try to make my config files environment agnostic? Should I investigate the whole WCF Discovery? Should I use the web.config transformation syntax?

答:
I used web.config transformation feature. [More information here.][1]
Link

You may also modify your settings programatically per environment after reading the settings from the config file.