问:
Snapchat clone: How do I secure pre-downloaded notifications so that they cannot be opened outside of the app?
Say I'm making a snapchat clone app for Android and iOS. Let's say that I get a snapchat from Baz. I want to pre-download the audio for this snapchat. However, as the developer, I want to secure this audio from being viewable outside of the app.

I've been thinking of encrypting it using AES with an IV and key that are both generated from a pseudo-random function that takes the user's unique ID as input. However, if an attacker found out that this was the way we encrypt our files, and had access to our PRF, he would easily be able to decrypt it and store it permanently. The thing is, I don't have enough background in cryptography or android programming to tell if that's really a concern or not. The attacker has to learn a lot about our cipher in order to break it, but he could gain pretty much all of that from looking at the unobfuscated source of our app.

Is my suggested approach cryptographically secure? What other, better or simpler approaches could I take to solving this problem?

答:
he could gain pretty much all of that from looking at the unobfuscated
  source of our app.

This is DEFINITELY a concern. If that's the case, then your application definitely has a major security flaw. That could be anywhere from hardcoding password/keys in the code, to writing your own crypto algorithms, to just leaking out information just because of the way code is written.

An established practice in security community has been that even if the code is made public, it should have no impact on the security of the application. Likewise, the cryptographic algorithms and their implementations are public knowledge, and is scrutinized by the security community all the time. It is only after such scrutiny that they are declared secure "enough" for use for various well-defined purposes.

Having said that you have two MAJOR flaws:

Pseudo random function is not a secure way to derive a key and IV. What you need to use is a Key Derivation Function (KDF), which are implemented in most languages.

You need to derive a Key and an IV from a secret, such as a password or use asymmetric algorithm in which the private key is used for decryption which happens to be secret. User's ID is NOT a secret.

There are also two places where you need to encrypt the data:

Encrypt when it is send from one user to the other.

Encrypt for storage on user's device.

I do not know which of these two were you planning to use. For the first case, you can either use symmetric keys or asymmetric keys. Although asymmetric keys have become de facto standard, more recently, some security experts (such as Bruce Schneier) have recommended preferring symmetric over asymmetric keys, but you will have to evaluate which one suffices your needs.

In any case, when you are using a symmetric algorithm, then using user's unique ID is not sufficient since unique IDs are usually known. You could use user's password and then derive a key and IV for encryption using a key derivation function (KDF). You will find already implemented KDFs very much like encryption algorithms. You would want to use a random salt with a high number of iterations (recommendations vary, but I have found > 10000 is usually fast enough and considered reasonably secure). You can then embed the unencrypted salt and the number of iterations along with your cipher text in one package that you store. When you have to decrypt, you read that salt and the number of iterations from the package you stored, and use them with the password to derive the key and the IV, and decrypt the cipher text.

A better yet approach is to generate a master key, which you can secure using the mechanism defined above. Use this master key to actually encrypt all the data. This way, if the user changes the password, all you have to do is decrypt the master key, and encrypt again using a key and IV derived from the new password instead of doing this with all the data that the user has stored.

You can also use certificates (which are asymmetric keys) that you store on the client and use for encryption/decryption, but the overall approach will change somewhat. Without knowing exactly what you are trying to encrypt, I do not want to go into too many possibilities.

If you clarify a bit more whether you are looking for encryption between two parties vs encrypting data at rest, I might be able to come back and provide a better recommendation.


问:
asp.net mvc vs angular.js model binding
So I've noticed a trend lately of .net web developers using angular.js on the client side of applications and I've become more curious as I play around with angular and compare it to how I would do things in asp.net mvc.

I'll give a quick example of what really got me thinking.

I recently came across a situation at work (I work in a .net environment) where I needed to create a table bound to a collection of objects that had the ability to add and remove rows/items from the collection. I had an add button that created a new object and appended a row to the end of the table, and a remove button in each row to remove a particular object/row. Using asp.net mvc, I first found myself making an ajax call to the server for each operation, updating the server side model, and refreshing part of the page to show the result in the table. This worked but I didn't really like the idea of calling the server to update the model each time, so I tried to come up with a solution to do this on the client side. It turned out to be quite a task, as I had to generate the html on add with validation and all and the correct indexing for the model binding to work. It got worse on remove, as I ended up with a crazy string replace function to recreate the indexes on each item to satisfy the binding requirements (if an item other than the last is removed, the indexes are no longer correct). Now out of curiosity, I tried to recreate this at home in angular (which I had no experience with) and it took me all of about 10 minutes with simple functions to add and remove items from the client side model.

This is just one example, but it seems to me that I'm able to achieve the same results with far fewer calls to the server in angular because of the fact that it binds to a client side model.

So my question is, is this a distinct advantage of using a javascript mvc framework or am I somehow under utilizing the power of asp.net mvc and am I right in thinking that these operations should be done on the client and have no business requiring calls to the server?

答:
In the end it depends on what you are trying to achieve. Whether it is nice user interface and sleek functionality or just basic implementation.

In case of using AngularJS for implementation of UI, you have some basic functionality that people have already wrote about. "Two Way Binding"

The beauty of this is you do need to do too much to manipulate data as it works like model and collection in .NET, once you modify data, they are there and you do not need to worry about updating, managing data also has simple way to update any changes without reloading whole page all the time. I believe that is the main reason why people are using it and we will do more (is simple, fast to deliver results to users and looks nice).

hope this helps

ContentLicense: CC BY-SA 3.0

Title: asp.net mvc vs angular.js model binding


问:
acceptance test driven development in c++
Was put on hold at stack overflow: hopefully it has value here.

I want to use a BDD / TDD / ATDD approach in c++. However I really want to emphasize vertical slices of end to end functionality rather than unit tests. There are plenty of unit testing frameworks.

How would you go about in c++ authoring an approach that emulates a user story based testing framework. If you can avoid reinventing the wheel great otherwise i have no idea how to go about writing one from scratch.

An example from another language would be specflow.

The specific question is - if someone has done it lets use their work - otherwise how would you go about writing a framework like specflow in c++?

答: Use Cucumber CPP which gives you Cucumber support for C++.</p>


问:
Why is it called a memory leak?
I am a hobbyist programmer, bit of a stickler for terminology, currently learning C and recently came across the concept of Memory Leak. Now, I do understand what it means. Dynamic memory allocated to a program is not returned by the program.

But where does the term 'leak' come from? Is it coming from the fact that other programs cannot access the dynamic memory, since one is already hogging it, and thus total memory available from the OS to the heap is reduced and therefore "leaked" to the one hogging it? Basically, are we see the memory leak from the OS's perspective? And therefore saying that it is leaked to the program?

答: It's fairly self explanatory. The application is diminishing system memory, this memory is allocated but not useful to running code. This is analogous to a physical leak as the system memory is slowly lost (like water from a leaky bucket) to useless allocation. I'm not sure about the etymology, but it a fairly obvious analogy, so I doubt there is a clear origin.</p>

Title: Why is it called a memory leak?


答:
Look at it at the other way, from the system perspective. You have a giant pool of free memory (free ram memory) where different programs can make use of. But all of their used resources should be returned sooner or later, or at least being used the entire time. When you no longer need it you should return it to the pool of free memory. Applications that keep asking for memory from the pool but never return it when they're done using it, cause a leak in the free memory pool until they've stopped. The program is a leak to the pool of free memory and I think from that perspective the term memory leak is a correct naming.

So we'll see the leak from the system's perspective.

Title: Why is it called a memory leak?

Body:
I am a hobbyist programmer, bit of a stickler for terminology, currently learning C and recently came across the concept of Memory Leak. Now, I do understand what it means. Dynamic memory allocated to a program is not returned by the program.

But where does the term 'leak' come from? Is it coming from the fact that other programs cannot access the dynamic memory, since one is already hogging it, and thus total memory available from the OS to the heap is reduced and therefore "leaked" to the one hogging it? Basically, are we see the memory leak from the OS's perspective? And therefore saying that it is leaked to the program?


问:
Should state machine with synonym states be shown explicitly?
I am new to state machine modeling and while trying to model a system, I have a question.

An example will explain it better:

Considering a system that does calling (probably a customized cell phone device) with possible states:

idle->calling->signal-dropping->handle->call ended

idle->calling->OS problem->handle->call ended

idle->calling->battery drained->handle->call ended

idle->calling->some other problem->handle->call ended

Above example is in form state1->transition1->state2->transition2->state3

Question is: Is there any significance of these intermediate states? Should they be shown/ modeled explicitly in UML or even programming?

Note: It would be helpful if anyone can mention (some existing if applicable) technical term  used to describe this scenario

答:
As usual, there is no definite answer for how you must model something. Everything that is valid according to whatever modeling language you apply is available and can potentially be used that way.

That being said, intermediate states are nothing out of the ordinary. I even have to correct the comment made by @rwong, that a state remains unchanged in the absence of input events. This is definitely not the case. In particular, the UML standard defines something called a completion transition (UML SSS 15.3.14), for which the semantics is defined such that you can immediately transition to the next state, after the source state has finished its entry and do activities.

So yes, intermediate states can be modeled, and yes, a lot of state machines exist, which do model intermediate states. Whether it makes sense in your scenario or not, however, cannot be easily answered.

In order to answer your questions: Yes, these states can be very significant, but that's mostly due to the behavior your model assigns to them. Whether they should be explicitly modeled has to be decided on a per state basis. If it is insignificant, and you really  just have a transition, then it may be better not to model it explicitly. It's also a judgement call each time, whether you assign an action to the transition or use an intermediate state with a completion transition. A rule of thumb here is that it's justified to use an explicit state, as soon as you have a reasonably complex behavior attached to it. If you just increase a counter variable, however, a transition action is easily sufficient to model that. As for the technical term, I think the UML concept of completion transition seems to be the best fit for what you described.

As a side-note: in your examples, you have different intermediate states reachable after the idle state, and in this case, modeling the intermediate states explicitly immediately shows up a problem: how do you distinguish which transition to use? calling is not your only trigger really, because that would mean your idle state has at least four transitions that trigger based only on calling, whereas you should have mutually exclusive trigger conditions (including guards) for the transitions. If you don't, your state machine becomes non-deterministic, which is something you probably won't want.

I also suggest that you read up on state machines in the UML SSS to get a grip on other typical terms related to state machines. Judging from their absence in your post, I guess you could profit from thinking about the differences between states, transitions, triggers, guards, etc.


问:
Usage of raw pointers
So from the top-voted answer to this question, it appears that using raw pointers for storage isn't frowned upon so much. However, then what is the point of a std::weak_ptr? I thought that storage was the exact purpose of that class. If so, is there any circumstance in which a raw pointer is considered good, valid code? If there isn't any, what is the point of having them in the language? Is it simply historical artifact?

答:
A weak_ptr can actually extend the lifetime of a shared_ptr.

To access what a weak_ptr points to, you have to call lock() on it.  This temporarily upgrades it to a shared_ptr.  You can then use this pointer without the danger of it going away while you are using it.  You don't get that guarantee when you are using naked pointers.

new, delete and raw pointers are not completely useless.  These are the building blocks of what smart pointers are built upon!

Title: Usage of raw pointers


答:
weak_ptr is solely usable in conjunction with shared_ptr. It also has a little memory overhead while some weak pointers remain (a struct on the heap holding the strong and weak refcounts).

It is fine to use raw pointers if you can assure yourself of the relative lifetimes of the pointer vs. what it points to and prevent dereferencing the pointer while it dangles.

The smart pointers are tools to help with that (under the hood they use raw pointers).

For example unique_ptr sets the lifetime of the pointed to object the same as the pointer with extra functionality for explicit reset or release. The memory footprint for a unique_ptr is the same as a raw pointer unless you use a stateful deleter.

Title: Usage of raw pointers

Body: So from the top-voted answer to this question, it appears that using raw pointers for storage isn't frowned upon so much. However, then what is the point of a std::weak_ptr? I thought that storage was the exact purpose of that class. If so, is there any circumstance in which a raw pointer is considered good, valid code? If there isn't any, what is the point of having them in the language? Is it simply historical artifact?


问:
Is the string "1.2.3f4" a standard format for version numbers?
The game development package Unity uses the following version numbering scheme:

```<code>{major}.{minor}.{patch}{type}{number}
</code>```

With the following known types:

a = alpha

b = beta

f = final

Some examples:

1.2.3a27

1.2.3b4

1.2.3f2

Is this a standard formatting for version numbers?

答:
It appears to be fairly common, yes.  Have a look at the Wikipedia article on software versioning.

Quote below is from that page:

Designating development stage

Some schemes use a zero in the first sequence to designate alpha or beta status for releases that are not stable enough for general or practical deployment and are intended for testing or internal use only.

It can be used in the third position:

```<code>0 for alpha (status)
1 for beta (status)
2 for release candidate
3 for (final) release
</code>```

For instance:

```<code>1.2.0.1 instead of 1.2-a1
1.2.1.2 instead of 1.2-b2 (beta with some bug fixes)
1.2.2.3 instead of 1.2-rc3 (release candidate)
1.2.3.0 instead of 1.2-r (commercial distribution)
1.2.3.5 instead of 1.2-r5 (commercial distribution with many bug fixes)
</code>```

Body:
It appears to be fairly common, yes.  Have a look at the Wikipedia article on software versioning.

Quote below is from that page:

Designating development stage

Some schemes use a zero in the first sequence to designate alpha or beta status for releases that are not stable enough for general or practical deployment and are intended for testing or internal use only.

It can be used in the third position:

0 for alpha (status)
1 for beta (status)
2 for release candidate
3 for (final) release

For instance:

1.2.0.1 instead of 1.2-a1
1.2.1.2 instead of 1.2-b2 (beta with some bug fixes)
1.2.2.3 instead of 1.2-rc3 (release candidate)
1.2.3.0 instead of 1.2-r (commercial distribution)
1.2.3.5 instead of 1.2-r5 (commercial distribution with many bug fixes)


答:
Not as such; There is not one standard versioning scheme. As such, each project tends to choose a versioning scheme that fits their development/release model (and this is perfectly fine, as long as the versioning scheme is known, consistent and respected by developers).

Here are some version examples I've used over the years:

Linux/OSS - style version (start from 0.1 and increment with each small feature; when stable, increment to 1.0)

Windows applications - style version (start from 1.0[.0] with the last numbers representing major version, minor version and build number)

Linux-kernel - style convention (start from 0.1.0, increment version with each stable feature; increment by two for each internal revision, keeping odd build numbers as internal builds, and defining the version using the next odd build number with each public release)

custom (I have various examples on this). The last time I developed a library for a customer, the library was termed 1.0RC - release candidate. With each revision to the library the "RC number" was increased - so I had 1.0RC1, 1.0RC2 and so on.

The library would have become 1.0 when the first customer would have begun using it, then each revision on top of that would have been 1.1RC, 1.1RC2 and so on. I left the project when the library was at 1.0RC3 though.

Title: Is the string "1.2.3f4" a standard format for version numbers?

Body:
The game development package Unity uses the following version numbering scheme:

```<code>{major}.{minor}.{patch}{type}{number}
</code>```

With the following known types:

a = alpha

b = beta

f = final

Some examples:

1.2.3a27

1.2.3b4

1.2.3f2

Is this a standard formatting for version numbers?


问:
Are Data Warehouses bespoke products that are tailored towards the specific needs of one single organisation?
Are Data Warehouses bespoke projects that are developed to meet the needs of a specific organisation or can you buy off the shelf products that would meet the needs of many organisations?

I am talking about a product that will integrate information from many different systems e.g. finance system, sales system, production system etc for management reporting.

Different organisations have different systems that have different database designs.  For example,  organisation A may use finance system A, which has a completely different design to finance system B used by organisation B.

Therefore I believe that Data Warehouse products are bespoke products and it is not possible to develop a product that could be used by many organisations e.g. organisation A and organisation B; that have the same types of systems e.g. Finance, Sales etc.

Am I correct in this analysis?

答:
Data Warehouses are not products, they are data bases with a specific architecture (logically or physically). If you read Gartner Magic Quadrant for Data Warehouse, it  basically lists DBMS vendors.

There are DBMS that's more suitable for data warehouse operation (e.g. aggregation) which are more commonly known as column oriented DBMS. This kind of database is physically different from row oriented database.

Logical difference between data warehouse and plain database is the structure where in data warehouse you will find star or snow flake schema kind of structure to define relationship between Fact tables and their Dimensions.

Data warehouse is a place where you store your data for later analysis as oppose to storing transactional data. You can build it using any DBMS or you can use column oriented DBMS to get more performance.

I think what you want is Business Intelligence suite. They usually have ETL tools that can be used to Extract data from your production database, Transform them (e.g. to create facts and dimensions) and Load them to your data warehouse. Because you mainly work with database, you can use ETL tool with different systems (finance, CRM, etc.) as long as you understand the structure of their databases.

Once you built your data warehouse, you use other tools in the BI suite to do analysis, reporting, data mining, etc. You need to build each of them, but the tools basically only need to be able to get data from data warehouse, they don't need to be able to speak to those other systems (finance, CRM, etc.). You can even use ETL tool from one BI product and build report using another BI product.


问:
Bug root cause analysis
In our group we usually don't ponder too much about what kind of design or implementation decisions caused a bug, we just fix it. Of course if some module constantly produces bugs people start to notice it, and sometimes this leads to major refactoring. But we don't have a process where bugs are routinely analyzed for their root causes.

My question is whether a formal process of bug root cause analysis is common in software development, and if not why not.

答:
The nature of causes is very different and bug cause analysis is often mistaken by analysis of the origin of a bug. For example imagine the wrong adaption of design patterns in contrast to a bad application design or simple programming mistakes.

So I think there will never be a formal process. Maybe the 5-Why-Method will take you to the root cause, but this is more a technique than a formal process.

Title: Bug root cause analysis


问:
What complexity do DI frameworks add?
The currently most upvoted answer to a very recent question states that

DI containers are an "enterprise software" pattern, used when the object graph is very large and complex. I suspect that 95% of applications do not require it.

which is something I strongly disagree with. Maybe I've got the terminology wrong, but for me DI framework means just "something wiring my objects together". Am I missing something?

I'm using Guice even for really tiny projects (like 10 classes) in order to simplify them. Sure, it's a 400 kB JAR file, but this isn't what I'd care about. For a small project I hardly ever need any configuration and the only "overhead" is adding the @Inject annotation.

So I really wonder, what added complexity do DI frameworks cause?

Update addressing the answers

In a 82 class project, I have

32 @Inject annotations

15 @Singleton and 1 @ProvidedBy annotations

4 Providers (all of which I'd need also without DI as they're my factories)

1 Module containing a single line

0 lines XML !!!

That's all. Sure, it's small project, but exactly this was my point. The additional work was a few words rather than lines.

I'm using solely constructor injection in order to get immutable "easygoing" objects. Whenever a new dependency appears, I add a final field, let Lombok's RequiredArgsConstructor take care of the declaration, and let Guice take care of calling it properly.

答:
There are a couple of compromises that are to be made when using DI frameworks as far as I can see.

The most worrying for me is that your application code is usually spread between a main programming language (like Java) and XML/JSON configuration code (it is code). This means that in the case of problems with your application you need to look in two places. Often the configuration code is not easily related to the main application code.

Of course the configuration is also outside the bounds of what the compiler (and often the IDE) can check for you, meaning that it is much easier to make mistakes in this configuration than if you were writing a main class that handled the wiring. In effect this means that wiring issues are pushed from being compile-time issues to being runtime issues.

As well as splitting the application, using DI Frameworks also often mean that you use @Inject or similar within your code, instead of traditional DI techniques (CTOR interface injection in Java/C++, template injection in C++). The downside of this is that you must then use a DI framework with the application. An alternative would be to design your application without expecting a DI framework and then allow the DI framework to re-use the traditional CTOR/setter injection of your classes.

The downside to the traditional injection mechanism comes when a complex and properly encapsulation classes demands a number of other relatively complex injections at CTOR time. This is usually solved by incorporating a Builder, but it can be a pain.

EDIT:

The lads below have mentioned that Guice does not need a separate XML/JSON config. My answer really applies to my own usage of Spring.

Title: What complexity do DI frameworks add?


答:
If you are employing lean software development practices, then examining the root cause of defects should be part of your development process. Defects are one of the wastes - defects that go undetected as development happens cost time, especially as either they go from activity to activity (requirements defects slipping through design or even into integration and acceptance testing activities) or go undetected as the complexity of the system increases (as new features are added). Extending some effort to understand why defects aren't being detected early within the process and making changes to improve defect detection in upstream activities is part of maintaining a lean organization. However, it's also important to note that the cost of performing a root cause analysis is weighed against the benefits - it may not be every defect that is examined, but perhaps as a result of one iteration, there were a large number of defects that can be categorized and analyzed in groups to improve future iterations.

As far as structured methods go, there isn't a single standard approach. It depends on the problem and the team. Some methodologies include Eight Disciplines, DMAIC, Plan-Do-Check-Act, and others. Using these methodologies, you may employ tools such as orthogonal defect classification, fault tree analysis, 5 Whys, Ishikawa (fishbone) diagrams, and nominal group technique, among others (see the Seven Basic Tools of Quality for examples, although these primarily come from manufacturing and industrial processes and may not all translate one-for-one to software development activities), to narrow down the scope of the problem, identify commonalities, and get to the root causes and possible solutions.

If you're looking for a common process that exists across organizations, there really isn't one. However, a lot of the methodologies and tools are common. They are just broken down or used slightly differently across organizations and teams. You ultimately need to determine what works best for you and your team, in terms of defining the problem, determining the best methods to investigate and identify root causes, developing solutions and verifying that they are correct, and ensuring that they are having a positive impact on the process.

Title: Bug root cause analysis

Body:
In our group we usually don't ponder too much about what kind of design or implementation decisions caused a bug, we just fix it. Of course if some module constantly produces bugs people start to notice it, and sometimes this leads to major refactoring. But we don't have a process where bugs are routinely analyzed for their root causes.

My question is whether a formal process of bug root cause analysis is common in software development, and if not why not.


问:
invoking methods within a conditional expression
In an oft-cited (if dated) reference for C# coding standards (pdf; from Lance Hunt), the statement is made,

33. Avoid invoking methods within a conditional expression.

I've not seen this recommendation elsewhere, including in the .NET guidelines (here or here). Unlike the other very reasonable guidelines in Hunt's document, this suggestion seems unintuitive to me. Can someone provide a justification for it?

答:
Well, I did not read Hunt's document in full but it seems that his advice is mainly about readability. A statement like...

```<code>if(myObject1.functionA() && myObject1.functionB())
{
  // do something
}
</code>```

...has a certain risk of being misunderstood, because of short-circuit evaluation, and also because of the if-line length. Instead...

```<code>bool resultOfA = myObject1.functionA();
bool resultOfB = myObject1.functionB();

if(resultOfA && resultOfB)
{
  // do something
}
</code>```

...is easier to read, and will always call both functions(). Of course, if you explicitly want to make use of short-circuit evaluation (maybe because functionB shouldn't be called when functionA returns false), then you may be better off ignoring Hunt's rules (note: he says "avoid", not "don't do this under any circumstances").

Body:
Well, I did not read Hunt's document in full but it seems that his advice is mainly about readability. A statement like...

if(myObject1.functionA() && myObject1.functionB())
{
  // do something
}

...has a certain risk of being misunderstood, because of short-circuit evaluation, and also because of the if-line length. Instead...

bool resultOfA = myObject1.functionA();
bool resultOfB = myObject1.functionB();

if(resultOfA && resultOfB)
{
  // do something
}

...is easier to read, and will always call both functions(). Of course, if you explicitly want to make use of short-circuit evaluation (maybe because functionB shouldn't be called when functionA returns false), then you may be better off ignoring Hunt's rules (note: he says "avoid", not "don't do this under any circumstances").


问:
Adding a minimum rectangle overlap threshold
I have a function that works perfectly for detecting whether or not r1 overlaps with r2:

```<code>boolean overlaps( Rectangle r1, Rectangle r2 ) {
    return r1.x < r2.x + r2.width && r1.x + r1.width > r2.x &&
        r1.y < r2.y + r2.height && r1.y + r1.height > r2.y;
}
</code>```

But now I would like to add a minimum threshold so that it would return true if r1 overlaps r2 by at least a given length.

Here's what I have so far but haven't had any luck:

```<code>boolean overlaps( Rectangle r1, Rectangle r2, float threshold ) {
    return r1.x < r2.x + r2.width && r1.x + r1.width > r2.x + threshold &&
        r1.y < r2.y + r2.height && r1.y + r1.height > r2.y + threshold;
}
</code>```

答:
I find it easier to read the expression if you can use named rectangle edges (Left, Top, etc. There may be slight performance advantages also). With that in mind, this code should work:</p>

```<code>boolean overlaps( Rectangle r1, Rectangle r2, float threshold  ) {
    return r1.Left < (r2.Right - threshold) && r1.Right > (r2.Left + threshold) &&
        r1.Bottom < (r2.Top - threshold) && r1.Top > (r2.Bottom + threshold);
}
</code>```

Body:
I find it easier to read the expression if you can use named rectangle edges (Left, Top, etc. There may be slight performance advantages also). With that in mind, this code should work:

boolean overlaps( Rectangle r1, Rectangle r2, float threshold  ) {
    return r1.Left < (r2.Right - threshold) && r1.Right > (r2.Left + threshold) &&
        r1.Bottom < (r2.Top - threshold) && r1.Top > (r2.Bottom + threshold);
}


问:
static or non-static, that is the question?
For comparisons / evaluations of objects of the same class(and other purposes), is it better to define a static or a non-static (is this called "dynamic" by chance?) function?

Sample code:

```<code>class student
{
    internal decimal medianOfMarks()
    {
        int count = 0;
        decimal sum = 0;
        foreach(float mark in reportCard)
        {
            counter++;
            sum += mark;
        }
        return sum / count;
    }

    **OR**

    internal static decimal medianOfMark(student delinquent)
    {
        [same logic]
    }
}
</code>```

Let's not consider making the function a property, though parameterless, since I'd like an answer applicable to parameterized functions as well.

What are arguments pro / con each approach?

What deciding factors do exist?

I've already thought into this myself, but I don't want to bias the discussion with my opinion.

答:
Subjectively, I like the non-static instance method, it feels more natural.  YMMV.

Objectively, the static form requires one additional parameter that feels redundant,  i.e.

myStudent.medianOfMark()

vs.

student.medianOfMark(myStudent)

I'm not a C# wizard so excuse any wrong syntax details.  Also, as others have commented, there are some other issues with naming, using floats, etc...


问:
Programmer VS Commercial Systems (ERP)
My question here is relative to jobs for programmers.

Why does employer still contract programmers if today we have a lot of good commercial system avaliable on the market?

I want to be very clear at this point, this question is relative only to a system, more specially to ERP systems.  Maybe this question looks a little bit useless, but right now I'm working and this doubt arose to me and my boss.

I have a few answers to my own question, but I really would like to speculate this subject a bit more.

Also I know, every good company needs a customized system, but ... the question is here. :-)

Any answer will make me feel better. Thanks.

答: good answers above; i would add that many of the ERP systems are ancient, not all that well-structured to start with, and have incredible technical debt; this makes them very very expensive and tricky to customize

ContentLicense: CC BY-SA 2.5

Title: Programmer VS Commercial Systems (ERP)


问:
factors that are important for success when letting an agile framework emerge for the whole organisation?
I previously posted a question [link] on programmers.stackexchange.com asking when it makes sense to adopt an existing enterprise scale agile framework and when it makes sense to allow your own enterprise scale agile framework to emerge (e.g. through trial and error).

This question takes the previous question a step further and asks for the factors that are important for success when you have decided to go down the route of letting your enterprise scale agile framework emerge?

--
Downvoters: down voting without adding a comment provides no opportunity for improving the question.  Please let me know why you are down voting so that I can improve the question.

答:
When discussing the question above with practitioners from the scaledagile.com, the following questions were raised:

Are we achieving the business results with our existing processes?

Is the business satisfied with our time to market?

Do we have the
time, resources and skills to document the emerging process?  If we
don’t document the new processes, how will this knowledge be
institutionalized?

How long is the company willing to wait for the
scaling agile practices to emerge?

What is the cost of the delay?

How slow do we want to wait for this process to emerge?

Do we have a
track record of scaling?

Do we truly understand lean and agile
practices? If we don’t, how will we know what and how to improve?

Do
our teams have a track record of continuous improvement.  If yes, why
haven’t the teams already developed these scaling practices already?
If no, what will change to enable this new scaling process to emerge?

Are the teams empowered to make process changes, re-org teams and
create new roles.

Do the teams have a holistic view of the
organization, and have the mindset to look at the big picture and
make process changes that do not cause local optimization at the
expense of the whole.

Will the teams be limited due to their
thinking “We can’t change that, they won’t allow us to”, “we’ve
always done it this way”,  “Management will never agree to allow us
to have face to face release planning meetings”, “That not our job,
we just code, I can’t worry about operations”, “why do we care about
those other groups, we need to get our work done faster”

These questions have helped me to understand the factors that are important to success when deciding to let your own enterprise agile framework emerge (e.g. through trial and error).


答: Some developers argue that any framework you use in your code is a potential problem at a later date, because it typically requires you to write your code in a certain way to interact with it correctly, and this can cause issues at a later date if it turns out that those ways conflict with other design requirements.  An example of this concern is expressed by Bob Martin here.  I don't personally agree, but I can see his point.</p>

Title: What complexity do DI frameworks add?

Body:
The currently most upvoted answer to a very recent question states that

DI containers are an "enterprise software" pattern, used when the object graph is very large and complex. I suspect that 95% of applications do not require it.

which is something I strongly disagree with. Maybe I've got the terminology wrong, but for me DI framework means just "something wiring my objects together". Am I missing something?

I'm using Guice even for really tiny projects (like 10 classes) in order to simplify them. Sure, it's a 400 kB JAR file, but this isn't what I'd care about. For a small project I hardly ever need any configuration and the only "overhead" is adding the @Inject annotation.

So I really wonder, what added complexity do DI frameworks cause?

Update addressing the answers

In a 82 class project, I have

32 @Inject annotations

15 @Singleton and 1 @ProvidedBy annotations

4 Providers (all of which I'd need also without DI as they're my factories)

1 Module containing a single line

0 lines XML !!!

That's all. Sure, it's small project, but exactly this was my point. The additional work was a few words rather than lines.

I'm using solely constructor injection in order to get immutable "easygoing" objects. Whenever a new dependency appears, I add a final field, let Lombok's RequiredArgsConstructor take care of the declaration, and let Guice take care of calling it properly.


问:
How much time should you allow for clock skew?
We are writing a B2B application that uses OAuth 2.0. Before a token expires we want to refresh it since it is faster to refresh a token, than to request a new one. However, we want to build in some resilience in the system to clock skew, so we want to consider a token expired a few seconds/minutes before it would actually expire.

How many seconds/minutes is it reasonable to expect for two servers, both connected to the internet, in different locations, to differ by?

答:
If both servers are synchronized to NIST time or something similarly accurate, the difference should be negligible (subject to transmission delays between the two servers; seconds or less).

If the servers are keeping their own time, and are not properly maintained, the difference can be substantial (minutes, or more).  Kinda depends on whether the servers have decent operating system software that automatically updates itself to Internet time periodically.

The clocks on every device I own that is connected to the Internet are never more than a tiny fraction of a second off. Even if they only sync once a month, they're not going to drift all that much, and if they take their cue from the mains power (which is kept at a very accurate frequency), they may not drift at all. Good watches based on a quartz crystal drift a few seconds each month. The computers that are five minutes off are the ones that are never updated.

ContentLicense: CC BY-SA 4.0


问:
Is my work on a developer test being taken advantage of?
I am looking for a job and have applied to a number of positions. One employer responded. I had a pretty lengthy phone interview (perhaps an hour +) and they then set me up with a developer test. I was told that the test was estimated to take between 6 and 8 hours and that, provided the results met with their approval, I would be paid for my work.

That gave me some pause, but I endeavored. The developer test took place on a VM accessed via RDP. The task was to implement a search page in a web project that requests data from the server, displays it on the screen in a table, has a pretty complicated search filtering scheme (there are about 15 statuses and when sending the search to the server you can search by these statuses) in addition to the string/field search. Additionally, they want SVG icons to change color on certain data values, and some data represented differently than how it's structured in the database.

Loooong story short, this took a heck of a lot longer than 6-8 hours. Much of it was due to the very poor VM that I was running on (Visual Studio 2013 took 10 minutes to load, and another 15 minutes to open the 3 GB ginormous solution).

I was told that after completing the test I should commit my changes to source control...  Hmm, OK. I followed directions. And after committing the changes, I was emailed a response. The SVGs weren't colored right, there was a bug in this edge-case, there was an occasional problem with this other thing that I never experienced, etc. So I am 13-14 hours into this thing now, and I have to do bug fixes. I do them, and the employer comes back with more bug fix requests.

All my work is apparently going into a production application. I noticed a few anomalies in the code where it looked like others had coded all of one functionality but hadn't touched anything else.

Am I just being used for cheap labor? Even if they pay me the promised 50 dollars an hour for 6 hours, I have committed about 18 hours to this thing now. If I bug fix all of the stuff they keep coming up with, I will have worked at least 16 hours for free.

I have taken a number of developer tests, but I have never taken one during which I worked on code destined for production. I have never taken a test where I implemented a feature that was in the pipeline for development, and I have never taken one that took 4 rounds and a total of 20+ hours. I get the impression they are using their developer test to field some of the functionality on the cheap.

Do I have the wrong impression? And is this testing protocol appropriate?

答:
I'm a great believer in code tests for developers interviewing for a job.  However, this sounds like the code test from hell...  Code tests should never involve production code.  They should be simple and should state that none of the work done will be used by the company.

Clearly, the work you did was on production code.  You should be paid for all of your time - at a minimum.  Try talking to an attorney and see if he thinks it would be worthwhile to sue them.  Many attorneys offer free initial consultations.  If fraud was involved, and in this case it looks that way, you would be entitled to quadruple money damages, and you might also be able to get some nice punitive damages on top of that.

By suing them and winning, you will make some headlines and discourage this practice by others in the future - which will be beneficial to all software developers looking for a new position.


答:
You should also consider function calls that have side effects (e.g. change some global variables). This can be a more important issue than just readability.

```<code>if (funcA() && funcB()) ...
</code>```

It might be intended that funcB only gets called when funcA succeeds, but you also might do a mistake here. If both functions have side effects and both are needed to be executed, then the code above is logically flawed. This may happen because the programmer was too ambitious with keeping his code tight, but it could also be that it was correct before, but due to some changes somewhere else the assumptions taken are no longer valid.

Therefore it's never a good idea to call functions with side effects inside a boolean expression.

Body:
In an oft-cited (if dated) reference for C# coding standards (pdf; from Lance Hunt), the statement is made,

33. Avoid invoking methods within a conditional expression.

I've not seen this recommendation elsewhere, including in the .NET guidelines (here or here). Unlike the other very reasonable guidelines in Hunt's document, this suggestion seems unintuitive to me. Can someone provide a justification for it?

Body:
You should also consider function calls that have side effects (e.g. change some global variables). This can be a more important issue than just readability.

if (funcA() && funcB()) ...

It might be intended that funcB only gets called when funcA succeeds, but you also might do a mistake here. If both functions have side effects and both are needed to be executed, then the code above is logically flawed. This may happen because the programmer was too ambitious with keeping his code tight, but it could also be that it was correct before, but due to some changes somewhere else the assumptions taken are no longer valid.

Therefore it's never a good idea to call functions with side effects inside a boolean expression.


问:
Do you have your own 'misc utils' library? What part are you most proud of?
I know that many of us maintain our own little personal library with tools and utilities that we use often.

I've had mine since I was 16 years old so it has grown to quite a considerable size. Some of the stuff I've written has since been added to the framework. I wrote my own little implementation of expression trees for use with genetic algorithms long before LINQ, which I quite like and was proud of at the time - of course its pretty useless now. But recently I have been going through it and upgrading to .NET 4.0 and re-kindled an interest.

So I'm curious as to what you use your library for. Maybe we could get some cool ideas going for useful little snippets and share them amongst ourselves.

So my questions are:

Do you have a miscellaneous utility library?

Which part are you most proud of and why?

Give an example of code if you like :-)

答:
I can't write desktop UIs now without dynamic dialogs, based on differential execution.
It's a hack I stumbled on around 1985, and I've re-implemented it in various languages more times than I can remember.</p>


问:
About grammar, Chomsky hierarchy and obj file format
Considering the Wavefront obj file format where this syntax fits in the Chomsky hierarchy and why ? I'm also not sure if PEG grammars are being considered in the kind of classification made by Chomsky and if an obj is a real example of a PEG grammar .

to formalize this: what kind of grammar and parser I need in order to read an obj file ?

答:
Depends on how you look at it.

The syntax (line per line first few chars show what the line is) is simple and a regular language.

The kicker is how to verify the f lines, however when you are parsing you have a turing machine at your disposal and you should just focus on the regular part and step in with the higher level where needed.


答:
You need to do this based on what you actually see in your system. The two basic approaches are to do it once or to make your code adjust on the fly. The first is obviously a lot easier to do but somewhat less resilient.

Doing it once means logging the time difference for each pair of servers for a while and seeing what you get. This might take a while, since you want to see whether they're re-synchronising to NIST or similar at intervals. But even very early on you should get an idea of whether the time differences are consistent or not. Then hard-code in some reasonable value. The biggest jump is likely to be the correction one, but you may never see that actually happen so you'll be guessing "our site is quiet overnight but the skip sees to happen between 2am and 6am AEST" is likely).

The more resilient but more code version is to do the above but map your actual offset to the most recently observed values. If your timeout is a couple of hours and you see the other system has been drifting a second a month just build that in to your pre-expiry. It only gets complex when you're trying to guess the point at which the other system will jump a couple of seconds back due to a monthly clock correction.

I think the latter is overkill unless you're looking at jumps within a factor of 10 of the total expiry time. At that point you're going to want to throw away 20% of the total time, which is a 25% increase in OAuth traffic. So it might be worthwhile to write more code in an effort to reduce it. But even then, that might not be the biggest bandwidth saving you can get for your programming time.

Title: How much time should you allow for clock skew?

Body:
We are writing a B2B application that uses OAuth 2.0. Before a token expires we want to refresh it since it is faster to refresh a token, than to request a new one. However, we want to build in some resilience in the system to clock skew, so we want to consider a token expired a few seconds/minutes before it would actually expire.

How many seconds/minutes is it reasonable to expect for two servers, both connected to the internet, in different locations, to differ by?


答:
This is how I would probably solve it, if possible:

Get the time from the target server (that will validate the token), and compute the difference with the time from the server that issued the token. Set a timer to get the token before it expires according to the time on the target server.

Do add a little bit of margin for round trip calls to get a new token as well as for the roundtrip call to check the time.

Add some margins for retries in case the server is down. For example, if the token is to be refreshed before 8:22:20, you may want to start at 8.21:20 with the assumption that you can try thrice (in case of network/connectivity failures) with 15 sec interval and still have 15 sec for the roundtrip calls margin. You can increase the margins if your token life is in hours instead of minutes.

When the code gets a token, and figures out that it will need to be refreshed too quickly (say below a certain threshold, such as < 50% of token lifetime or 5 mins), it should raise an alert because the servers are getting really out of sync.

In the computation, the code should normalize all time to the same time zone, such as UTC, or the code will go all whacky.

On some platforms, getting the time of a target server is quite trivial. On others, you may have to expose web methods to do this, but hopefully, that should be fine.

Despite having the logic to get refresh token, I think your code should get an access token if the window to get refresh token has passed, but raise an alert so the code can be fixed. If the operation is not time critical, you might want it to fail gracefully if it's not been able to get a refresh token, but it should still raise an alert to fix the code.


答:
First, it is clear from the context that by conditional expression Hunt means the boolean expression in a conditional statement. This is a section about flow control, and not about the use of boolean expressions for other purposes, or about (what I would call) conditional expressions based on the ternary '?:' operator.

I believe the underlying intent here is that the parts of a conditional expression used for flow control should avoid misunderstandings that might arise from shortcircuit evaluation or from side-effects. I can see no reason for avoiding calling method functions to obtain values used in a conditional expression (provided there are no side-effects), and I can see no problem in depending on shortcircuit evaluation provided the relationships between the parts of the expression are clearly visible. It's the risk of hidden connections and hidden consequences that should be avoided. So:

```<code>if (x.Contains(a) && x.Median() > b) {} // ok
if (x.Insert(a) && x.Median() > b) {} // NOT ok
</code>```

There is a further consideration. The calling of a method may involve a performance penalty, so if Median() is slow to compute:

```<code>if (x.Median() >= a && x.Median() <= b) {} // slower
var median = x.Median();
if (median >= a && median <= b) {} // faster
</code>```

Having said all that, I think Hunt does us a disservice by failing to explain what he means. Hopefully a future release will address that shortcoming.

Title: invoking methods within a conditional expression

Body:
First, it is clear from the context that by conditional expression Hunt means the boolean expression in a conditional statement. This is a section about flow control, and not about the use of boolean expressions for other purposes, or about (what I would call) conditional expressions based on the ternary '?:' operator.

I believe the underlying intent here is that the parts of a conditional expression used for flow control should avoid misunderstandings that might arise from shortcircuit evaluation or from side-effects. I can see no reason for avoiding calling method functions to obtain values used in a conditional expression (provided there are no side-effects), and I can see no problem in depending on shortcircuit evaluation provided the relationships between the parts of the expression are clearly visible. It's the risk of hidden connections and hidden consequences that should be avoided. So:

if (x.Contains(a) && x.Median() > b) {} // ok
if (x.Insert(a) && x.Median() > b) {} // NOT ok

There is a further consideration. The calling of a method may involve a performance penalty, so if Median() is slow to compute:

if (x.Median() >= a && x.Median() <= b) {} // slower
var median = x.Median();
if (median >= a && median <= b) {} // faster

Having said all that, I think Hunt does us a disservice by failing to explain what he means. Hopefully a future release will address that shortcoming.


问:
Why did Shannon's outguessing machine beat Hagelbarger's?
I'm reading "Rock Breaks Scissors", which describes two "outguessing machines" built at Bell Labs that try to exploit human non-randomness in the game of matching pennies. There was an outguessing machine built by the famous Claude Shannon, and one built by Dave Hagelbarger.

The machines worked like this (quoted from the book):

Suppose you win twice in a row with the same choice. What would you
  pick next? You could stick with the choice that's been winning - or
  you could switch, perhaps on the grounds that three times in a row
  wouldn't be "random."

Each time a particular situation occurred, [Shannon's] machine
  archived what the player had decided. Every decision was encoded as a
  1 or 0 and slotted into one of the machine's 16 precious bits of
  memory. For each of the eight given situations, Shannon's machine
  cataloged the last two decisions only. That filled the machine's 16
  bits.

When the machine needed to predict, it looked at what the player had
  done the last two times that the same situation had occurred. Whenever
  the player's response had been identical both times, the machine
  predicted that the player would do the same thing once again.
  Otherwise, it guessed randomly from its [random number generator].

The main difference between Shannon's machine and Hagelbarger's was
  that Shannon's was simpler. Hagelbarger's machine kept track of a
  percentage of outcomes for each of the eight situations. The higher
  the percentage, the more likely Hagelbarger's machine was to predict a
  repeat of the past. This may sound more reasonable and nuanced than
  Shannon's all-or-nothing approach, but in practice, Shannon's device
  was the better predictor.

Shannon's machine beat humans at a higher rate than Hagelbarger's, and also beat Hagelbarger's machine when they played each other. I don't understand why Shannon's simpler approach was significantly better than Hagelbarger's percentage-based approach.

答:
Why did algorithm S do better at beating humans than algorithm H? Because S was a better model of human behaviour. The obvious difference is that S (Shannon) had a short memory and H (Hagelbarger) had one that was longer. We can hypothesise that humans play this game with more short term than long term consistency. Obviously to check our hypothesis will require more experiments.

Why did algorithm S beat algorithm H? Because it could and it did.

For a game such as this which is fair and for which there is no simple Nash equilibrium, then any algorithm with deterministic features (such as H) can be beaten by another algorithm designed specifically for that purpose. [Shannon acknowledges as much in that reference.] I surmise that S by chance was such an algorithm.

If there exists a full specification of each algorithm it would now be trivial to code the simulation and run a few billion trials to see if the result was inherent in the algorithm, or occurred by chance.


问:
What is the one bit of computer science theory I should know?
Speaking as someone with an Electronic Engineering rather than Computer Science degree, what is the one bit of computer science I should know to make me a better real world programmer?

(By real world I mean something I'm going to use and benefit from in my day to day job as a programmer - for instance I'd suggest understanding database normalisation is of more practical use than understanding a quick sort for which there are lots of libraries).

答:
Well, I could give you a dull answer: automata theory, and information theory.

Or I could tell you what I learned from a hardware consultant a long time ago:

"Good Enough" isn't good enough.


问:
What prevents a race condition on a lock?
I understand the basics of what data races are, and how locks/mutexes/semaphores  help prevent them. But what happens if you have a "race condition" on the lock itself? For example, two different threads, perhaps in the same application, but running on different processors, try to acquire a lock at the exact same time.

What happens then? What is done to prevent that? Is it impossible, or just plain unlikely? Or is it a real race condition waiting to happen?

答:
Is it impossible, or just plain unlikely?

Impossible. It can be implemented in different ways, e.g., via the Compare-and-swap where the hardware guarantees sequential execution. It can get a bit complicated in presence of multiple cores or even multiple sockets and needs a complicated protocol between the cores, but this is all taken care of.


答:
Study the concept of atomic "Test and Set" operations.

Essentially the operation cannot be divided - it is not possible for two things to do it at exactly the same time. It will check a value, set it if it is clear, and return the value as it was when test.  In a lock operation, the result will always be "lock == TRUE" after a test-and-set, the only difference is was it set or not at the start.

At the micro code level in a single core processor, this is one indivisible instruction, and is easy to implement. With multiple and multicore processors, it becomes harder, but as programmers we have no need to worry about it, as it is designed to work by the really smart guys who do the silicon.  Essentially they do the same thing - make an atomic instruction that a fancy version of test-and-set

Title: What prevents a race condition on a lock?

Body:
I understand the basics of what data races are, and how locks/mutexes/semaphores  help prevent them. But what happens if you have a "race condition" on the lock itself? For example, two different threads, perhaps in the same application, but running on different processors, try to acquire a lock at the exact same time.

What happens then? What is done to prevent that? Is it impossible, or just plain unlikely? Or is it a real race condition waiting to happen?


问:
What's the most flexible way to ship changeable resources such as icons for an application?
We're currently upgrading some components of our application to new technologies such as C# using WPF and MVVM. Since we try to avoid past mistakes that have been made in our now legacy applications, a question came up in our team how we should ship external resources that are likely to change, such as icons or images. In our legacy applications they were basically embedded in each applications, which required a full recompile of the applications just to change some icon. We don't want to just dump the raw files into a folder either, since some of them might be licensed and shouldn't be directly accessible to the customer.

We thought that we split all our resources into an external file (such as a DLL), which all our applications can access. So every time some resource is changed, we just have to ship a new version of our resource library. However there are some cases, where a general storage is not desirable, for example if just one specific icon in a single application should change. If we'd just replace that resource, it would likely change in all applications using that resource.

How do "big" applications handle this or is there a best practice in how to do this?

答:
You can consider putting these resources up on a website (or network location), and have your application download and cache on the local device. Every time a connection is available, the application would check if the resource has been updated, and if so, download it again. This will allow single resource to be changed without affecting others.

This even allows some advanced cases. For example, if you have two places in code that reference the same resource (such as an image), this allows you to embed two different URLs in those two places. However, on the web server, you could still have the same image served without even duplicating it (e.g. links, redirects, etc.). If at a later stage, the image needed to be changed in one place in the app, you only need to update the server without redeploying the client.

Some caveats include ensuring that you have SSL/TLS connection so it's not easy for some rogue site to act as your server and throw in malicious code/content on the device.

As you add more apps, you can reuse the same, and if you were eventually writing a Web Application, then this is how you would be serving resources anyway.


问:
Expected error handling
Let's say I have a social media website. On this website, users can upload several pieces of information about themselves, including their phone number. To implement this, I have a class called PhoneNumber that represents the users phone number. But phone numbers are optional. I have this PhoneNumber class which is supposed to guarantee access to a users phone number, but it can't. How do I handle this?

My current approach is to, whenever there's a problem, assign a value to an error variable inside PhoneNumber that represents the problem in question (this could be an exception, a string, or an error code, it's irrelevant for this question). I also added a method to PhoneNumber called isPhoneNumberAvailable() that should be called before any of the accessors are used. If one of the accessors is called and the user hasn't added their phone number, I throw an IllegalStateException. But this doesn't seem like a good solution. I'm not sure why, I'm too new at this to explain it, but it seems like this could cause me some problems down the road.

Note that this question is language agnostic, the existence of an IllegalStateException in Java is purely coincidental.

EDIT: The solution is improving the model. I have guaranteed access to something I can't guarantee access to, which is bad design. My other problem was with the use of an error variable in class scope but that's beyond the scope of this question. See my follow up question here.

答:
I think what you're asking is where to handle possible errors, right? Among others you have the ways you described:

The client asks if phone numbers are available. This has the benefit of a clean and exception-free API. But what happens if the client never asked before accessing the numbers?

Your getter (within your PhobeNumber) throws an exception of nothing is available. The advantage here is that clients don't need two remember two API calls.

Both are valid ways to handle this and which you choose depends highly on your application and what you think should happen if no phone numbers are available. I, personally, prefer exceptions as you can't forget them but that is even a matter of style.

Is that what you were looking for?

Title: Expected error handling


问:
Are error variables an anti-pattern or good design?
In order to handle several possible errors that shouldn't halt execution, I have an error variable that clients can check and use to throw exceptions. Is this an Anti-Pattern? Is there a better way to handle this? For an example of this in action you can see PHP's mysqli API. Assume that visibility problems (accessors, public and private scope, is the variable in a class or global?) are handled correctly.

答:
Unless there is something very specific, I think having an error variable for validation is a bad idea.
The purpose seems to be about saving the time spent on validation (you can just return the variable value)

But then if you change anything, you have to recompute that value anyway.
I can't say more about halting and Exception throwing though.

EDIT: I didn't realize this is a question of software paradigm instead of a specific case.

Let me further clarify my points in a particular case of mine in which my answer would make sense

I have a collections of entity objects

I have procedural style web services which work with these entity objects

There are two kinds of errors:

The errors when processing happens in the service layer

The errors because there are inconsistencies in the entity objects

In the service layer, there is no choice but using Result object as wrapper which is the equivalence of error variable. Simulating an exception via service call on protocol like http is possible, but is definitely not a good thing to do. I am not talking about this kind of error and didn't think this is the kind of error being asked in this question.

I was thinking about the second kind of error. And my answer is about this second kind of errors. In the entity objects, there are choices for us, some of them are

using a validation variable

throw an exception immediately when a field is set incorrectly from the setter

Using validation variable is the same as having a single validation method for each entity object. In particular, the user can set the value in a way that keep the setter as purely setter, no side effect (this is often a good practice) or one can incorporate validation into each setter and then save the result into a validation variable. The advantage of this would be to save time, the validation result is cached into the validation variable so that when the user calls validation() multiple time, there is no need to do multiple validation.

The best thing to do in this case is using a single validation method without even using any validation to cache validation error. This helps keep the setter as just setter.


答:
SmartFormat

My favorite utility is one I wrote - a simple string builder/formatter that makes it really easy to turn data into strings with correct grammar.

For example, most programmers build text from a template:
"There are {0} items remaining"
but this leads to grammatical errors: "There are 1 items remaining".

So, SmartFormat lets you write: "There {0:is|are} {0} item{0:|s} remaining".

You just replace String.Format(...) with Smart.Format(...) and that's it!

The SmartFormat code is open source: http://github.com/scottrippey/SmartFormat/wiki

Title: Do you have your own 'misc utils' library? What part are you most proud of?

Body:
I know that many of us maintain our own little personal library with tools and utilities that we use often.

I've had mine since I was 16 years old so it has grown to quite a considerable size. Some of the stuff I've written has since been added to the framework. I wrote my own little implementation of expression trees for use with genetic algorithms long before LINQ, which I quite like and was proud of at the time - of course its pretty useless now. But recently I have been going through it and upgrading to .NET 4.0 and re-kindled an interest.

So I'm curious as to what you use your library for. Maybe we could get some cool ideas going for useful little snippets and share them amongst ourselves.

So my questions are:

Do you have a miscellaneous utility library?

Which part are you most proud of and why?

Give an example of code if you like :-)


答:
I think it's awful.  I'm currently refactoring a Java app that uses return values instead of exceptions.  Although you may not at all be working with Java, I think this applies nonetheless.

You end up with code like this:

```<code>String result = x.doActionA();
if (result != null) {
  throw new Exception(result);
}
result = x.doActionB();
if (result != null) {
  throw new Exception(result);
}
</code>```

Or this:

```<code>if (!x.doActionA()) {
  throw new Exception(x.getError());
}
if (!x.doActionB()) {
  throw new Exception(x.getError());
}
</code>```

I'd much rather have the actions throw exceptions themselves, so you end up with something like:

```<code>x.doActionA();
x.doActionB();
</code>```

You can wrap that in a try-catch, and get the message from the exception, or you can choose to ignore the exception, for example when you're deleting something that may already be gone.  It also preserves your stack trace, if you have one.  The methods themselves become easier, too.  Instead of handling the exceptions themselves, they just throw what went wrong.

Current (horrible) code:

```<code>private String doActionA() {
  try {
    someOperationThatCanGoWrong1();
    someOperationThatCanGoWrong2();
    someOperationThatCanGoWrong3();
    return null;
  } catch(Exception e) {
    return "Something went wrong!";
  }
}
</code>```

New and improved:

```<code>private void doActionA() throws Exception {
  someOperationThatCanGoWrong1();
  someOperationThatCanGoWrong2();
  someOperationThatCanGoWrong3();
}
</code>```

Strack trace is preserved and the message is available in the exception, rather than the useless "Something went wrong!".

You can, of course, supply better error messages, and you should.  But this post is here because the current code I'm working on is a pain, and you shouldn't do the same.

Title: Are error variables an anti-pattern or good design?

Body: In order to handle several possible errors that shouldn't halt execution, I have an error variable that clients can check and use to throw exceptions. Is this an Anti-Pattern? Is there a better way to handle this? For an example of this in action you can see PHP's mysqli API. Assume that visibility problems (accessors, public and private scope, is the variable in a class or global?) are handled correctly.

Body:
I think it's awful.  I'm currently refactoring a Java app that uses return values instead of exceptions.  Although you may not at all be working with Java, I think this applies nonetheless.

You end up with code like this:

String result = x.doActionA();
if (result != null) {
  throw new Exception(result);
}
result = x.doActionB();
if (result != null) {
  throw new Exception(result);
}

Or this:

if (!x.doActionA()) {
  throw new Exception(x.getError());
}
if (!x.doActionB()) {
  throw new Exception(x.getError());
}

I'd much rather have the actions throw exceptions themselves, so you end up with something like:

x.doActionA();
x.doActionB();

You can wrap that in a try-catch, and get the message from the exception, or you can choose to ignore the exception, for example when you're deleting something that may already be gone.  It also preserves your stack trace, if you have one.  The methods themselves become easier, too.  Instead of handling the exceptions themselves, they just throw what went wrong.

Current (horrible) code:

private String doActionA() {
  try {
    someOperationThatCanGoWrong1();
    someOperationThatCanGoWrong2();
    someOperationThatCanGoWrong3();
    return null;
  } catch(Exception e) {
    return "Something went wrong!";
  }
}

New and improved:

private void doActionA() throws Exception {
  someOperationThatCanGoWrong1();
  someOperationThatCanGoWrong2();
  someOperationThatCanGoWrong3();
}

Strack trace is preserved and the message is available in the exception, rather than the useless "Something went wrong!".

You can, of course, supply better error messages, and you should.  But this post is here because the current code I'm working on is a pain, and you shouldn't do the same.


答:
If a language inherently supports exceptions, then it is preferred to throw exceptions and the clients can catch the exception if they do not want it to result in a failure. In fact, the clients of your code expect exceptions and will run into many bugs because they will not be checking the return values.

There are quite a few advantages to using exceptions if you have a choice.

Messages

Exceptions contain user readable error messages which can be used by the developers for debugging or even displayed to the users if so desired. If the consuming code cannot handle the exception, it can always log it so the developers can go through the logs without having to stop at every other trace to figure out what was the return value and map it in a table to figure out what was the actual exception.

With return values, there is no additional information can be easily provided. Some languages will support making method calls to get the last error message, so this concern is allayed a bit, but that requires the caller to make extra calls and sometimes will require access to a 'special object' that carries this information.

In the case of exception messages, I provide as much context as possible, such as:

A policy of name "foo" could not be retrieved for user "bar", which was referenced in user's profile.

Compare this to a return code -85. Which one would you prefer?

Call stacks

Exceptions usually also have detailed call stacks which help debug code faster and quicker, and can also be logged by the calling code if so desired. This allows the developers to pinpoint the issue usually to the exact line, and thus is very powerful. Once again, compare this to a log file with return values (such as a -85, 101, 0, etc.), which one would you prefer?

Fail fast biased approach

If a method is called somewhere that fails, it will throw an exception. The calling code has to either suppress the exception explicitly or it will fail. I have found this to be actually amazing because during development and testing (and even in production) the code fails quickly, forcing the developers to fix it. In the case of return values, if a check for a return value is missed, the error is silently ignored and the bug surfaces somewhere unexpected, usually with a much higher cost to debug and fix.

Wrapping and Unwrapping Exceptions

Exceptions can be wrapped inside other exceptions and then unwrapped if needed. For example, your code might throw ArgumentNullException which the calling code might wrap inside a UnableToRetrievePolicyException because that operation had failed in the calling code. While the user might be shown a message similar to the example I provided above, some diagnostic code might unwrap the exception and find that an ArgumentNullException had caused the issue, which means it is a coding error in your consumer's code. This could then fire an alert so the developer can fix the code. Such advanced scenarios are not easy to implement with the return values.

Simplicity of code

This one is a bit harder to explain, but I learnt through this coding both with return values as well as exceptions. The code that was written using return values would usually make a call and then have a series of checks on what the return value was. In some cases, it would make call to another method, and now will have another series of checks for the return values from that method. With exceptions, the exception handling is far simpler in most if not all cases. You have a try/catch/finally blocks, with the runtime trying its best to execute the code in the finally blocks for clean-up. Even nested try/catch/finally blocks are relatively easier to follow through and maintain than nested if/else and associated return values from multiple methods.

Conclusion

If the platform you are using supports exceptions (esp. such as Java or .NET), then you should definitely assume that there is no other way except to throw exceptions because these platforms have guidelines to throw exceptions, and your clients are going to expect so. If I were using your library, I will not bother to check the return values because I expect exceptions to be thrown, that's how the world in these platforms is.

However, if it were C++, then it would be a bit more challenging to determine because a large codebase already exists with return codes, and a large number of developers are tuned to return values as opposed to exceptions (e.g. Windows is rife with HRESULTs). Furthermore, in many applications, it can be a performance issue too (or at least perceived to be).


答:
On Apple's OS X, applications are shipped in a special directory where a Resources subdirectory stores all app resources, such as icons, graphic art, localization data, custom libraries, scripts...

Nothing is crypted, though.

Title: What's the most flexible way to ship changeable resources such as icons for an application?

Body:
We're currently upgrading some components of our application to new technologies such as C# using WPF and MVVM. Since we try to avoid past mistakes that have been made in our now legacy applications, a question came up in our team how we should ship external resources that are likely to change, such as icons or images. In our legacy applications they were basically embedded in each applications, which required a full recompile of the applications just to change some icon. We don't want to just dump the raw files into a folder either, since some of them might be licensed and shouldn't be directly accessible to the customer.

We thought that we split all our resources into an external file (such as a DLL), which all our applications can access. So every time some resource is changed, we just have to ship a new version of our resource library. However there are some cases, where a general storage is not desirable, for example if just one specific icon in a single application should change. If we'd just replace that resource, it would likely change in all applications using that resource.

How do "big" applications handle this or is there a best practice in how to do this?


问:
What is the argument for singular nouns in RESTful API resource naming?
I understand that when naming RESTful URI's it is commonly accepted to use plurals to represent collections of resources. I am curious as to the argument for using singular nouns instead.</p>

答:
Some resources contain only a single item. Good examples would be everything for which you don't need an ID to find out what data to render. Very common for example would be the Login resource. You have (from the users and browsers view) only a single login. You can create it, you can destroy it but you won't have an index action with several Logins to choose from.

Similar examples would be some mostly static pages like company information, imprints, contact forms and similar things that only display a single item or only allow a single create action.

It could be a matter of discussion if using singular nouns really adds much to readability of the code.


答:
Error variables are a relic from languages like C, where exceptions were not available. Today, you should avoid them except when you are writing a library which is potentially used from a C program (or a similar language without exception handling).

Of course, if you have a type of error which could be better classified as "warning" (= your library can deliver a valid result and the caller can ignore the warning if he thinks it is not important), then a status indicator in form of a variable can make sense even in languages with exceptions. But beware. Callers of the library tend to ignore such warnings even if they should not. So think twice before introducing such a construct into your lib.


答:
I would just have the PhoneNumber property on the User object set to null. That way you can test if PhoneNumber == null, then the user can't call the phone number, so your UI doesn't even need to show the option (or show that there's no phone number).

Once phone number is provided, initialize an instance of the PhoneNumber class with the user's phone number and assign it the PhoneNumber property on the User object. The user's phone number can be validated the first time it is provided, and then it would be guaranteed to exist and be called. If the validation fails on the first attempt, it throws an exception during instantiation, and thus the PhoneNumber object is never created.

If at a later stage, you decided to have multiple phone numbers, either you can add more properties to the User (i.e. User.HomePhone, User.MobilePhone), or have a list of PhoneNumbers that is instantiated to empty list. As phone numbers are added, a new PhoneNumber object is instantiated and added to the list. Both these approaches will also guarantee that you never have a PhoneNumber unless it holds a valid number.

In fact, I have done something similar for a PhoneNumber class for multi-factor authentication and this approach worked fine for me.

Title: Expected error handling

Body:
Let's say I have a social media website. On this website, users can upload several pieces of information about themselves, including their phone number. To implement this, I have a class called PhoneNumber that represents the users phone number. But phone numbers are optional. I have this PhoneNumber class which is supposed to guarantee access to a users phone number, but it can't. How do I handle this?

My current approach is to, whenever there's a problem, assign a value to an error variable inside PhoneNumber that represents the problem in question (this could be an exception, a string, or an error code, it's irrelevant for this question). I also added a method to PhoneNumber called isPhoneNumberAvailable() that should be called before any of the accessors are used. If one of the accessors is called and the user hasn't added their phone number, I throw an IllegalStateException. But this doesn't seem like a good solution. I'm not sure why, I'm too new at this to explain it, but it seems like this could cause me some problems down the road.

Note that this question is language agnostic, the existence of an IllegalStateException in Java is purely coincidental.

EDIT: The solution is improving the model. I have guaranteed access to something I can't guarantee access to, which is bad design. My other problem was with the use of an error variable in class scope but that's beyond the scope of this question. See my follow up question here.


问:
Sortable listview using SQLite
I'm implementing a sortable listview using bauerca's library here. This works, but now I need to define some things where I need some help. This is the functionality of my app_

I can create up to 5 names. These names are saved in a SQLite database. Then, in other activity, these names are loaded from the database and shown to select which ones I'm going to use.

With 5 names, there are several combinations I can use, but the basic porpouse of this app is that when I select some names, these are shown in a sortable listview where I can sort them. After sorting them, they should be saved in another database to remember the position of each one.

For this, the second database has these columns: NAME, GROUP, ORDER.

My approach is this: if I select for example NAME1 and NAME2, this would be GROUP2_1. If I select NAME1 and NAME3 this would be GROUP2_2... and this with all the posible combinations. Then, in the ORDER column, the position of each name in the listview is saved.

But seems that this approach with the GROUP column doesn't work... it saves the position of each name, but regardless of the group to which it belongs. So for example, if I have these names:

```<code>MARK
PAUL
JERRY
</code>```

If I select MARK and JERRY, the listview at first time would show them that way:

```<code>MARK
JERRY
</code>```

But now I sort them:

```<code>JERRY
MARK
</code>```

So these combination belongs to GROUP2_1 and JERRY has 1 value in the ORDER column and MARK the 2.

If now I go back and I select this other combination:

```<code>MARK
PAUL
JERRY
</code>```

This should be GROUP3_1, and now I sort them this way:

```<code>MARK
JERRY
PAUL
</code>```

So now MARK has ORDER value 1, JERRY 2 and PAUL 3.

Now if I go back and load again the first combination, it will load the names with the last asigned ORDER value so instead of loading in this order:

```<code>JERRY
MARK
</code>```

It will load them using the values of the last combinations:

```<code>MARK
JERRY
</code>```

Sorry for such a long explanation, but I dind't know other best way to explain my issue. In resume, the problem is that the ORDER value is asigned to each name, regardless of the GROUP, so this is not a valid approach for what I need to get.

Update -- key definition

Thats my current table:

```<code>db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
            TravelOrder._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
            TravelOrder.NAME + " TEXT NOT NULL " +
            ");");
</code>```

答:
From what you have given here, I would make a few addition assumptions and then propose a solution.

You have a set of entities which you can uniquely identify

You care about the order (in the list) when you have lists of these entities

An entity can be in multiple lists, lists are NOT all disjoined

Solution: Don't use generated ID in the second table. Instead create a table called group table which actually has generated ID.
You will then have a relationship table between the group table and the initial entity table (name table): in this relationship table, use the combination of groupID and name as the key, also add in an order column (which you, and not the DB, will have to manage)

[EDIT:]
Specifically speaking:

Table 1 (String name as key) to store the names.

Table 2 (int id as key) to store the id of the group/list

Table 3 relationship table between table 1 and table 2. This one will have the pair (group_id, name) as key and a column for order, you manage this value to keep an order of each name in the group.

If you know how many groups you will have (or how many groups will be added in a time range: hour, day, week, month, year), then I would propose another solution.

At the start of each interval, create the number of tables that you wanted. Each of the table will keep the list of names you want to have. Now you will use auto-generated Id whenever you add names into the table. There is a catch for this, but I am not sure if your usage case will run into it or not.

Title: Sortable listview using SQLite


问:
Technical example of modeling a domain with OOD?
Considering favoring composition over inheritance and looking at various design patterns there are multiple approaches to modeling a domain.

Say you have some Entities which are very similar in some respects, yet differ widely when it comes to technical implementations. To try portray the scenario here is the classic car example.

```<code>(Vehicles)
Car
Truck
Van
</code>```

From a user perspective, they are all pretty much the same (all vehicles). From a DDD perspective, car, truck, van all share certain common state (number of tires, engine, ...) and certain behaviors (steering, changing speed, ...). However, they also have various state and behavior that is unique such as the Truck's bed, the van's internal storage, or the cars 5 seats. As time progresses there will be a fair amount of change. Validation would be different for certain things, and similar for others. Change speed, steer, etc. are similar, yet pull trailer is optional and even that differs between e.g. the Van and Truck.

How would you design this to cope with change, yet remain DRY and adhering to the DDD mindset? Please explain how you would go about it (pseudo code?) and mention any design patterns or strategies you would try implement to model this (simple, yet dynamic) domain and which OO principles are being applied etc.

答: Looks like the purpose of the model is missing from the picture. DDD is not about modelling reality: it's about discovering the model which is the best fit for the specific purpose. Design patterns will eventually follow.</p>


问:
What happens if you're unable to solve a problem?
I'm a year away from graduating from university, and I'm really looking forward to solving practical problems. Especially non-trivial ones which require a bit of research and a lot of thinking.

But at the same time, that is also my greatest fear - being faced with a problem that I'm unable to solve, no matter how hard I try. And with pressure to deliver code on impending deadlines just around the corner, it does look a bit scary when viewing it from the safe playgrounds on uni (where the worst thing that can happen is that you have to redo a course or exam).

So for those who have been in industry for any longer length of time, what would happen if you were told to solve a problem that you couldn't? Has it happened, and if so, what did happen? Did they just drop it and said "Oh well, guess we can make do with something else"? Were there consequences? Were you reprimanded, or even fired?

答:
There are lots of different types of problems that you will be stumped on, and many have different ways to handle them.

One type of problem is implementing something you haven't seen before like a strange sound API or something. In this case I'd ask on SO, seriously.

Another is a very large problem to solve.  This type of problem can be approached iteratively.  They tell you "Implement Humongous".  You look it over and write as many steps as you can figure out.  Then you break down the complicated steps into smaller steps.  As you are forced to think about smaller steps they become clearer.  If you encounter a technical difficulty, try a test implementation and ask here if necessary.

One of the more annoying problems is poorly specified requests.  They just want a thing that does "x" and don't tell you how it should be done.  For these a good approach is prototype an interface (typically a GUI) and let someone play with it.

Then there are time constraints that can't be met.  This often involves modifying expectations and delivering functional prototypes.

You will generally find your way through things one way or another.  It's frightening but once you're in it you can pretty much always find some way through.

Your best bet may be to just paint the words "Don't Panic" on the outside of your laptop.  And don't forget your towel.


问:
Why do so many hashed and encrypted strings end in an equals sign?
I work in C# and MSSQL and as you'd expect I store my passwords salted and hashed.

When I look at the hash stored in an nvarchar column (for example the out the box aspnet membership provider). I've always been curious why the generated Salt and Hash values always seem to end in either one or two equals signs.

I've seen similar things while working with encryption algorithms, is this coincidence or is there a reason for it?

答: These hashed string are (usually?) coded in the Base64 format and the equal sign are used for padding the string to make the length (number of bytes) divisible by three. Wikipedia explains it pretty well: http://en.wikipedia.org/wiki/Base64.</p>


答:
Could it be Base 64 encoding padding?

The '==' sequence indicates that the last group contained only one byte, and '=' indicates that it contained two bytes. The example below illustrates how truncating the input of the whole of the above quote changes the output padding:

http://en.wikipedia.org/wiki/Base64#Output_padding

Title: Why do so many hashed and encrypted strings end in an equals sign?

Body:
I work in C# and MSSQL and as you'd expect I store my passwords salted and hashed.

When I look at the hash stored in an nvarchar column (for example the out the box aspnet membership provider). I've always been curious why the generated Salt and Hash values always seem to end in either one or two equals signs.

I've seen similar things while working with encryption algorithms, is this coincidence or is there a reason for it?