问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
I'm from Denmark.

Code, documentation, naming, design documents etc. is all done in English. I have only ever seen otherwise in hobbyist and student projects - and even then only very rarely.

The only open question that I see is what to do about (potentially) user-visible strings:

```<code>window.setHeader("????");

throw new ThisMightBeSeenByTheUserInAnErrorMessageException("????");
</code>```

For exceptions I prefer using English messages. It looks better and you have to deal with English exception-messages from frameworks anyway.

For GUI texts I am more agnostic. It is a more elegant solution to write everything in English and use a localization solution to translate to Danish, but it is a lot of work for an application that will only ever be used by Danish users.

Body:
I'm from Denmark.

Code, documentation, naming, design documents etc. is all done in English. I have only ever seen otherwise in hobbyist and student projects - and even then only very rarely.

The only open question that I see is what to do about (potentially) user-visible strings:

window.setHeader("????");

throw new ThisMightBeSeenByTheUserInAnErrorMessageException("????");

For exceptions I prefer using English messages. It looks better and you have to deal with English exception-messages from frameworks anyway.

For GUI texts I am more agnostic. It is a more elegant solution to write everything in English and use a localization solution to translate to Danish, but it is a lot of work for an application that will only ever be used by Danish users.


问:
How do you stay motivated for hobby projects?
I started seriously programming as a hobbiest, student and then intern about 4 years ago and I've always done small projects on the side as a learning exercise.  Schools over now though, and I spend my days at work as a software developer. I would still love to do projects on the side to learn about areas in computer science that I'm not exposed to at work, but I've noticed that after 8 hours of starring at an IDE it's far to tempting to veg out.  Any time I do get up the gumption to work on something for a few hours lately it's gotten left by the wayside.

Anyone have any advice for sticking with side projects when you spend most of your day coding?

答: For me, people make the difference.  I have a ridiculous amount of side projects begging for my attention.  The ones that get my "spare" time (an extremely finite resource) are the ones in which I work with people who teach me new things, spark new ideas, or inspire me in some way.  I find it hard to stay motivated on the others.</p>

ContentLicense: CC BY-SA 2.5


问:
The Meaning of Unified in UML
UML and other related modelling languages are exists in most of the system engineering fields to represent the system, flow, relations in a structured way. UML also is one of the modelling language used in computer science like other industries to represent the systems in obeject oriented way by using different types of diagrams. Does 'Unified' UML has a special (or real) meaning here?</p>

答:
There is a history behind UML that it combines the object oriented methodologies advocated by three camps.  James Rumbaugh had a group that created an object oriented methodology called Object Modeling Technique (OMT), Grady Booch had overlapping work and notation that I always used to just call the Booch method, and Ivar Jacobson had a methodology based on use cases.

The unification in unified, is the unification of their methodologies.

Another piece of trivia is that they called themselves the three amigos (friends) and were part of Rational before it was sold to IBM.

ContentLicense: CC BY-SA 3.0

Title: The Meaning of Unified in UML


问:
Testing vs QA - output?
I was trying to find a relevant source of information for the above, but I failed. What is the output of software testing? Some say its "list of bugs", others say "answer whether or not the software conforms to what customer wanted".
I know testing is a part of QA but not sure what is its aim and output in this context.</p>

答:
the purpose of testing is to validate that the product meets the quality requirements.

That includes both functional (meeting customer requirements for features, usability, performance) and technical (crashes, data corruption, etc.) requirements.

It's an integral part of the QA process, no more and no less. Ergo, there is no other context, unless you're testing stuff for the sake of testing it in which case only you can say what you want the aim and output to be, and most likely both will be irrelevant as you're testing without aim and therefore won't care about the output.

Title: Testing vs QA - output?


答:
Quality Assurance is a phase that each feature/product must go through before it is ready for end-users. The goal of QA is to ensure that when your product reaches its users, they will be able to use it and not be frustrated by things that don't meet customer expectations or those that are simply broken.

Testing is the primary activity done during QA phase. Although QA certainly is responsible for generating "a list of bugs", I would not consider that to be the output. If it was, then QA engineers would be evaluated based on how many bugs they write per day and that doesn't make much sense.

Instead, consider bug tracking to be simply a communications mechanism to be used internally for effective interaction between QA and development teams.  The real output of QA is working software and in order to verify that it is working, that software must pass set of acceptance tests.  So you could say that QA's output is a checklist which shows the state of all acceptance tests and identifies which ones have passed and failed.  Ideally, by the time QA is done working with development engineers, all acceptance tests should be passing, but in some circumstances if a feature is isolated and not in high demand, product management might make a decision to ship the product without the support for that feature.

Title: Testing vs QA - output?

Body:
I was trying to find a relevant source of information for the above, but I failed. What is the output of software testing? Some say its "list of bugs", others say "answer whether or not the software conforms to what customer wanted".
I know testing is a part of QA but not sure what is its aim and output in this context.</p>


问:
What causes overtime and how can it be avoided?
Today, my manager told me that I must work over time to make up for a lack of planning and project management. Instead of incentivizing this unpaid mandatory overtime, my manager has made it clear I have no choice in the matter.

This isn't a single project. We currently have a dozen projects all on the go at one time, and I simply can't get them all done. Therefore, I must work overtime so we don't have to push deadlines.

Is this a sign of an ignorant or disrespectful manager, or simply an inexperienced one?

I'm in this position because of a lack of planning and project management (I think). How might I avoid this in the future? I'm no Project Manager, it isn't my strength.

What are good ways to get an employee to work overtime if you can't directly pay them? Good incentives, etc.

From what I hear, gaining your employee's respect is the single best way to get your employees to work over time, although you should never make a habit of it.

答:
It's totally disrespectful.  They clearly view you as a means to their personal ends, and couldn't care less about you.

But, I wouldn't characterize it as 'forced' overtime, as it's still your choice.  Tell them no, you have plans that night, so you can't stay.  What are they going to do?  Fire you?  And then how far behind are their projects going to be?

Programmers & IT folks have this tendency to let themselves be abused.  Why, I don't know.  But programmers can do things that most other people can't even be trained to do.  Good ones, at least.  Your boss wants you to work overtime?  Let him finish the code.  See who needs who.  Or let them outsource it and see how well that works out for them.

Seriously, the modern world runs on software.  Programmers have more bargaining power than they think.  They just need to wield it.


问:
Persuading management that refactoring code is a good idea

Possible Duplicate:

  Best supporting argument for refactoring

Has anyone got any tips for persuading management that refactoring code is a good idea ?  I was asked something like

"After this refactoring, will I have a better product ?  How does time spent on this benefit the company?"

Or something along those lines.  I can see why management asked it but my response was not fantastic.  I said something about how a well designed piece of software will mean that adding new features in the future will be quicker and easier.

Does anyone else have any tips ?

Many thanks.

答:
Don't bother.

Rather than selling refactoring as a stand alone feature combine refactoring into your estimates for implementing fixes/ new features when it makes sense to do so, generally speaking the business need not and does not want to know exactly how you plan on implementing a feature, just that it gets done.


问:
What's the normal way machine-learning algorithms are integrated into normal programs?
I'm currently taking a machine learning course for fun, and the course heavily focuses on Matlab/Octave to write the code.  One thing mentioned in the course is that, while Matlab/Octave are great for prototyping, they're very rarely used for production algorithms.  Instead, those algorithms are typically rewritten in C++/Python/etc., using appropriate libraries, before reaching customers.

Fair enough; I get that.  But here's my question: is that done for cultural reasons, for technical reasons, or because there is really no language that provides Matlab/Octave-like fluidity, but in a compiled form that can be linked from C/C++/$MainstreamLanguage?  The game industry uses Lua for game logic because it's easy to embed, and vastly superior for expressing things like AI.  Likewise, there are Prolog variants for rules-heavy applications, Scheme variants for compilers, and so on.

If there's a matrix equivalent language, what is it?  If there isn't, why is this field different?

答:
MATLAB tends not to find its way into production code for several reasons.  Among these:

It's proprietary

It's old and hasn't aged well as a language

It was traditionally difficult to to embed in other applications

Points 1 and 3 aren't so much true today, since we've got Octave and there are many ways to interface MATLAB with external programs, but these are still the perceived drawbacks.  Point 2 is definitely valid though today.  MATLAB is great when what you're trying to do decomposes nicely into matrix operations, but when you talk about data structure manipulations and complicated logic, MATLAB really begins to be vexing and SLOW.  OOP remains a huge pain in MATLAB and for being a research language, it lacks a lot of the constructs researchers have come to enjoy, such as functional features.  It might be more informative to ask why people still use MATLAB in spite of it cruftiness, and the answer would be the easy syntax, the very well integrated IDE, the massive number of freely available domain-specific toolboxes out there, and the fact that it still absolutely rocks for making plots.

But in my experience, Python is rapidly supplanting MATLAB in the research world.  As a language, it is much nicer to work with.  Numpy and SciPy are in many ways more modern and advanced than MATLAB's basic library, readily generalizing matrix operations to arbitrary dimensionality.  Every field seems to have its Python evangelists, working hard to create packages that match up to MATLAB's vast toolbox library.  And Python has the huge advantage of being free, easy to install, and easy to use.


问:
When to use functional programming approach and when not? (in Java)
let's assume I have a task to create a Set of class names. To remove duplication of .getName() method calls for each class, I used org.apache.commons.collections.CollectionUtils and org.apache.commons.collections.Transformer as follows:

Snippet 1:

```<code>Set<String> myNames = new HashSet<String>();
CollectionUtils.collect(
        Arrays.<Class<?>>asList(My1.class, My2.class, My3.class, My4.class, My5.class),
        new Transformer() {
            public Object transform(Object o) {
                return ((Class<?>) o).getName();
            }
        }, myNames);
</code>```

An alternative would be this code:

Snippet 2:

```<code>Collections.addAll(myNames, My1.class.getName(), My2.class.getName(), My3.class.getName(), My4.class.getName(), My5.class.getName());
</code>```

So, when using functional programming approach is overhead and when it's not and why?

Isn't my usage of functional programming approach in snippet 1 is an overhead and why?

答: Functional approach usually gives you a better looking, shorter code. But dealing with immutability may result in a performance penalty. I think first snippet looks like overhead because functional syntax in Java is too verbose.</p>


问:
Best supporting argument for refactoring
Currently I am working on a code best described as C code living in C++ body. However I haven't been able to convince power that be to re-factor on ground of ease of maintenance. </p>

<p>What in your opinion is the best argument for refactoring the code. </p>

答:
As with everything examples are the best way. Some examples you can give:

Hard to change code: Bug X took 3 days to fix caused by code issues a,b,c

Tight coupling: Fixing Bug Y introduced bug G, fixing both causes bug F

Hard to read: It took 1 whole day to investigate bug C

Bad cohesion: Introducing feature D required dependency on F, which is unrelated. This causes problems such as circular dependency problem a, build time increase b etc...

To put this simply if you can draw a cause and effect line and illustrate with bug tracker records, e-mails and other forms of proof that indicate that there is a problem that should motivate refactoring quite easily. "It shouldn't have taken 2 weeks to implement feature X!"

There are tools out there that can help you motivate your refactoring too. They can draw dependency graphs or show code complexity, duplication etc. If a tool reports thousands of warnings and management ignores it then there is no hope for management.

These focus on code structure changes. Small refactorings like naming conventions and pulling up into base classes are things that I consider part of my job, and I don't ask permission to do it. If it's going to impact productivity or delivery date significantly then it is worth asking permission.


答:
As others noted, you can't really use a functional approach in Java, because it is way too verbose and simply lacks a lot of necessary features. So the resulting code will usually look more complex and ugly. Sometimes it is still worth it—because the alternative would include even more duplication and/or other ugliness—sometimes it isn't. You need to decide on a case by case basis. Try out different approaches and choose the one resulting in the cleanest, simplest code. And don't bother too much with labels. :-) Writing code in "functional" style is not superior per se than any other style—only if your code is actually shorter, cleaner, easier to maintain and extend and/or more efficient in some significant way.

This brings us to another important point. Even if you managed to implement some piece of code in a "functional" way really succinctly, you need to look at it from the point of view of the future maintainers. Will an average Java programmer understand your piece of code if it is so different from the mainstream and well-known Java idioms? Most likely not, which increases the probability of them introducing bugs during future development/maintenance. Your code must have very strong and provable advantages to counterbalance this, and you need to document it well.

Title: When to use functional programming approach and when not? (in Java)

Body:
let's assume I have a task to create a Set of class names. To remove duplication of .getName() method calls for each class, I used org.apache.commons.collections.CollectionUtils and org.apache.commons.collections.Transformer as follows:

Snippet 1:

```<code>Set<String> myNames = new HashSet<String>();
CollectionUtils.collect(
        Arrays.<Class<?>>asList(My1.class, My2.class, My3.class, My4.class, My5.class),
        new Transformer() {
            public Object transform(Object o) {
                return ((Class<?>) o).getName();
            }
        }, myNames);
</code>```

An alternative would be this code:

Snippet 2:

```<code>Collections.addAll(myNames, My1.class.getName(), My2.class.getName(), My3.class.getName(), My4.class.getName(), My5.class.getName());
</code>```

So, when using functional programming approach is overhead and when it's not and why?

Isn't my usage of functional programming approach in snippet 1 is an overhead and why?


答:
Java was not designed for functional programming and so, while you can use a functional programming style in Java (immutable state, recursion, function composition, high-order functions, ...), you will often miss certain features that facilitate functional programming (ad-hoc syntactic constructs, currying, function composition operator, tail-call optimization, ...).

Therefore, even though a functional style in Java can make your code (sometimes) more readable or (more often) more robust, if you really want to use it heavily you'd better use a language that was designed for it. For the JVM you can use Scala or Clojure (here is a short article, that also discusses Groovy). Otherwise, you can try Haskell, Common Lisp, Scheme, F#, Ocaml, and others.


答:
Theoretically a functional approach is simpler, more versatile, more verifiable, and easier to understand at-a-glance. If what you end up with doesn't hit at least one of those goals, then perhaps it's not the best approach for your circumstances.

Note that functional is, as previously mentioned, a bit of a reach for Java. But not for the JVM. Scala and Groovy are a bit more flexible in that regard and allow you to express functional concepts much more succinctly. And if you want to to all-out functional, there's always Clojure. All of these target the JVM and should integrate reasonably well into an existing Java project.

If you're stuck with a Java environment (JVM) but are getting tired of the language itself, I'd recommend trying out Scala or Groovy. It's a bit like Java with a more modern syntax (or Jython if you're feeling a twinge of python-envy).


答:
One tip - make sure your hobby project has nothing to do whatsoever with your day job.  If you use C++ at work, use something else in your hobby projects.  This will help you avoid some of the burnout because you're at least switching to a different IDE and/or skill set.

But, a hobby is a hobby...so don't fret it.  It's supposed to be relaxing, not stressful.

Title: How do you stay motivated for hobby projects?

Body:
I started seriously programming as a hobbiest, student and then intern about 4 years ago and I've always done small projects on the side as a learning exercise.  Schools over now though, and I spend my days at work as a software developer. I would still love to do projects on the side to learn about areas in computer science that I'm not exposed to at work, but I've noticed that after 8 hours of starring at an IDE it's far to tempting to veg out.  Any time I do get up the gumption to work on something for a few hours lately it's gotten left by the wayside.

Anyone have any advice for sticking with side projects when you spend most of your day coding?


问:
Why don't computers store decimal numbers as a second whole number?
Computers have trouble storing fractional numbers where the denominator is something other than a solution to 2^x.  This is because the first digit after the decimal is worth 1/2, the second 1/4 (or 1/(2^1) and 1/(2^2)) etc.

Why deal with all sorts of rounding errors when the computer could have just stored the decimal part of the number as another whole number (which is therefore accurate?)

The only thing I can think of is dealing with repeating decimals (in base 10), but there could have been an edge solution to that (like we currently have with infinity).

答:
That would be called BCD, I think you can still use it if you really want to.
However it's not really worth it as:

You'll very rarely run into a rounding error with 64 bit floating point

It makes the arithmatic complex and inefficient

It wastes 6 values every 4 bits


问:
Examples of non open source projects on Bitbucket or Github
Need examples to show management that these are used for source control and effectively backup of projects.

They will be concerned about having their source code off-site.  If there are good examples I think that it may help in convincing them to consider this as an option.

答:
Your a bit out of luck there, as there's no way to gain insights into private repositories. Luckily, GitHub does have support for organizations and Bitbucket has an equivalent support with teams.

For no particular reason, I can give you an example of Engine Yard as one of the organizations that are using GitHub, but with a bit of repository browsing I'm sure you can find other businesses closely related to your niche that have a presence on one of the two.

I'm unable to find any adequate published sources right now, but I do have an understanding that their in-house support and maintainers do not have access to repository particularities such as source files, which is what I believe one of the main concerns would be for hosting your sources on remote services.


答: GitHub is proprietary and is hosted on GitHub.</p>

Title: Examples of non open source projects on Bitbucket or Github

Body:
Need examples to show management that these are used for source control and effectively backup of projects.

They will be concerned about having their source code off-site.  If there are good examples I think that it may help in convincing them to consider this as an option.


问:
PHP PSR-0 + several namespaces in one file and autoload
I've been thinking for a while about defining several namespaces in one php file and so, having several classes inside this file.

Suppose, I want to implement something like Doctrine\ORM\Query\Expr:

```<code>Expr.php
Expr
|-- Andx.php
|-- Base.php
|-- Comparison.php
|-- Composite.php
|-- From.php
|-- Func.php
|-- GroupBy.php
|-- Join.php
|-- Literal.php
|-- Math.php
|-- OrderBy.php
|-- Orx.php
`-- Select.php
</code>```

It would be nice if I had all of this in one file - Expr.php:

```<code>namespace Doctrine\ORM\Query;
class Expr {
    // code
}

namespace Doctrine\ORM\Query\Expr;

class Func {
    // code
}

// etc...
</code>```

What I'm thinking of is directories naming convention and, unlike PSR-0 having several classes and namespaces in one file. It's best explained by the code:

```<code>ls Doctrine/orm/query
Expr.php
</code>```

that's it - only Expr.php

Since Expr.php is somewhat I call a "meta-namespace" for Expr\Func, it make sense to place all the classes inside Expr.php (as shown above).

So, the vendor name is still starts with an uppercased letter (Doctrine) and the other parts of namespace start with lowercased letter. We can write an autoload so it would respect this notion:

```<code>function load_class($class) {
    if (class_exists($class)) {
        return true;
    }
    $tokenized_path = explode(array("_", "\\"), DIRECTORY_SEPARATOR, $class);
    // array('Doctrine', 'orm', 'query', 'Expr', 'Func');
    //                                    ^^^^
    // first, we are looking for first uppercased namespace part
    // and if it's not last (not the class name), we use it as a filename
    // and wiping away the rest to compose a path to a file we need to include
    if (FALSE !== ($meta_class_index = find_meta_class($tokenized_path))) {
        $new_tokenized_path = array_slice($tokenized_path, 0, $meta_class_index);
        $path_to_class = implode(DIRECTORY_SEPARATOR, $new_tokenized_path);
    }
    else { // no meta class found
        $path_to_class = implode(DIRECTORY_SEPARATOR, $tokenized_path);
    }
    if (file_exists($path_to_class.'.php')) {
        require_once $path_to_class.'.php';
    }
    return false;
}
</code>```

Another reason to do so is to reduce a number of php files scattered among directories.
Usually you check file existence before you require a file to fail gracefully:

```<code>file_exists($path_to_class.'.php');
</code>```

If you take a look at actual Doctrine\ORM\Query\Expr code, you'll see they use all of the "inner-classes", so you actually do:

```<code>file_exists("/path/to/Doctrine/ORM/Query/Expr.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/AndX.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Base.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Comparison.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Composite.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/From.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Func.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/GroupBy.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Join.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Literal.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Math.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/OrderBy.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Orx.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Select.php");
</code>```

in your autoload which causes quite a few I/O reads.
Isn't it too much to check on each user's hit?

I'm just putting this on a discussion.

I want to hear from another PHP programmers what do they think of it.
And, of course, if you have a silver bullet addressing this problems I've designated here, please share.

I also have been thinking if my vogue question fits here and according to the FAQ it seems like this question addresses "software architecture" problem slash proposal.

I'm sorry if my scribble may seem a bit clunky :)
Thanks.

答:
I am not convinced, that you really want to have all your classes in one file. Of course it is possible, but I wouldn't want to maintain it. You can use multiple namespaces in one file. There are two allowed syntaxes:

Example #1 Declaring multiple namespaces, simple combination syntax

```<code><?php
namespace MyProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }

namespace AnotherProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
?>
</code>```

Example #2 Declaring multiple namespaces, bracketed syntax

```<code><?php
namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}

namespace AnotherProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}
?>
</code>```

I would go with the second one, for readability, maintenance and error avoidance reasons.

However, I don't like the idea of using one file for multiple classes. I would suggest to use one file per class, organized in folders according to your namespace. This allows you to use really straightforward autoloading:

```<code>spl_autoload_register(function ($className) {
    $className = (string) str_replace('\\', DIRECTORY_SEPARATOR, $className);
    if(file_exists($className)) {
        include_once($className . '.class.php');
    } else {
        // throw class not found
    }
});
</code>```

Thats a pattern I usually use in my applications. If you are concerned about IO and speed, I would look at the things Yannis Rizos mentioned:

Have you thought of just putting everything in a phar archive? Still a
  file per class (easier to maintain), but a bit less strain on the
  filesystem (especially with APC).

You could even use the HipHop compiler.

Body:
I am not convinced, that you really want to have all your classes in one file. Of course it is possible, but I wouldn't want to maintain it. You can use multiple namespaces in one file. There are two allowed syntaxes:

Example #1 Declaring multiple namespaces, simple combination syntax

<?php
namespace MyProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }

namespace AnotherProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
?>

Example #2 Declaring multiple namespaces, bracketed syntax

<?php
namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}

namespace AnotherProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}
?>

I would go with the second one, for readability, maintenance and error avoidance reasons.

However, I don't like the idea of using one file for multiple classes. I would suggest to use one file per class, organized in folders according to your namespace. This allows you to use really straightforward autoloading:

spl_autoload_register(function ($className) {
    $className = (string) str_replace('\\', DIRECTORY_SEPARATOR, $className);
    if(file_exists($className)) {
        include_once($className . '.class.php');
    } else {
        // throw class not found
    }
});

Thats a pattern I usually use in my applications. If you are concerned about IO and speed, I would look at the things Yannis Rizos mentioned:

Have you thought of just putting everything in a phar archive? Still a
  file per class (easier to maintain), but a bit less strain on the
  filesystem (especially with APC).

You could even use the HipHop compiler.


问:
How do you get a client to understand the importance of a project lifecycle?
Situation is I have a number of in-house clients who continue to have trouble grasping the concept of defining clear requirements for a project and committing to them. Unfortunately my job situation is that I can't decline such projects, and I am often forced into situations that I can tell are doomed to scope creep (or worse) from the very start. Telling them that detailed requirements are vital and why we need them (using examples of past troubled projects due to this) have not helped.

I am looking for techniques, tips, words, etc that you might use to motivate or illuminate clients in such situations to the necessity of requirements,setting milestones, etc.

I am only a developer, and not a manager.

答:
Draw the Time-Quality-Cost triangle on their whiteboard:

.

Explain the trade-off: It's physically impossible to satisfy all 3 properties. They want good quality in a short time? It's going to cost them dearly. No time, no money? Then they're going to see it in the shoddy quality. High quality, low cost? That'll be ready whenever it's ready!!

This doesn't exactly address requirements and milestones, but it may plant some kind of seed that says, "Hey, if I leave stuff too late I'm going to end up paying more or get worse quality."


答:
Learning a bit about functional programming can improve the way you write object oriented software. For example the value of immutable objects, lack of side effects and new ways of seeing and appreciating abstractions - favoring 'verbs' over 'nouns'. But as others noted, java is no functional language and you may make the lives of other programmers reading your code hard when using unexpected paradigms.

Have a look at what the authors of google guava have to say about the functional idioms built into their library.


答:
Short Answer: Testing and QA are seem similar but do have different meanings and implications.

Testing - stands to any type of testing, just to break the system by user inputs with age case entries (like to see a rough behavior of UI on user entries, like validation and how exception cases are handled.)

QA(Quality Assurance) - has a goal to verify the requirements by testing the products. In another words, its core purpose is monitoring the software engineering processes and methods used to ensure quality. The purpose is to assure that the all functionality is in place and implemented as expected before user acceptance.

Overall, there are several sequential levels (unit testing, integration testing, etc.) in software testing process that you may get detailed information from - Wikipedia Software testing.

Title: Testing vs QA - output?


答:
While I can't give you examples of companies using github for hosting, I can suggest some other arguments you could use in favour of using it.

One of the major advantages of distributed version control like git or mercurial is that each repository is a full or almost full backup. So you'll have central server hosted and managed by someone else, but even if anything catastrophic happens and github goes out of business, the damage will be quite limited.

You can also note that administrator you'd otherwise have will certainly be less experienced than the ones in big hosting company like github and thus your own server is actually more likely to fail. Because in a big server farm, individual servers die now and than, so all recovery procedures are tested. While with own server it will work fine for some years, so when it fails you can easily find yourself with broken backup or missing bits or such.


问:
DAO/Webservice Consumption in Web Application
I am currently working on converting a "legacy" web-based (Coldfusion) application from single data source (MSSQL database) to multi-tier OOP.

In my current system there is a read/write database with all the usual stuff and additional "read-only" databases that are exported daily/hourly from an Enterprise Resource Planning (ERP) system by SSIS jobs with business product/item and manufacturing/SCM planning data.

The reason I have the opportunity and need to convert to multi-tier OOP is a newer more modern ERP system is being implemented business wide that will be a  complete replacement.

This newer ERP system offers several interfaces for third party applications like mine, from direct SQL access to either a dotNet web-service or a SOAP-like web-service.

I have found several suitable frameworks I would be happy to use (Coldspring, FW/1) but I am not sure what design patterns apply to my data access object/component and how to manage the connection/session tokens, with this background, my question has the following three parts:

Firstly I have concerns with moving from the relative safety of a SSIS job that protects me from downtime and speed of the ERP system to directly connecting with one of the web services which I note seem significantly slower than I expected (simple/small requests often take up to a whole second). Are there any design patterns I can investigate/use to cache/protect my data tier?

It is my understanding data access objects (the component that connects directly with the web services and convert them into the data types I can then work with in my Domain Objects) should be singletons (and will act as an Adapter/Facade), am I correct?

As part of the data access object I have to setup a connection by username/password (I could set up multiple users and/or connect multiple times with this) which responds with a session token that needs to be provided on every subsequent request.

Do I do this once and share it across the whole application, do I setup a new "connection" for every user of my application and keep the token in their session scope (might quickly hit licensing limits), do I set the "connection" up per page request, or is there a design pattern I am missing that can manage multiple "connections" where a requests/access uses the first free "connection"?

It is worth noting if the ERP system dies I will need to reset/invalidate all the connections and start from scratch, and depending on which web-service I use might need manually close the "connection/session"

答:
The options you've provided lead me to think that continuing to use the SSIS jobs to import data into a database you control for your application looks to be the best option for both managing the data flow and performance for the end-user.

If you've got requirements that need more up to date data than that supplied via SSIS then I would go for using the web services at that point for those specific parts of the application.

There is nothing in the DAO pattern that requires the implementation to be a singleton, you'll have a much easier time testing the DAO classes if they are implemented as normal classes and then only use a single instances as a dependency when in production.

Finally as session maintenance is required i would use short lived instances given you need to maintain per-request and if connection/resource limits are required to be managed a resource pool pattern implementation could be used to manage checking out/in access to instances that maintain the session tokens (eg get a new token on check out, release token on check in, ensure use is short lived). There should be a number of existing resource pool implementations available, use one as there are many gotchas to implementing that type of pattern.


问:
Is it worth moving from Microsoft tech to Linux, NodeJS & other open source frameworks to save money for a start-up?
I am currently getting involved in a startup, I am the only developer involved at the moment, and the other guys are leaving all the tech decisions up to me at the moment.

For my day job I work at a software house that uses Microsoft tech on a day to day basis, we utilise .NET, SqlServer, Windows Server etc. However, I realise that as a startup we need to keep costs down, and after having a brief look at the cost of hosting for Windows I was shocked to see some of the prices for a dedicated server. The cheapest I found was £100 a month. Also if the business needs to scale in the future and we end up needing multiple servers, we could end up shelling out £10's of £000's a year in SQL Server / Windows Server licenses etc.

I then had a quick look at the price of Linux hosting for a dedicated server and saw the price was waaaaaay lower than windows hosting. One place was offering a machine with 2 cores for less than £20 a month.

This got me thinking maybe the way to go is open source on Linux.

As I write a lot of Javascript at work (I'm working on a single page backbone app at the moment), I thought maybe NodeJS and a web framework like Express would be cool to use. I then thought that instead of using SQL why not use an open source NoSQL database like MongoDB, which has great support on NodeJS?

My only concern is that some of the work the application is going to do is going to be dynamically building images and various other image related stuff, i.e. stuff that is quite CPU heavy - so I'm thinking of maybe writing anything CPU heavy in C++ and consuming it as a module in Node.

That's the background - but basically is Linux a good match for:

Hosting a NodeJS/Express site?

Compiling C++ node modules?

Using a NoSQL DB like MongoDB?

And is it a good idea to move to these unfamiliar technologies to save money?

3 MONTH UPDATE

I've been working on this for the past few months now so thought I would give an update in case anyone is interested.

In the end I decided against using a NodeJS & Linux stack for the simple reason of time. I am doing this startup on the side, so I am working 9 hour days, then going home and working until late on the startup. While working in this way I obviously need to be as efficient with my time as possible, or I will never end up shipping the product.

After taking some of the advice on this thread I did apply for Microsoft BizSpark, and was accepted. This means I now have access to Visual Studio license, Windows Server license etc, all for free. Which is awesome. Hopefully by the time we are required to begin paying for everything we will be turning over enough that will make it a non-issue.

Do not think I am only using Microsoft tech, however, as I have tried to use open source stuff where possible. The main place I have done this is my data layer, where I have decided to use PostgreSQL and MongoDB. I am also using BackboneJS on my front end.

Below is a summary of the tech/frameworks I am currently using:

Standard DB stuff: PostreSQL

Logging & Data Store: MongoDB

ORM: Entity Framework 5

Core libraries: .NET (C#)

Web Framework: ASP.NET MVC3

UI: Razor view engine / BackboneJS

答:
Almost 10 years ago, I was in the same situation. However, all my Microsoft software was handed to me and I had a relative who was a manager in a large Microsoft shop help me out with development. One year and $50K in expenses later, Microsoft made changes to .NET which threw everything into a loop and we had to start over (Long story short. Don't ask.).

On the advice of my relative, we switched to FreeBSD and Linux and, three months later, rebuilt everything for virtually nothing using the same people. We are a thriving small web dev business now and have no had to buy any software (or hardware) since.


答:
As a small start-up you don't yet need dedicated servers. You can choose cloud, which is cheaper and already includes MS licenses. And you'd be using same stack as currently.

Windows Azure — by default same stack as yours

Amazon Web Service — your stack as an option (bit more expensive than Linux/MySQL, but they do have Windows and MS SQL Servers)

There are many reasons to switch to Open Source platform, but saving few bucks on hosting isn't one of them.

Also, keep in mind that SysOps for Unix/Linux platform are usually paid more than SysOps for Windows. Thus your "saving" might end up costing you more.

Title: Is it worth moving from Microsoft tech to Linux, NodeJS & other open source frameworks to save money for a start-up?

Body:
I am currently getting involved in a startup, I am the only developer involved at the moment, and the other guys are leaving all the tech decisions up to me at the moment.

For my day job I work at a software house that uses Microsoft tech on a day to day basis, we utilise .NET, SqlServer, Windows Server etc. However, I realise that as a startup we need to keep costs down, and after having a brief look at the cost of hosting for Windows I was shocked to see some of the prices for a dedicated server. The cheapest I found was £100 a month. Also if the business needs to scale in the future and we end up needing multiple servers, we could end up shelling out £10's of £000's a year in SQL Server / Windows Server licenses etc.

I then had a quick look at the price of Linux hosting for a dedicated server and saw the price was waaaaaay lower than windows hosting. One place was offering a machine with 2 cores for less than £20 a month.

This got me thinking maybe the way to go is open source on Linux.

As I write a lot of Javascript at work (I'm working on a single page backbone app at the moment), I thought maybe NodeJS and a web framework like Express would be cool to use. I then thought that instead of using SQL why not use an open source NoSQL database like MongoDB, which has great support on NodeJS?

My only concern is that some of the work the application is going to do is going to be dynamically building images and various other image related stuff, i.e. stuff that is quite CPU heavy - so I'm thinking of maybe writing anything CPU heavy in C++ and consuming it as a module in Node.

That's the background - but basically is Linux a good match for:

Hosting a NodeJS/Express site?

Compiling C++ node modules?

Using a NoSQL DB like MongoDB?

And is it a good idea to move to these unfamiliar technologies to save money?

3 MONTH UPDATE

I've been working on this for the past few months now so thought I would give an update in case anyone is interested.

In the end I decided against using a NodeJS & Linux stack for the simple reason of time. I am doing this startup on the side, so I am working 9 hour days, then going home and working until late on the startup. While working in this way I obviously need to be as efficient with my time as possible, or I will never end up shipping the product.

After taking some of the advice on this thread I did apply for Microsoft BizSpark, and was accepted. This means I now have access to Visual Studio license, Windows Server license etc, all for free. Which is awesome. Hopefully by the time we are required to begin paying for everything we will be turning over enough that will make it a non-issue.

Do not think I am only using Microsoft tech, however, as I have tried to use open source stuff where possible. The main place I have done this is my data layer, where I have decided to use PostgreSQL and MongoDB. I am also using BackboneJS on my front end.

Below is a summary of the tech/frameworks I am currently using:

Standard DB stuff: PostreSQL

Logging & Data Store: MongoDB

ORM: Entity Framework 5

Core libraries: .NET (C#)

Web Framework: ASP.NET MVC3

UI: Razor view engine / BackboneJS


问:
Is taking frequent breaks really that beneficial when programming?
I keep reading that it is recommended for a programmer to take frequent breaks while programming, and the usual recommendation I see is 5 minutes every half hour or 10 minutes every hour.

I gave it a try, but quite often I find something interesting during those 5 minutes, and it takes me away from what I was working on for longer than I planned. Either that, or my mind gets focused on something else and I find it hard to get back into my work and don't focus very well.

Is it really that beneficial to take frequent breaks while programming? Am I doing something wrong for it to be decreasing my productivity instead of increasing it?

答:
Taking frequent breaks is VERY important for your health. I read that people who sit down or lay down watching TV even just for a couple of hours have increased risk of mortality even if you exercise. You just HAVE to keep moving around.

"A new study from American Cancer Society researchers finds it's not just how much physical activity you get, but how much time you spend sitting that can affect your risk of death. Researchers say time spent sitting was independently associated with total mortality, regardless of physical activity level."

http://www.sciencedaily.com/releases/2010/07/100722102039.htm

"Couch potatoes beware: every hour of television watched per day may increase the risk of dying earlier from cardiovascular disease, according to research reported in Circulation: Journal of the American Heart Association."

http://www.sciencedaily.com/releases/2010/01/100111161927.htm


问:
How can I estimate the entropy of a password?
Having read various resources about password strength I'm trying to create an algorithm that will provide a rough estimation of how much entropy a password has.

I'm trying to create an algorithm that's as comprehensive as possible.  At this point I only have pseudocode, but the algorithm covers the following:

password length

repeated characters

patterns (logical)

different character spaces (LC, UC, Numeric, Special, Extended)

dictionary attacks

It does NOT cover the following, and SHOULD cover it WELL (though not perfectly):

ordering (passwords can be strictly ordered by output of this algorithm)

patterns (spatial)

Can anyone provide some insight on what this algorithm might be weak to?  Specifically, can anyone think of situations where feeding a password to the algorithm would OVERESTIMATE its strength?  Underestimations are less of an issue.

The algorithm:

```<code>// the password to test
password = ?
length = length(password)

// unique character counts from password (duplicates discarded)
uqlca = number of unique lowercase alphabetic characters in password
uquca = number of uppercase alphabetic characters
uqd   = number of unique digits
uqsp  = number of unique special characters (anything with a key on the keyboard)
uqxc  = number of unique special special characters (alt codes, extended-ascii stuff)

// algorithm parameters, total sizes of alphabet spaces
Nlca = total possible number of lowercase letters (26)
Nuca = total uppercase letters (26)
Nd   = total digits (10)
Nsp  = total special characters (32 or something)
Nxc  = total extended ascii characters that dont fit into other categorys (idk, 50?)

// algorithm parameters, pw strength growth rates as percentages (per character)
flca = entropy growth factor for lowercase letters (.25 is probably a good value)
fuca = EGF for uppercase letters (.4 is probably good)
fd   = EGF for digits (.4 is probably good)
fsp  = EGF for special chars (.5 is probably good)
fxc  = EGF for extended ascii chars (.75 is probably good)

// repetition factors.  few unique letters == low factor, many unique == high
rflca = (1 - (1 - flca) ^ uqlca)
rfuca = (1 - (1 - fuca) ^ uquca)
rfd   = (1 - (1 - fd  ) ^ uqd  )
rfsp  = (1 - (1 - fsp ) ^ uqsp )
rfxc  = (1 - (1 - fxc ) ^ uqxc )

// digit strengths
strength =
( rflca * Nlca +
  rfuca * Nuca +
  rfd   * Nd   +
  rfsp  * Nsp  +
  rfxc  * Nxc    ) ^ length

entropybits = log_base_2(strength)
</code>```

A few inputs and their desired and actual entropy_bits outputs:

```<code>INPUT           DESIRED        ACTUAL
aaa             very pathetic  8.1
aaaaaaaaa       pathetic       24.7
abcdefghi       weak           31.2
H0ley$Mol3y_    strong         72.2
s^fU¬5ü;y34G<   wtf            88.9
[a^36]*         pathetic       97.2
[a^20]A[a^15]*  strong         146.8
xkcd1**         medium         79.3
xkcd2**         wtf            160.5

* these 2 passwords use shortened notation, where [a^N] expands to N a's.
** xkcd1 = "Tr0ub4dor&3", xkcd2 = "correct horse battery staple"
</code>```

The algorithm does realize (correctly) that increasing the alphabet size (even by one digit) vastly strengthens long passwords, as shown by the difference in entropy_bits for the 6th and 7th passwords, which both consist of 36 a's, but the second's 21st a is capitalized.  However, they do not account for the fact that having a password of 36 a's is not a good idea, it's easily broken with a weak password cracker (and anyone who watches you type it will see it) and the algorithm doesn't reflect that.

It does, however, reflect the fact that xkcd1 is a weak password compared to xkcd2, despite having greater complexity density (is this even a thing?).

How can I improve this algorithm?

Addendum 1

Dictionary attacks and pattern based attacks seem to be the big thing, so I'll take a stab at addressing those.

I could perform a comprehensive search through the password for words from a word list and replace words with tokens unique to the words they represent.  Word-tokens would then be treated as characters and have their own weight system, and would add their own weights to the password.  I'd need a few new algorithm parameters (I'll call them lw, Nw ~= 2^11, fw ~= .5, and rfw) and I'd factor the weight into the password as I would any of the other weights.

This word search could be specially modified to match both lowercase and uppercase letters as well as common character substitutions, like that of E with 3.  If I didn't add extra weight to such matched words, the algorithm would underestimate their strength by a bit or two per word, which is OK.  Otherwise, a general rule would be, for each non-perfect character match, give the word a bonus bit.

I could then perform simple pattern checks, such as searches for runs of repeated characters and derivative tests (take the difference between each character), which would identify patterns such as 'aaaaa' and '12345', and replace each detected pattern with a pattern token, unique to the pattern and length.  The algorithmic parameters (specifically, entropy per pattern) could be generated on the fly based on the pattern.

At this point, I'd take the length of the password.  Each word token and pattern token would count as one character; each token would replace the characters they symbolically represented.

I made up some sort of pattern notation, but it includes the pattern length l, the pattern order o, and the base element b.  This information could be used to compute some arbitrary weight for each pattern.  I'd do something better in actual code.

Modified Example:

```<code>Password:          1234kitty$$$$$herpderp
Tokenized:         1 2 3 4 k i t t y $ $ $ $ $ h e r p d e r p
Words Filtered:    1 2 3 4 @W5783 $ $ $ $ $ @W9001 @W9002
Patterns Filtered: @P[l=4,o=1,b='1'] @W5783 @P[l=5,o=0,b='$'] @W9001 @W9002

Breakdown:         3 small, unique words and 2 patterns
Entropy:           about 45 bits, as per modified algorithm

Password:          correcthorsebatterystaple
Tokenized:         c o r r e c t h o r s e b a t t e r y s t a p l e
Words Filtered:    @W6783 @W7923 @W1535 @W2285

Breakdown:         4 small, unique words and no patterns
Entropy:           43 bits, as per modified algorithm
</code>```

The exact semantics of how entropy is calculated from patterns is up for discussion.  I was thinking something like:

```<code>entropy(b) * l * (o + 1) // o will be either zero or one
</code>```

The modified algorithm would find flaws with and reduce the strength of each password in the original table, with the exception of s^fU¬5ü;y34G<, which contains no words or patterns.

答:
Appendix A on p46 of NIST SP 800-63 talks about the work of Claude Shannon, who estimates password entropy using a number of bits. Indeed, this is the document that the XKCD cartoon uses to calculate the entropy bits. Specifically:

the entropy of the first character is taken to be 4 bits;

the entropy of the next 7 characters are 2 bits per character; this is roughly consistent with Shannon’s estimate that “when statistical
  effects extending over not more than 8 letters are considered the
  entropy is roughly 2.3 bits per character;”

for the 9th through the 20th character the entropy is taken to be 1.5 bits per character;

for characters 21 and above the entropy is taken to be 1 bit per character;

A “bonus” of 6 bits of entropy is assigned for a composition rule that requires both
  upper case and non-alphabetic characters. This
  forces the use of these characters, but in many cases thee characters
  will occur only at the beginning or the end of the password, and it
  reduces the total search space somewhat, so the benefit is probably
  modest and nearly independent of the length of the password;

A bonus of up to 6 bits of entropy is added for an extensive dictionary check. If the
  attacker knows the dictionary, he can avoid
  testing those passwords, and will in any event, be able to guess much
  of the dictionary, which will, however, be the most likely selected
  passwords in the absence of a dictionary rule. The assumption is that
  most of the guessing entropy benefits for a dictionary test accrue to
  relatively short passwords, because any long password that can be
  remembered must necessarily be a “pass-phrase” composed of dictionary
  words, so the bonus declines to zero at 20 characters.

The idea is that an authentication system would pick certain entropy levels as thresholds. For example, 10 bits may be weak, 20 medium and 30 strong (numbers picked arbitrarily as an example, not a recommendation). Unfortunately, the document does not recommend such thresholds, probably because the computational power available to brute force or guess passwords increases over time:

As an alternative to imposing some arbitrary specific set of rules, an
  authentication system might grade user passwords, using the rules
  stated above, and accept any that meet some minimum entropy standard.
  For example, suppose passwords with at least 24-bits of entropy were
  required. We can calculate the entropy estimate of
  “IamtheCapitanofthePina4” by observing that the string has 23
  characters and would satisfy a composition rule requiring upper case
  and non-alphabetic characters.

This may or may not be what you are looking for but is not a bad reference point, if nothing else.

[Edit: Added the following.]

The paper Testing Metrics for Password Creation Policies
by Attacking Large Sets of Revealed Passwords (by Matt Weir, Sudhir Aggarwal, Michael Collins and Henry Stern) demonstrated the Shannon model, described above, is not an accurate model of entropy for human generated passwords. I would recommend looking at "Section 5 Generating New Password Creation Policies" for more accurate proposals.

OwnerDisplayName: Wug


问:
Where should I handle fatal exceptions
Suppose I have a controller that loads a file and hands it over to the processing.

Should I handle the exception in the file loader and return Null if something is wrong, or should I throw the exception and handle it in the controller?

Without the file the rest of the program can´t work. Where should I handle a exception that shuts down the program properly?

I want to shut down an Android application properly.

答:
In layman's words:

You should not return null.

The exception should be handled in the top-most layer.

The program should not terminate, but give feedback to the user, unless it is a Unix style command line program where it's ok to terminate after showing an error message.

By definition no exception is fatal and each one can be handled.

Errors are fatal and cannot be recovered from.

Exceptions and errors are not the same.

Title: Where should I handle fatal exceptions


答:
You ask

Specifically, can anyone think of situations where feeding a password to the algorithm would OVERESTIMATE its strength?

But you have an example in the question. By design, xkcd2 has ~44 bits of entropy, but your estimate is 160.5 bits.

Title: How can I estimate the entropy of a password?

Body:
Having read various resources about password strength I'm trying to create an algorithm that will provide a rough estimation of how much entropy a password has.

I'm trying to create an algorithm that's as comprehensive as possible.  At this point I only have pseudocode, but the algorithm covers the following:

password length

repeated characters

patterns (logical)

different character spaces (LC, UC, Numeric, Special, Extended)

dictionary attacks

It does NOT cover the following, and SHOULD cover it WELL (though not perfectly):

ordering (passwords can be strictly ordered by output of this algorithm)

patterns (spatial)

Can anyone provide some insight on what this algorithm might be weak to?  Specifically, can anyone think of situations where feeding a password to the algorithm would OVERESTIMATE its strength?  Underestimations are less of an issue.

The algorithm:

```<code>// the password to test
password = ?
length = length(password)

// unique character counts from password (duplicates discarded)
uqlca = number of unique lowercase alphabetic characters in password
uquca = number of uppercase alphabetic characters
uqd   = number of unique digits
uqsp  = number of unique special characters (anything with a key on the keyboard)
uqxc  = number of unique special special characters (alt codes, extended-ascii stuff)

// algorithm parameters, total sizes of alphabet spaces
Nlca = total possible number of lowercase letters (26)
Nuca = total uppercase letters (26)
Nd   = total digits (10)
Nsp  = total special characters (32 or something)
Nxc  = total extended ascii characters that dont fit into other categorys (idk, 50?)

// algorithm parameters, pw strength growth rates as percentages (per character)
flca = entropy growth factor for lowercase letters (.25 is probably a good value)
fuca = EGF for uppercase letters (.4 is probably good)
fd   = EGF for digits (.4 is probably good)
fsp  = EGF for special chars (.5 is probably good)
fxc  = EGF for extended ascii chars (.75 is probably good)

// repetition factors.  few unique letters == low factor, many unique == high
rflca = (1 - (1 - flca) ^ uqlca)
rfuca = (1 - (1 - fuca) ^ uquca)
rfd   = (1 - (1 - fd  ) ^ uqd  )
rfsp  = (1 - (1 - fsp ) ^ uqsp )
rfxc  = (1 - (1 - fxc ) ^ uqxc )

// digit strengths
strength =
( rflca * Nlca +
  rfuca * Nuca +
  rfd   * Nd   +
  rfsp  * Nsp  +
  rfxc  * Nxc    ) ^ length

entropybits = log_base_2(strength)
</code>```

A few inputs and their desired and actual entropy_bits outputs:

```<code>INPUT           DESIRED        ACTUAL
aaa             very pathetic  8.1
aaaaaaaaa       pathetic       24.7
abcdefghi       weak           31.2
H0ley$Mol3y_    strong         72.2
s^fU¬5ü;y34G<   wtf            88.9
[a^36]*         pathetic       97.2
[a^20]A[a^15]*  strong         146.8
xkcd1**         medium         79.3
xkcd2**         wtf            160.5

* these 2 passwords use shortened notation, where [a^N] expands to N a's.
** xkcd1 = "Tr0ub4dor&3", xkcd2 = "correct horse battery staple"
</code>```

The algorithm does realize (correctly) that increasing the alphabet size (even by one digit) vastly strengthens long passwords, as shown by the difference in entropy_bits for the 6th and 7th passwords, which both consist of 36 a's, but the second's 21st a is capitalized.  However, they do not account for the fact that having a password of 36 a's is not a good idea, it's easily broken with a weak password cracker (and anyone who watches you type it will see it) and the algorithm doesn't reflect that.

It does, however, reflect the fact that xkcd1 is a weak password compared to xkcd2, despite having greater complexity density (is this even a thing?).

How can I improve this algorithm?

Addendum 1

Dictionary attacks and pattern based attacks seem to be the big thing, so I'll take a stab at addressing those.

I could perform a comprehensive search through the password for words from a word list and replace words with tokens unique to the words they represent.  Word-tokens would then be treated as characters and have their own weight system, and would add their own weights to the password.  I'd need a few new algorithm parameters (I'll call them lw, Nw ~= 2^11, fw ~= .5, and rfw) and I'd factor the weight into the password as I would any of the other weights.

This word search could be specially modified to match both lowercase and uppercase letters as well as common character substitutions, like that of E with 3.  If I didn't add extra weight to such matched words, the algorithm would underestimate their strength by a bit or two per word, which is OK.  Otherwise, a general rule would be, for each non-perfect character match, give the word a bonus bit.

I could then perform simple pattern checks, such as searches for runs of repeated characters and derivative tests (take the difference between each character), which would identify patterns such as 'aaaaa' and '12345', and replace each detected pattern with a pattern token, unique to the pattern and length.  The algorithmic parameters (specifically, entropy per pattern) could be generated on the fly based on the pattern.

At this point, I'd take the length of the password.  Each word token and pattern token would count as one character; each token would replace the characters they symbolically represented.

I made up some sort of pattern notation, but it includes the pattern length l, the pattern order o, and the base element b.  This information could be used to compute some arbitrary weight for each pattern.  I'd do something better in actual code.

Modified Example:

```<code>Password:          1234kitty$$$$$herpderp
Tokenized:         1 2 3 4 k i t t y $ $ $ $ $ h e r p d e r p
Words Filtered:    1 2 3 4 @W5783 $ $ $ $ $ @W9001 @W9002
Patterns Filtered: @P[l=4,o=1,b='1'] @W5783 @P[l=5,o=0,b='$'] @W9001 @W9002

Breakdown:         3 small, unique words and 2 patterns
Entropy:           about 45 bits, as per modified algorithm

Password:          correcthorsebatterystaple
Tokenized:         c o r r e c t h o r s e b a t t e r y s t a p l e
Words Filtered:    @W6783 @W7923 @W1535 @W2285

Breakdown:         4 small, unique words and no patterns
Entropy:           43 bits, as per modified algorithm
</code>```

The exact semantics of how entropy is calculated from patterns is up for discussion.  I was thinking something like:

```<code>entropy(b) * l * (o + 1) // o will be either zero or one
</code>```

The modified algorithm would find flaws with and reduce the strength of each password in the original table, with the exception of s^fU¬5ü;y34G<, which contains no words or patterns.


答:
Can anyone provide some insight on what this algorithm might be weak to? Specifically, can anyone think of situations where feeding a password to the algorithm would OVERESTIMATE its strength?

You've hinted at some in the preamble (dictionary attacks, etc).  Essentially, there are a number of common practices that can be guessed at by the attacker which greatly lowers the  search space.  I am pretty sure that your algorithm will "overestimate" the following:

everywhere

Everywhere

Everywhere1

The password is quite long, but is trivially crackable since the original word appears in a basic dictionary, and the modifications are considered common enough to form part of any decent dictionary attack.  Typical letter -> number conversions (i.e. 3v3rywh3r3) should also be considered pretty weak, and you should penalise for these.

To a much lesser degree, other trouble passwords may be ones that have obvious patterns, such as:

abcdefghijklmnop

abcde12345

Although these are probably less likely to be targeted in actual dictionary attacks, they suffer from similar problems as your "aaaaa..." example.

I'm not sure if password phrases are currently targeted in most dictionary attacks, but no doubt as they gain popularity, they will be targeted more and more.  I think the famous xkcd example takes this into account, since only 11 bits are assigned for each "common word".  Your algorithm overestimates these types of passwords, as well.

So, to summarise, the algorithm does a fairly good job of the estimation, but it really should be taking into consideration the structure of the password and common, known patterns.


问:
Throwing and catching exceptions in the same function/method
I've written a function that asks a user for input until user enters a positive integer (a natural number). Somebody said I shouldn't throw and catch exceptions in my function and should let the caller of my function handle them.

I wonder what other developers think about this. I'm also probably misusing exceptions in the function. Here's the code in Java:

```<code>private static int sideInput()
{
    int side = 0;
    String input;
    Scanner scanner = new Scanner(System.in);

    do {
        System.out.print("Side length: ");
        input = scanner.nextLine();
        try {
            side = Integer.parseInt(input);
            if (side <= 0) {
                // probably a misuse of exceptions
                throw new NumberFormatException();
            }
        }
        catch (NumberFormatException numFormExc) {
            System.out.println("Invalid input. Enter a natural number.");
        }
    } while (side <= 0);

    return side;
}
</code>```

I'm interested in two things:

Should I let the caller worry about exceptions? The point of the function is that it nags the user until the user enters a natural number. Is the point of the function bad? I'm not talking about UI (user not being able to get out of the loop without proper input), but about looped input with exceptions handled.

Would you say the throw statement (in this case) is a misuse of exceptions? I could easily create a flag for checking validity of the number and output the warning message based on that flag. But that would add more lines to the code and I think it's perfectly readable as it is.

The thing is I often write a separate input function. If user has to input a number multiple times, I create a separate function for input that handles all formatting exceptions and limitations.

答:
You should not both throw and catch the same exception in a method, I even think the the catch block will catch the same exception you are throwing, so you are not really throwing it.

If parseInt was successful, then it's not a NumberFormatException.

if side is less than zero, you should throw a NegativeSideLengthException;

Create a custom/bussiness Exception named NegativeSideLengthException

```<code>public class NegativeSideLengthException extends Exception
{

    public NegativeSideLengthException(Integer i)
    {
        super("Invalid negative side length "+i);
    }

}
</code>```

Then sideInput throws NegativeSideLengthException

```<code>private static int sideInput() throws NegativeSideLengthException
{
    int side = 0;
    String input;
    Scanner scanner = new Scanner(System.in);

    do {
        System.out.print("Side length: ");
        input = scanner.nextLine();
        try {
            side = Integer.parseInt(input);
            if (side <= 0) {
                throw new NegativeSideLengthException(side);
            }
        }
        catch (NumberFormatException numFormExc) {
            System.out.println("Invalid input. Enter a natural number.");
        }
    } while (side <= 0);

    return side;
}
</code>```

You can even ( if you want ) add another catch block to catch NegativeSideLengthException and not have the method throw it.

```<code>do {
    System.out.print("Side length: ");
    input = scanner.nextLine();
    try {
        side = Integer.parseInt(input);
        if (side <= 0) {
            throw new NegativeSideLengthException(side);
        }
    }
    catch (NumberFormatException numFormExc) {
        System.out.println("Invalid input. Enter a natural number.");
    } catch (NegativeSideLengthException e){
        System.out.println("Invalid input. Enter a non-negative number.");
    }
} while (side <= 0);
</code>```

Flags are not a good way to handle exceptions.

Body:
You should not both throw and catch the same exception in a method, I even think the the catch block will catch the same exception you are throwing, so you are not really throwing it.

If parseInt was successful, then it's not a NumberFormatException.

if side is less than zero, you should throw a NegativeSideLengthException;

Create a custom/bussiness Exception named NegativeSideLengthException

public class NegativeSideLengthException extends Exception
{

    public NegativeSideLengthException(Integer i)
    {
        super("Invalid negative side length "+i);
    }

}

Then sideInput throws NegativeSideLengthException

private static int sideInput() throws NegativeSideLengthException
{
    int side = 0;
    String input;
    Scanner scanner = new Scanner(System.in);

    do {
        System.out.print("Side length: ");
        input = scanner.nextLine();
        try {
            side = Integer.parseInt(input);
            if (side <= 0) {
                throw new NegativeSideLengthException(side);
            }
        }
        catch (NumberFormatException numFormExc) {
            System.out.println("Invalid input. Enter a natural number.");
        }
    } while (side <= 0);

    return side;
}

You can even ( if you want ) add another catch block to catch NegativeSideLengthException and not have the method throw it.

do {
    System.out.print("Side length: ");
    input = scanner.nextLine();
    try {
        side = Integer.parseInt(input);
        if (side <= 0) {
            throw new NegativeSideLengthException(side);
        }
    }
    catch (NumberFormatException numFormExc) {
        System.out.println("Invalid input. Enter a natural number.");
    } catch (NegativeSideLengthException e){
        System.out.println("Invalid input. Enter a non-negative number.");
    }
} while (side <= 0);

Flags are not a good way to handle exceptions.


问:
How to avoid throwing vexing exceptions?
Reading Eric Lippert's article on exceptions was definitely an eye opener on how I should approach exceptions, both as the producer and as the consumer. However, I'm still struggling to define a guideline regarding how to avoid throwing vexing exceptions.

Specifically:

Suppose you have a Save method that can fail because a) Somebody else modified the record before you, or b) The value you're trying to create already exists. These conditions are to be expected and not exceptional, so instead of throwing an exception you decide to create a Try version of your method, TrySave, which returns a boolean indicating if the save succeeded. But if it fails, how will the consumer know what was the problem? Or would it be best to return an enum indicating the result, kind of Ok/RecordAlreadyModified/ValueAlreadyExists? With integer.TryParse this problem doesn't exist, since there's only one reason the method can fail.

Is the previous example really a vexing situation? Or would throwing an exception in this case be the preferred way? I know that's how it's done in most libraries and frameworks, including the Entity framework.

How do you decide when to create a Try version of your method vs. providing some way to test beforehand if the method will work or not? I'm currently following these guidelines:

If there is the chance of a race condition, then create a Try version. This prevents the need for the consumer to catch an exogenous exception. For example, in the Save method described before.

If the method to test the condition pretty much would do all that the original method does, then create a Try version. For example, integer.TryParse().

In any other case, create a method to test the condition.

答:
The save() method must throw an exception.

The top-most layer should catch and inform the user, without terminating the program, unless it's an Unix like command line programs, in which case it's OK to terminate.

Return values are not a good way to manage exceptions.

ContentLicense: CC BY-SA 4.0


问:
Am I wrong in thinking that needing something like AutoMapper is an indication of poor design?
Automapper is an "object-object mapper" for .Net, which means copying objects from a class into another class that represents the same thing.

Why is this ever useful? Is the duplication of classes ever useful/good design?

答:
A quick google search revealed this example:

http://www.codeproject.com/Articles/61629/AutoMapper

showing a perfectly valid usage of AutoMapper which is definitely not an example for a poor design. In a layered application, you may have objects in your data or business layer, and you sometimes need just a subset of the attributes of that data objects, or some kind of view to them in your UI layer. So you create a view model which contains objects with exactly the attributes you need in your UI, not more, and use AutoMapper to provide the content of that objects with less boilerplate code.

In such a situation your "view objects" are not a duplicate of the original class. They have different methods and perhaps a few duplicate attributes. But that's ok as long as you use that view objects only for UI displaying purposes and don't start to misuse them for data manipulation or business operations.

Another topic you may read to get a better understanding of this is Fowlers Command Query Responsibility Segregation pattern, in contrast to CRUD. It shows you situations where different object models for querying data and updating them in a database make sense. Here, mapping from one object model to another may also be done by a tool like AutoMapper.


答:
Check out the source code for KeePass at the bottom of this page. The QualityEstimation class implements a rather nice algorithm which seems to be in line with what you're looking to have in place. My results look as such:

```<code>aaa                              8
aaaaaaaaa                        9
abcdefghi                       18
H0ley$Mol3y_                    73
s^fU¬5ü;y34G<                   99
[a^36]*                         10
[a^20]A[a^15]*                  18
Tr0ub4dor&3                     66
correct horse battery staple    98
</code>```

Body:
Check out the source code for KeePass at the bottom of this page. The QualityEstimation class implements a rather nice algorithm which seems to be in line with what you're looking to have in place. My results look as such:

aaa                              8
aaaaaaaaa                        9
abcdefghi                       18
H0ley$Mol3y_                    73
s^fU¬5ü;y34G<                   99
[a^36]*                         10
[a^20]A[a^15]*                  18
Tr0ub4dor&3                     66
correct horse battery staple    98


问:
Why aren't more desktop apps written with Qt?
As far as I know and have understood in my experience with Qt, it's a very good and easy to learn library. It has a very well designed API and is cross-platform, and these are just two of the many features that make it attractive. I'm interested to know why more programmers don't use Qt. Is there a deficiency which speaks against it? Which feature makes other libraries better than Qt? Is the issue related to licensing?</p>

答:
The most important but not mentioned thing. In big project one thing causes so much problems and non necessary code. Qt's signal slot mechanisms is inefficient. Qt widgets does not provide necessary signals for event simple widgets. For example you can not set signals for onHover, onMouseEnter, onMouseLeave, onKeyReleased, onLostFocus, onGainFocus and etc. Even the most complex widget such as QTreeWidget does provide one or two ultra simple useless signals.

Yes, you can use events BUT !!! you have create new class for each widget with custom event. This is huge efficiency lost;

You have rewrite each customized widget object event there is small changes.

You lose all of Qt Designer stuff. You have to promote every widget with custom events.

Project became bigger and hard to maintain.

You started dislike qt because of this. And starting to talk about how .net provides delegates, how it is much much much more better than signal slot, how .net components (widgets) generally provides every event that you can imagine. And etc.

One of my college has wrote made new combo box class for each combo box widget because he had to use some non signal event. True story...

However, Qt is the best C++ UI framework so far with downs and ups.


问:
Have I mistakenly assumed that my routines are loosely coupled?
My Selenium test structures goes as -

Data Object class -

```<code>public class RegistrationData {

  String firstName = "test first name";
  String lastName = "test last name";

  // Getter Setter Here
}
</code>```

Page Object class which carries out operations on a Web Page -

```<code>public class RegistrationPage {
   private RegistrationData regData;

   public void setRegistrationData(RegistrationData regData) {
   this.regData = regData();

   public NewAccountPage fillRegForm() {
     enterFirstName("FirstNameTextBoxLocator", regData.getFirstName);
     enterLastName("LastNameTextBoxLocator", regData.getLastName);
     // Some more fields are filled here
     return NewAccountPage();
   }
}
</code>```

And test class uses them as -

```<code>public class TestRegistration extends SelTestCase {

   @Test
   public void testRegNewUser() {
     RegistrationData regData = new RegistrationData();
     RegistrationPage regPage = New RegistrationPage();
     regPage.setRegistrationData(regData)
     regPage.fillRegForm();
     // Some assertion here
   }
}
</code>```

Now since fillRegForm method does not take any argument, Can I assume that it is an example of loose coupling despite I need to set RegistrationData in RegistrationPage before being able to use fillRegForm method.

答:
Short answer:

The three classes are strongly coupled.

fillRegForm not taking any argument is a matter of cohesion, not loose coupling.


问:
Difference between Unified Process model and agile development
I am confused concerning the unified process model and agile development. When I'm reading about the UP, I'm only understanding that it is an iterative improvement.  Can someone please clarify this?</p>

答:
Both UP and Agile are iterative approaches.  If we were to draw a spectrum of documentation requirements for development processes then Waterfall would represent one extreme, Agile would be placed on the other side.  UP exists in the middle between Waterfall and Agile and can take many slots in that spectrum depending upon how it's implemented.

No documentation as a development model would be much further past Agile on that spectrum, so please don't misconstrue my comment as indicating Agile is as far from the "middle" as Waterfall is.  Agile can be a pretty reasonable approach to development.

UP is more document (artifact) heavy than Agile is.  There is a broader range of artifacts that can be created through the development process, and there are potentially more stages for review.  Agile relies a lot more on direct communication and short iterations for constant validation.

As a generalization, UP is better suited for larger teams on larger projects where you won't always have face to face communications.  Agile works better on smaller teams and smaller projects.  But those are just generalizations, not hard and fast rules.

IMO, every team should examine the various development approaches, including Waterfall, to understand the strengths of the approach and to determine if that's appropriate for the team.  I have seen a number of Agile projects that could use better defined documentation.  I have seen UP projects that disconnected from the client's real requirements because they picked the wrong artifacts to work with.  All processes have their negatives, so make sure the right approach is picked for the project and team.


问:
OO Software Architecture - base class that everything inherits from. Bad/good idea?
I am reviewing a proposed OO software architecture that looks like this:

Base

Foo

Something

Bar

SomethingElse

Where Base is a static class.

My immediate thought was that every object in any class will inherit all the methods in Base which would create a large object.  Could this cause problems for a large system?  The whole architecture is hierarchical.. the 'tree' is much bigger than this really.  Does this sort of architecture have a name (hierarchical?!).  What are the known pros and cons?

答:
Short answer:

It seems the design is flawed.

I can't imagine how every class in the solution domain has an "is a" relationship with a single class, except they all inherit from Object, but that's another thing.

If you show us some real class names in that tree, I'm sure that will be obvious.


问:
Can I use a child class variables in its parent class?
I am programming in Objective C, iOS. I create a Class A which is a parent class, and Class B inherits to Class A.

Now I have Class B variables which I also need to use in Class A. And also one another Class C, Class A add in Class C (not inherits), and I want to use Class B variables in Class C.

How can I access? I have created object also but not working, is that possible to access?

答:
Short answer:

That can't be done because parent classes are totally oblivious of it's children.


问:
Algorithm to use for shop floor layout?
I ran into a classroom problem yesterday (business oriented class, not computer science) and I found it interesting from an algorithmic perspective.

The problem goes something like this:

Assume there is a shop floor with N different rooms, and you have N different departments that need to go in those rooms.  The departments and the rooms are all the same size, so any department could go in any room.  There is a known travel distance from each room to each other room.  There is also a known amount of trips necessary from one department to another (trips are counted the same regardless which room they originate from, so a trip from A to B is equivalent to a trip from B to A).  Given those inputs, determine a layout of departments into rooms which minimizes travel time.

What is the best way to approach this problem algorithmically?  Is there already a particular algorithm or class of algorithms designed to solve this type of problem?  Does this type of problem have a name in computer science?

I am not looking for you to design an algorithm to solve this, although feel free to do so if you would like.  I'm wondering if this is a problem space that has already been well defined and studied algorithmically and if so get some links to research further.  I can see a lot of different data structures and algorithms that might apply to this and I'm curious which approach would be "best".

And don't worry, you are not doing my homework for me.  This is not a homework problem per se, as this is a business course and we were simply discussing the concepts and not trying to solve the problem algorithmically.

答: This is called Facility Location Problem, which is a NP-hard problem. Typical algorithmic solution to such problem is using approximation algorithms.</p>

Title: Algorithm to use for shop floor layout?


问:
What are the pros and cons of a language using whitespace vs. {}'s to indicate scope?
There seems to be a conflict over whether its better to use whitespace or tokens like brackets to indicate scope. I've seen many praise python's solution to the inconsistent indentation problem, but many disagree:

Any language that has whitespace as tokens needs to die.

posted later on the same answer:

I was sortof anti-whitespace-as-tokens, until I actually tried it. It probably helped that my personal white-space layout pretty much matches what everyone in python-land uses. Perhaps it's that I am a bit minimalist, but if you're going to indent anyways, why bother with the {}s?

I can see some clear arguments for each side:

using whitespace:

helps reduce inconsistent indentation in code

clears the screen by replace visible tokens with whitespace to serve the same purpose

using tokens:

much easier to cut and paste code to different levels (you don't have to fix the
indentation)

more consistent. Some text editors display whitespace differently.

more popular currently.

Are there any points I missed? Which do you prefer? Any words of wisdom after having worked with one or the other for a long time?

PS. I hate it when languages don't use the same token for each control structure. VB is really annoying with its End If and End While statements, most other languages just use {}'s for everything. But maybe that's a topic for a different question...

答:
At the risk of sounding like an utter fanboy, I think everyone who claims that whitespace “helps reduce inconsistent indentation in code” has never used Visual Studio. With a single command (I think the default shortcut is Ctrl+K,D), all the indentation is instantaneously consistent¹. Furthermore, when pasting code the indentation is instantaneously corrected without having to do anything at all, and the same is true when writing new code or when wrapping something in an if or some other block (reformat happens as the } is typed). Furthermore, pressing Enter after a completed statement always places the cursor at the correct indentation level for the next statement, even if the previous statement was indented further because of an if or similar, making it very difficult to accidentally think that a statement is still under an if when it isn’t.

The point I’m trying to make is not that Visual Studio is great. The point I’m trying to make is that the IDE can automate indentation-fixing (and other formatting issues), but only if the meaning of the program does not depend on its formatting. This gives the programmer a greater opportunity to focus on the actual programming task. A syntax like Python’s is counterproductive: it is not possible to write an IDE that can “fix” the indentation of Python code because the indentation itself specifies some of the semantics.

¹ (I know there is a special case which VS refuses to reformat, namely array literals that span multiple lines, but that’s beside the point.)


问:
Why would an employer ask for a 'long' code sample?
What would a large project that spanned multiple files and >1000 lines show to an employer that a few individual files and a couple hundred lines couldn't capture?</p>

答:
I think it is likely that this potential employer wants to see how you would structure a larger application and is looking for whether you made use of good design principles.

You should just politely contact this potential employer and ask them yourself.


答:
Reason 1: Is it your own code, or something you copied?

(Mostly) anyone can copy a short piece of code from the internet, explore it, and give it as his own during an interview while being able to explain the code itself.

Doing the same with a large codebase would be difficult, since it would be easily recognized and searchable as one of the an open source projects.

Reason 2: Do you have skills to work on a large codebase?

When you give a link to a large codebase under version control, you show that you actually have the skills required to write a large codebase.

When you give a small piece of code, you are showing just that you was able to write a small piece of code. Would you be able to work on a codebase with thousands of lines?

Reason 3: Have you studied/verified your code enough?

For an interviewer, it would be easy to find an issue in a large codebase¹, and to interview you on it. The interviewer may ask if you are aware of one of those bugs, why didn't you solve it, and how do you think to be able to solve it now.

Moreover, during an interview, the interviewer can target any smallest part of the codebase, and ask you to explain it in details, to see how well do you know your own code.

¹ Strangely enough, it is not rare to see small (under 100 lines) pieces of code with one or several bugs where the code is not doing what it is expected to do. This applies as well to candidates who are writing that they have +10 years of professional experience and qualify themselves as highly skillful.

Title: Why would an employer ask for a 'long' code sample?

Body: What would a large project that spanned multiple files and >1000 lines show to an employer that a few individual files and a couple hundred lines couldn't capture?</p>


问:
Is the creator of a piece of software bound by the license he gives it?
For example, if a person creates an application that they open-source under a license that says you can use this code but you cannot sell it, has that person just bound himself to not selling it now as well?</p>

答: You retain copyright and as long as you don't sign THAT away you can license your code under different licenses. Watch out though, it may turn out hard to remove a license once you put a license on a work.</p>


问:
How to implement child-parent aggregation link in C++?
Suppose that I have

three classes P, C1, C2,

composition (strong aggregation) relations between P <>- C1 and P <>- C2, i.e. every instance of P contains an instance of C1 and an instance of C2, which are destroyed when the parent P instance is destroyed.

an association relation between instances of C1 and C2 (not necessarily between children of the same P).

To implement this, in C++ I normally

define three classes P, C1, C2,

define two member variables of P of type boost::shared_ptr<C1>, boost::shared_ptr<C2>, and initialize them with newly created objects in P's constructor,

implement the relation between C1 and C2 using a boost::weak_ptr<C2> member variable in C1 and a boost::weak_ptr<C1> member variable in C2 that can be set later via appropriate methods, when the relation is established.

Now, I also would like to have a link from each C1 and C2 object to its P parent object. What is a good way to implement this?

My current idea is to use a simple constant raw pointer (P * const) that is set from the constructor of P (which, in turn, calls the constructors of C1 and C2), i.e. something like:

```<code>class C1
{
  public:
    C1(P * const p, ...)
    : paren(p)
    {
    ...
    }

  private:
    P * const parent;
    ...
};

class P
{
  public:
    P(...)
    : childC1(new C1(this, ...))
    ...
    {
        ...
    }

  private:
    boost::shared_ptr<C1> childC1;
    ...
};
</code>```

Honestly I see no risk in using a private constant raw pointer in this way but I know that raw pointers are often frowned upon in C++ so I was wondering if there is an alternative solution.

答: Pointers create headaches when you use them to manage dynamically allocated resources. In this case, however, a pointer is a simple "backlink" to the parent, and it cannot be changed during the lifetime of a child object (i.e. there's no re-parenting). This is a good solution that helps you keep things simple.</p>


答:
Writing small pieces of code and stitching them together to form a coherent, bigger whole are two different skill sets entirely.

Asking for bigger pieces of code across several files is a way of testing for the latter. I.e. the employer isn’t simply interested in your “coding skills” but in your architectural skills.


答:
A license is the owner assigning rights and responsibilities over their intellectual property to a third party. Assigning one set of rights in one license does not preclude them from assigning a different set of rights and responsibilities to another third party.

This is how software products come to be dual-licensed or multi-licensed. Each license grants certain rights but imposes its own restrictions. Thus a software house may opt to release a software product under GPL for free, requiring derivations to be provided with source code, and under a closed source license, for a fee, where derivatives can be supplied without source code.

Title: Is the creator of a piece of software bound by the license he gives it?

Body: For example, if a person creates an application that they open-source under a license that says you can use this code but you cannot sell it, has that person just bound himself to not selling it now as well?</p>


问:
Should an image be able to resize itself in OOP?
I'm writing an app that will have an Image entity, and I'm already having trouble deciding whose responsibility each task should be.

First I have the Image class. It has a path, width, and other attributes.

Then I created an ImageRepository class, for retrieving images with a single and tested method, eg: findAllImagesWithoutThumbnail().

But now I also need to be able to createThumbnail(). Who should deal with that? I was thinking about having an ImageManager class, which would be an app-specific class (there would also be a third party image manipulation reusable component of choice, I'm not reinventing the wheel).

Or maybe it would be 0K to let the Image resize itself? Or let the ImageRepository and ImageManager be the same class?

What do you think?

答:
Short answer:

My recomendation is adding this methods the image class:

```<code>public Image getResizedVersion(int width, int height);
public Image getResizedVersion(double percentage);
</code>```

The Image object is still inmutable, these methods return a new image.

Body:
Short answer:

My recomendation is adding this methods the image class:

public Image getResizedVersion(int width, int height);
public Image getResizedVersion(double percentage);

The Image object is still inmutable, these methods return a new image.


答:
So here's the problem, CMMI and RUP have gotten a bad rep because they have been associated with expensive, documentation-riddled, over-priced projects. This is how it was sold by the "experts". Think about it, when you ask an outside company to help you put a software process into place and then to implement a pilot project using that process, the temptation is very high for that company to make the process as drawn out and convoluted as possible.

The RUP does not require you to fill out every document in the catalog, it provides them as guidelines and templates and encourages you to take what you need and even GASP customize the process to fit your company.

Likewise CMMI does not REQUIRE reams of documentation. Unfortunately, a lot of the companies that perform CMMI appraisals are the same ones that sell RUP as a waterfall process. One need not look far to see how conflicting interests of an auditor who is also a contractor can lead to disaster (e.g. Enron).

RUP is a framework and as you've recognized is an iterative process. There are agile frameworks that recognize this (see eXtreme Unified Process).

Title: Difference between Unified Process model and agile development

Body: I am confused concerning the unified process model and agile development. When I'm reading about the UP, I'm only understanding that it is an iterative improvement.  Can someone please clarify this?</p>


问:
Should I pass an object into a constructor, or instantiate in class?
Consider these two examples:

Passing an object to a constructor

```<code>class ExampleA
{
  private $config;
  public function __construct($config)
  {
     $this->config = $config;
  }
}
$config = new Config;
$exampleA = new ExampleA($config);
</code>```

Instantiating a class

```<code>class ExampleB
{
  private $config;
  public function __construct()
  {
     $this->config = new Config;
  }
}
$exampleA = new ExampleA();
</code>```

Which is the correct way to handle adding an object as a property? When should I use one over the other? Does unit testing affect what I should use?

答:
ExampleA is decoupled from concrete class Config which is good, provided object received if not of type Config but the type of an abstract superclass of Config.

ExampleB is strongly coupled to concrete class Config which is bad.

Instantiating an object creates a strong coupling between classes. It should be done in a Factory class.


问:
How is it possible to write the compiler of a programming language with that language itself

Possible Duplicate:

  How could the first C++ compiler be written in C++?

You probably heard that Microsoft released a new language called TypeScript which is a the typed superset of JavaScript.

The most interesting thing that makes me wonder is the fact that its compiler writen in TypeScript itself.

Call me ignorant but I really couldn't figure out in my head how that is possible. This is just like chicken and egg problem in my head because there is no compiler to compile TypeScript's compiler in the first place. How is it possible to write a compiler of the compiler of a programming language with that language?

答: It's called Bootstrapping. You're right that the first version has to be written in another language. But once that's done, you can write successive versions with the previously finished compiler.</p>