答:
I think you're asking the wrong question. There is no objective bar to be a professional programmer. If there were, there'd be a standard programming exam, but there isn't. Your individual bar just has to be set based on how picky you can afford to be, how much you can afford to pay, how much blunder your software can afford to accept, and how much time you can afford to spend teaching.

In this case, I'm guessing that a buffer overrun probably means that this code, which the candidate presented as a sample of exemplary work, crashes with a segmentation fault instead of doing what you asked. So, should you accept a coder who writes code that crashes with a segmentation fault instead of doing what you asked for? Ask:

Is your organization capable of attracting anyone who can write working code?

Is your development process robust enough such that someone who can almost write code could write working code with the help of peer review and testing support?

Are you capable to teaching sort-of-programmers how to be a programmers, and are you willing to expend that effort and wait maybe a few years and hope that the candidate's inner talent will come to fruition?

Title: What standards can be expected from graduate/junior engineers?

Body:
Are buffer overflows acceptable from a graduate developer? Are we setting the bar too high? What are the expected capabilities of graduate/junior engineers?

Context:

We are currently recruiting for a Junior Developer position working mainly in C on Linux.

As part of the process, we require candidates to complete a code test at their leisure in C.

So far we have rejected two candidates on the basis that their code, although readable and in one case rather idiomatic, suffered from buffer overflow errors due to unbounded buffer writes.

[Edit]:

We explicitly ask for error-checked, production quality code.

We provide a test & build framework for the candidates

[Update]:

As a result of this thread, and conversations we have had with other developers in person, we are changing the way we carry out code tests and who we target with our recruiting.

We decided that a candidate being unable to fix or understand a buffer overflow means that he would be unsuitable for the work we carry out, in particular he would take more mentoring than we are comfortable with. We will therefore still reject candidates that cannot eventually submit a robust code sample.

However, we have put in place some measures to make the recruitment process more productive for both us and the candidates.

In particular:

We make our expectation more explicit, with clear explanation of what we mean by production quality, and a warning that the code is expected to be robust with respect to input and errors.

We now link candidates to resources on defensive programming and the C standard library in the description of the code test.

We changed our target audience from Junior developers and graduates to target people with some relevant experience.

In case the submitted code fails in some way but would otherwise be accepted, we now provide a minimum test case that causes the error condition and give the candidates a chance to correct their mistakes (unless the code is rejected for some other reason). We'll also point out problematic lines/functions if appropriate.

The goal of the tests itself has now slightly changed from a front end filter to a chance to build a better picture of the candidate, in particular it will inform our phone discussion. That said, we are still willing to reject based solely on code.

[Update 2015-07-09]:
Andy Davis from Nujob has written an interesting and relevant article on the use of a code test from the candidate's perspective, and the article is worth looking at. Find it here.


问:
Is Moving Entity Framework objects over a webservice really the best way?
I've inherited a .NET project that has close to 2 thousand clients out in the field that need to push data periodically up to a central repository. The clients wake up and attempt to push the data up via a series of WCF webservices where they are passing each entity framework entity as parameter. Once the service receives this object, it preforms some business logic on the data, and then turns around and sticks it in it's own database that mirrors the database on the client machines.

The trick is, is that this data is being transmitted over a metered connection, which is very expensive. So optimizing the data is a serious priority. Now, we are using a custom encoder that compresses the data (and decompresses it on the other end) while it is being transmitted, and this is reducing the data footprint. However, the amount of data that the clients are using, seem ridiculously large, given the amount of information that is actually being transmitted.

It seems me that entity framework itself may be to blame. I'm suspecting that the objects are very large when serialized to be sent over wire, with a lot context information and who knows what else, when what we really need is just the 'new' inserts.

Is using the entity framework and WCF services as we have done so far the correct way, architecturally, of approaching this n-tiered, asynchronous, push only problem? Or is there a different approach, that could optimize the data use?

答:
It seems you are using self-tracking entities and indeed these objects being serialised will be large and not recommended to send over WCF in your scenario. DTO, as others have mentioned would also be my preferred option. The next question would be what wire level serialisation will give the smallest size. One option is using protocol-buffers which I haven't used personally but worth looking into.<br>
But the one I will suggest is to use JSON as JSON is significantly smaller than equivalent XML. You can use WCF ([WebGet], [WebIvoke] attributes) or better yet use the ASP.Net MVC Web API. Enabling gzip compression using IIS should significantly reduce the payload size. </p>

ContentLicense: CC BY-SA 3.0

Body:
It seems you are using self-tracking entities and indeed these objects being serialised will be large and not recommended to send over WCF in your scenario. DTO, as others have mentioned would also be my preferred option. The next question would be what wire level serialisation will give the smallest size. One option is using protocol-buffers which I haven't used personally but worth looking into.

But the one I will suggest is to use JSON as JSON is significantly smaller than equivalent XML. You can use WCF ([WebGet], [WebIvoke] attributes) or better yet use the ASP.Net MVC Web API. Enabling gzip compression using IIS should significantly reduce the payload size.


问:
Is there a good reason not to display error messages to users?
Windows 8 seems to have chosen to silently shutdown applications that misbehave, there is no message informing the user something bad happened and no information on why the application closed.

I heard through the grapevine that employees at Microsoft are tired of customers blaming them for crashes and that they believe when they display an error to the user the user will accuse Microsoft of the crash instead of the app developer. Regardless of whether that is true or not is it really not a good idea to display error messages? I thought that error messages at least give users something to use when they are searching the web for help or talking to customer service. What possible good reason is there for crashing silently and not showing an error message?

答:
If it is not shown to the end-user, then it must be shown to an administrator (if the computer is managed by a company that owns it, e.g. in a workplace), or an error signature is being collected and uploaded to the Microsoft HQ and then classified into a Winqual bucket.

Apparently, by deciding not to show the error message to end-user, they also decided to secretly collect the error information without giving end-user a choice. This will massively increase the opportunity for collecting software errors on a massive scale.

If the crashing software happens to be Windows-certified, Microsoft can take actions by revoking it, or by implementing special workaround for this particular software, and push out the workaround (again, secretly) to everyone who happen to use it.

This is just my pure speculation.


答:
At work, we use a certain email program that is known to crash from time to time.  When it does this, the app displays a "please wait" message box while it submits a crash report, whose only real purpose is to keep me from re-launching the app while an error log is submitted.

Importantly, WINDOWS does not ever display an error message.  That's the job of the application, and the operating system has no business leaving the app's window drawn with a "this app is busted" dialog showing.

In general, a user should ONLY be shown an error message when there is something they can do.  An application should display an error dialog if there is a reasonable expectation that the user is waiting for the app; if your app is silently running in the background, displaying an error message is likely not relevant.

And Windows 8 silently killing apps is no different than android or iOS doing the same.  Especially if it's a "metro" app, which is meant to be largely managed by the OS anyway.

Title: Is there a good reason not to display error messages to users?

Body:
Windows 8 seems to have chosen to silently shutdown applications that misbehave, there is no message informing the user something bad happened and no information on why the application closed.

I heard through the grapevine that employees at Microsoft are tired of customers blaming them for crashes and that they believe when they display an error to the user the user will accuse Microsoft of the crash instead of the app developer. Regardless of whether that is true or not is it really not a good idea to display error messages? I thought that error messages at least give users something to use when they are searching the web for help or talking to customer service. What possible good reason is there for crashing silently and not showing an error message?


答:
Speaking from my code, and not microsoft's I would say that there are times I might hide errors from users. Usually, these are times when one of several things is true:

There is nothing the user can do with the knowledge

Imagine that your program hits some limit that it cannot recover from. Regardless of what the user does, you know the program has to be restarted. In this case, sometimes you might hide the cause from the user. BUT, and it is a big BUT, the program really should avoid this line or reasoning if at all possible. Take running out of memory for example. That might be unrecoverable, but if you never tell the user, they can't provide more memory.

My code can reasonably recover and the user can't really help

This isn't related to the scenario you describe, but there may be times when a program has an issue that it can handle, and not tell the user that it happened. But again, hiding errors like this could hide a deeper problem that the user could avoid in the future.

I don't know the error or handle it

In your example, Windows 8 may be shutting down "bad" programs. But what is bad (too much memory) and why they are bad are two different things. I could see deciding that it is better to just shut down than it is to provide an overly generic message or a bad one.

In all these cases, I would say that hiding an error from a regular user might be OK, but the error should be logged somewhere for a power user or administrator.


问:
Is there a way to prevent the editing of HTML and CSS contents in a page using Firebug-like tools?
Is there a way to prevent the editing of HTML and CSS contents in a page using Firebug-like tools?

I found that some users are editing some values in hidden fields and some contents which written between a div or span tag for gaining some profits. They are doing mostly by editing with help of tools like firebug. Is there any way to identify such modifications? The problem here is that the values they are editing is generated when the page is compiled. The page is developed in PHP. The editing is done mostly in between the tags.

答:
Nope, sorry. Even if you could, users could just submit the form to your site using some other tool.

The golden rule here is: Never trust user input. Be sure to validate everything on the server side (in php) and look up any important values from your database instead of trusting whatever came from the user.


问:
Web Project Class Architecture
I think this is a good question for here but I'm not 100% sure. Please flag if it's too vague.

I've worked on many websites where common framework classes are overridden.

Since I work mostly in .net these days examples would include Page, Masterpage, UserControl, DbContext ect. I believe this could apply to any language though.

Sometimes I can see why it's done, I overrode entity framework's DbContext to include some logging code.

Allot of the time though I don't see why these base classes were created. Because I've inherited most of the sites I can't really ask why.

My question: Is it a good idea/practice when creating a new site to Override the common framework classes mentioned above? Would doing so be considered more of an old style?

答:
In computer programming, a software framework is an abstraction in which software providing generic functionality can be selectively changed by additional user-written code, thus providing application-specific software. A software framework is a universal, reusable software platform to develop applications, products and solutions. Software frameworks include support programs, compilers, code libraries, tool sets, and application programming interfaces (APIs) that bring together all the different components to enable development of a project or solution.

Framework is a set of classes and utilities which has some basic functions but at the same time it is not standalone. Framework has many hooks which you can override to your own logic and has many holes which you must fill up with your own logic. Like interface and abstract class for example. Unless you are doing special work which need your own logic you are free to use the basic general framework logic.

For an example, we can use ASP.NET membership system in our ASP.NET application. It will act with the general membership logic. But if we need a special situation which is special for your application then you have to inherit and override the membership provider classes to give your own implementation.

Title: Web Project Class Architecture


问:
Microsoft's coding standards for ASP.NET controls
I cannot find any naming standards/conventions in MSDN for naming ASP.NET controls.

One of the following standards tends to be used by programmers:

lblAddress

AddressLabel

Address

According to MSDN's Name of Type Members, should we be treating ASP.NET controls as fields, hence using Pascal Case (e.g. AddressLabel)?

答: Yes controls are fields of your Page class. You should name it with camel casing. Like lblResult, grdEmployees etc. If you do not have any good naming convention in your company then you can use Microsoft naming convention. You can read more about basic Microsoft naming convention here.


问:
How to use my proprietary framework on a new job without making it open-source?
I have been working on a framework for years. It is solid, extensive and tested. It is exactly what the employer needs for the foundation of its new project. There is no point in rewriting the whole thing from scratch or using a competing open-source alternative.

My desire is to give a free, non-exclusive, non-redistributable license to the employer for access to the binaries and sources, so the employer can change the code. I understand that the employer cannot depend on closed-source code so I am willing to give my sources to the employer for free (the equivalent to two years of my work for free). I just want to protect my copyright and prevent the employer from giving the code to someone else. I believe many programmers will find themselves in this situation when starting a new job.

However, making it open-source is out of question for a variety of reasons that do not matter for the purpose of this question.  I want to keep the source closed, but provide a free copy under a non-exclusive, non-redistritubable license.

So my questions are:

When do I bring it up that I have a framework that I would like to use? Probably before I take the job because if they don't want to use it OR don't accept my license I am not taking the job.

What kind of license should I use to make this deal with my employer?

Any other considerations or comments?

UPDATES:

One thing I can say is that there are other companies using the software (with licenses) so I cannot make it open-source or simply transfer the copyright to my new employer, which is what actually happens if you use it in your job without having this discussion.

答:
As the use of your framework is a condition for you in accepting the job, you really must discuss this before you (even verbally) accept any kind of offer.

As to the licensing question, the fact that you give a 'customer' access to your source code does not imply that you must make your project open-source. It is entirely possible to provide the framework (including source code) to your employer under the same license as you used for the other companies. Unless the license explicitly permits it, they can read the source code, but not modify or re-distribute it.

You can also choose to give your employer a more relaxed license that allows modification, but not re-distribution.

As for other things to consider:

Would you give them a license if the want your framework, but don't offer an acceptable job for you?

Have you considered the possibility that you make a nice enhancement on behalf of your employer that you might want to distribute also to your other customers? Doing so without consent from your employer might land you on a legal slippery slope.

Instead of entering into a standard employment contract and bringing your framework along, you might also consider some more unusual constructs. For example, you enter into two contracts. One is an employment contract for the work you will do for your employer, with the difference that any work you do on your framework on request of your employer is excluded from the terms of that contract, but your employer is required to give you the opportunity to perform that work under working hours. The other is a service contract for your framework under which you perform the work excluded from the regular employment contract.

The advantage of such a construct is that it remains clear that you are, and remain, in full control of the framework. In return, your employer gets their requested updates fast (as you don't have to do it in your spare time).

As this all is a rather uncommon situation, I strongly advise you to seek proper legal advise.


问:
Which layer does async code belong?
I am developing an application that consumes data from an external service.  The application is being implemented following a typical layered architecture with UI, Presentation, Domain and Data layers.  The service client resides within the Data layer.

As is typically the case, I do not want the UI to 'lock-up' while waiting for calls from the external service to complete.  However, implementing the service agents with asynchronous methods results in a complicate model chaining async methods up the layers so the UI can stay responsive.

For example:

In the ViewModel:

```<code>TheRepository.LoadDataAsync().ContinueWith(t => { _data = t.Result; });
</code>```

In TheRepository:

```<code>public Task<TheData> LoadDataAsync()
{
    return ServiceClient.GetDataFromServiceAsync();
}
</code>```

(Note, this is a significant over-simplification meant to convey what I mean by task chaining.)

Because the requirement is a UI requirement (prevent the UI from 'locking'), doesn't it make sense to keep the Domain and Data layers synchronous and leave it up to the Presentation layer to decide when it needs to perform some operation asynchronously?

On the other hand, it is so easy and natural to implement the service client/proxy with async methods (VS will auto-generate them if needed) because this is what we think of when we think about the need for async.

If the application was pulling data out of a database instead of making a service call, the layers wouldn't be any different and it shouldn't really change how the UI, Presentation or Domain layers have been implemented, right?  In this case, we wouldn't think twice about having the data access be synchronous.

Would it be a better design to model the Domain synchronously and leave it to the Presentation layer to address performance issues in the UI?  Or, in the emerging async world, should we just accept async as the norm and make everything fit this model?

答:
```<code> > Which layer does async code belong?
</code>```

Short answer: into presenter or into an extra service-layer but not in the gui, data or domain layer.

Long answer:

I would put it into a service-layer that sits between presenter- and domain-layer resulting in these layers

```<code>gui - presenter - service - domain - data
</code>```

In the domainlayer (or the servicelayer) you have a synchronios version of the logic that needs to consume the data of the external service. Lets call it mySyncMethod.

In the servicelayer you create a thin async wrapper around mySyncMethod.

Reason: It is very difficuilt to unittest async methods. sync methods are much easier to test.

If there is only one reference to the async functionality you can put into the presenter.

Title: Which layer does async code belong?

Body:
 > Which layer does async code belong?

Short answer: into presenter or into an extra service-layer but not in the gui, data or domain layer.

Long answer:

I would put it into a service-layer that sits between presenter- and domain-layer resulting in these layers

gui - presenter - service - domain - data

In the domainlayer (or the servicelayer) you have a synchronios version of the logic that needs to consume the data of the external service. Lets call it mySyncMethod.

In the servicelayer you create a thin async wrapper around mySyncMethod.

Reason: It is very difficuilt to unittest async methods. sync methods are much easier to test.

If there is only one reference to the async functionality you can put into the presenter.


问:
Are bugs part of technical debt?
Our Scrum Master keeps referring to bugs as technical debt. Is he right, are bugs considered to be technical debt in the world of Agile?</p>

答:
Yes.

Technical debt (also known as design debt or code debt) is a neologistic metaphor referring to the eventual consequences of poor or evolving software architecture and software development within a codebase.

Source: Wikipedia

Read technical debt as something you could have avoided by having a better workflow (for example doing architecture properly before jumping to coding, doing TDD, etc.), better coding practices, etc.

Most bugs could have been avoided by additional review or the usage of more formal methods. By not doing everything you can to not having bugs in the first place, you lower the immediate/short term cost of the project, but increasing the technical debt.

After reading the answer by BЈовић, I see that it may not be as easy as I thought.

For example Are bugs part of technical debt? article claims that only bugs you know about but decided not to fix are part of technical debt.

Another example, Christopher's Thoughts on Technical Debt qualifies bugs as the result of technical debt, not part of it. This being said, many of the listed results, like "cost to implement new feature", are influenced by the number of bugs.

Finally, when creating ABCDE-T model of technical debt, I included bugs as one of the six factors, but they are considered differently. The focus is not on the bugs themselves, but on the ways they are collected, prioritized and solved. Bugs themselves appear as the result of technical debt (like in the previous example), but never appear themselves as a factor of technical debt.

This being said, I'm still inclined to answer that bugs —any bugs— are part of technical debt.

First argument:

Reading Jeff Atwood's quote, most bugs would qualify as:

the extra effort that we have to do in future development because of the quick and dirty design choice

In business applications, nearly every bug comes from either quick and dirty design choice or bad practices (would it be the lack of testing, the usage of technologies the developers don't know enough, lack of communication, lack of understanding of the domain, etc.) This means that "by refactoring the quick and dirty design into the better design" and by adapting better practices, businesses could solve most of their bugs.

Second argument:

If we make a parallel between the ordinary debt of a company which is important to take in account when a company is sold to another, and the technical debt, which is equally important to take in account when a project is sold to another company or given to another team, we can easily see that bugs are part of the technical debt, since the new team would:

Either have to deal with those bugs before making new features (point 5 of Joel Test: Do you fix bugs before writing new code?)

Or keep the bugs, preserving/increasing this way the technical debt.

Title: Are bugs part of technical debt?


答:
Jeff Atwood in his article Paying Down Your Technical Debt gives quite nice answer on what technical debt is :

the technical debt incurs interest payments, which come in the form of
  the extra effort that we have to do in future development because of
  the quick and dirty design choice. We can choose to continue paying
  the interest, or we can pay down the principal by refactoring the
  quick and dirty design into the better design. Although it costs to
  pay down the principal, we gain by reduced interest payments in the
  future.

Strictly speaking, bugs are not part of technical debt, if they do not slow down further software development (changing things, adding new features, etc). They are software defects.

However, when it is too expensive to fix a bug, or it forces you to work around it (and introduce even more technical debt), then it becomes part of a technical debt.

Title: Are bugs part of technical debt?

Body: Our Scrum Master keeps referring to bugs as technical debt. Is he right, are bugs considered to be technical debt in the world of Agile?</p>


问:
Subclassing to change default settings?
I have a class called Timeline. I want to allow several defaults in my code, such as a Timeline with a Start event (The details are not needed. All that matters is that I have a class, and I want to be able to have a few different default setting). Here are the options I thought of:

1) Following a GUI/Swing inspired idea, I might want to subclass the Timeline class and, in its constructor, use the public functions to set the default. Then, I could later just instantiate those objects instead of the superclass

2) A factory class could have functions like "getTimeLineWithExplosion" and set everything up.

Which of those two is the better idea? Is there a design pattern better than both of them?

PS: This is implemented in Java, but could easily be in another language.

答:
Yes, 2nd approach is better.
 Here are other options.
You can go for prototype pattern.
Extra thing which will be required is that timeline class should implement
Clone able, and then depending on timeline class I will do
Shallow cloning or deep cloning.

If prototype option is too much, then you can go for builder
Pattern. This approach will be more cleaner.

Title: Subclassing to change default settings?


问:
LGPL and commerical application in PHP
I have rather specific question about licensing but first of all I would just like to state that I already read a lot of Q&A's here but I'm still not sure about the problem in that particular scope.

As I've understand from other Q&A's, you are allowed to distribute your commercial application even with LGPL library as long as this library can be replaced by another version of it by user himself. That means that you pack it as .dll or whatever. The rest of the application remains proprietary licensed.

This is clear at all for compiled software. But my question is: how this relate to software which is not compiled (which is distributed as source code but still proprietary) like all PHP applications?

To be really clear I will show you exact example. I'm building a CMS applications for various purposes. All of them are different but most of them share the same "basic element" - JavaScript WYSIWYG editor. I would like to use one which is GPL/LGPL/MPL licensed.

So there are several questions:

Can I use this LGPL editor at all so that rest of my application remains proprietary?

What I have to do to be able to do that?

Are there any special "ways of distributing" the library like separated ZIP archive or something like that?

As for non-native English speaker it's really hard for me to read the licenses in their original form. I just don't want to get in any trouble.

答:
As far as the large majority of open-source licenses is concerned, there is no difference at all between software written in a compiled language (thus providing the ability to distribute object/binary code) and software written in an interpreted language (thus effectively requiring distribution in source form). This also holds for the interaction of these licenses with each other and with non-free licenses.

For example, if you have written a PHP program that makes use of a module that is distributed under the GPL license, then you can not distribute the code you wrote under a license that forbids modification or redistribution. This is regardless of the availability of the source code, because it is about the rights you give the recipients of the program.

To answer your questions: Yes, you can use an LGPL editor in your proprietary application (without affecting the license), provided that the user of the application has the possibility to replace the editor with another (compatible) one. There are no special requirements on how you distribute such an application, but if you use third-party components (regardless of how they are licensed) it is a good idea to clearly identify them in a Readme file or something similar.

Title: LGPL and commerical application in PHP


问:
Design guidelines for this scenario in C#?
I have to create a validation system(I don't want to use Data Annotation or any other system) for my C# application using .Net Compact Framework, where I have an object which contains many other objects.

Many of the properties are dependent on each other means they have some sort of dependencies.

I can write a simple validator class which goes through all the properties
and checks them one by one with lots of if and else but I want to design something dynamic e.g. I should be able to specify list of dependencies on a property and specify a method which should be invoked during validation.

I mean some design guidelines would be appreciated ?

Example ( just for demo purpose ):

```<code>    public enum Category
        {
            Toyota,
            Mercedes,
            Tata,
            Maruti
        }

        class MyBigClass
        {
            public Category Category { get; set; }
            public double LowerPrice { get; set; }
            public double UpperPrice { get; set; }

            public SomeOtherObject OtherObject { get; set; }

public List<string> Validate()
        {
            List<string> listErrors = new List<string>();
            ParameterInfo pInfo = null;
            switch (Category)
            {
                case Category.Toyota:
                    pInfo = ParameterStorage.GetParameterInfo(PTYPE.Category_Toyota);
                    break;
                case Category.Mercedes:
                    pInfo = ParameterStorage.GetParameterInfo(PTYPE.Category_Mercedes);
                    break;
                case Category.Tata:
                    pInfo = ParameterStorage.GetParameterInfo(PTYPE.Category_Tata);
                    break;
                case Category.Maruti:
                    pInfo = ParameterStorage.GetParameterInfo(PTYPE.Category_Maruti);
                    break;
                default:
                    break;
            }

            if (LowerPrice < pInfo.Min || LowerPrice >= pInfo.Max)
            {
                listErrors.Add("LowerPrice");
            }

            if (UpperPrice > pInfo.Max || UpperPrice <= pInfo.Min)
            {
                listErrors.Add("UpperPrice");
            }

            return listErrors;
        }
        }

        public enum PTYPE
            {
                RATING,
                Category_Tata,
                Category_Toyota,
                Category_Mercedes,
                Category_Maruti
            }

            public class ParameterInfo
            {
                public PTYPE Type { get; set; }
                public int Min { get; set; }
                public int Max { get; set; }
                public int Default { get; set; }
            }

       public class ParameterStorage
        {
            private static Dictionary<PTYPE, ParameterInfo> _storage = new Dictionary<PTYPE, ParameterInfo>();
            static ParameterStorage()
            {
                _storage.Add(PTYPE.Category_Maruti, new ParameterInfo { Type = PTYPE.Category_Maruti, Min = 50000, Max = 200000 });
                _storage.Add(PTYPE.Category_Mercedes, new ParameterInfo { Type = PTYPE.Category_Mercedes, Min = 50000, Max = 800000 });
                _storage.Add(PTYPE.Category_Toyota, new ParameterInfo { Type = PTYPE.Category_Toyota, Min = 50000, Max = 700000 });
                _storage.Add(PTYPE.Category_Tata, new ParameterInfo { Type = PTYPE.Category_Tata, Min = 50000, Max = 500000 });
            }

            public static ParameterInfo GetParameterInfo(PTYPE type)
            {
                ParameterInfo pInfo = null;
                _storage.TryGetValue(type, out pInfo);
                return pInfo;
            }
        }
</code>```

In the above example I have a MyBigObject which contains some properties and some other objects and I have a storage class which keeps all the limits of properties which will be required to validate a property.

As described in the above example I have to get ParameterInfo for each property and then compare, I am looking for some kind of automatic way/dynamic way of doing the same.

答:
I think you want something like this Fluent Validator for ASP MVC

The idea is the same as with annotations, but you can define rules at runtime, though with much less "if-statements".

Here is the sample code of validation method:

```<code>[Validator(typeof(PersonValidator))]
public class Person {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public int Age { get; set; }
}

public class PersonValidator : AbstractValidator<Person> {
    public PersonValidator() {
        RuleFor(x => x.Id).NotNull();
        RuleFor(x => x.Name).Length(0, 10);
        RuleFor(x => x.Email).EmailAddress();
        RuleFor(x => x.Age).InclusiveBetween(18, 60);
    }
}
</code>```

Body:
I think you want something like this Fluent Validator for ASP MVC

The idea is the same as with annotations, but you can define rules at runtime, though with much less "if-statements".

Here is the sample code of validation method:

[Validator(typeof(PersonValidator))]
public class Person {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public int Age { get; set; }
}

public class PersonValidator : AbstractValidator<Person> {
    public PersonValidator() {
        RuleFor(x => x.Id).NotNull();
        RuleFor(x => x.Name).Length(0, 10);
        RuleFor(x => x.Email).EmailAddress();
        RuleFor(x => x.Age).InclusiveBetween(18, 60);
    }
}


答:
I think there is one mistake you are making. And that is you want to create a framework/library directly. Eg. you don't know all cases this framework/library needs to solve, yet, you are trying to create this framework/library.

You should first do things directly, without first making a framework. Only after you create multiple cases should you try to abstract away what is common among those classes. Trying to be "dynamic" and "universal" will only hurt you in the long run.

Also, your code example is screaming from bad OO design. The moment you name an enum "type" or "kind" (or "category" in your case), it becomes obvious it should be multiple different classes within a hierarchy. This is probably why your code looks so bad and "static". Because you didn't care about proper separation of concerns and polymorphism. If you did this, you could even realize you don't need any dynamic validation and that hand-coded validation is just fine.

Title: Design guidelines for this scenario in C#?

Body:
I have to create a validation system(I don't want to use Data Annotation or any other system) for my C# application using .Net Compact Framework, where I have an object which contains many other objects.

Many of the properties are dependent on each other means they have some sort of dependencies.

I can write a simple validator class which goes through all the properties
and checks them one by one with lots of if and else but I want to design something dynamic e.g. I should be able to specify list of dependencies on a property and specify a method which should be invoked during validation.

I mean some design guidelines would be appreciated ?

Example ( just for demo purpose ):

```<code>    public enum Category
        {
            Toyota,
            Mercedes,
            Tata,
            Maruti
        }

        class MyBigClass
        {
            public Category Category { get; set; }
            public double LowerPrice { get; set; }
            public double UpperPrice { get; set; }

            public SomeOtherObject OtherObject { get; set; }

public List<string> Validate()
        {
            List<string> listErrors = new List<string>();
            ParameterInfo pInfo = null;
            switch (Category)
            {
                case Category.Toyota:
                    pInfo = ParameterStorage.GetParameterInfo(PTYPE.Category_Toyota);
                    break;
                case Category.Mercedes:
                    pInfo = ParameterStorage.GetParameterInfo(PTYPE.Category_Mercedes);
                    break;
                case Category.Tata:
                    pInfo = ParameterStorage.GetParameterInfo(PTYPE.Category_Tata);
                    break;
                case Category.Maruti:
                    pInfo = ParameterStorage.GetParameterInfo(PTYPE.Category_Maruti);
                    break;
                default:
                    break;
            }

            if (LowerPrice < pInfo.Min || LowerPrice >= pInfo.Max)
            {
                listErrors.Add("LowerPrice");
            }

            if (UpperPrice > pInfo.Max || UpperPrice <= pInfo.Min)
            {
                listErrors.Add("UpperPrice");
            }

            return listErrors;
        }
        }

        public enum PTYPE
            {
                RATING,
                Category_Tata,
                Category_Toyota,
                Category_Mercedes,
                Category_Maruti
            }

            public class ParameterInfo
            {
                public PTYPE Type { get; set; }
                public int Min { get; set; }
                public int Max { get; set; }
                public int Default { get; set; }
            }

       public class ParameterStorage
        {
            private static Dictionary<PTYPE, ParameterInfo> _storage = new Dictionary<PTYPE, ParameterInfo>();
            static ParameterStorage()
            {
                _storage.Add(PTYPE.Category_Maruti, new ParameterInfo { Type = PTYPE.Category_Maruti, Min = 50000, Max = 200000 });
                _storage.Add(PTYPE.Category_Mercedes, new ParameterInfo { Type = PTYPE.Category_Mercedes, Min = 50000, Max = 800000 });
                _storage.Add(PTYPE.Category_Toyota, new ParameterInfo { Type = PTYPE.Category_Toyota, Min = 50000, Max = 700000 });
                _storage.Add(PTYPE.Category_Tata, new ParameterInfo { Type = PTYPE.Category_Tata, Min = 50000, Max = 500000 });
            }

            public static ParameterInfo GetParameterInfo(PTYPE type)
            {
                ParameterInfo pInfo = null;
                _storage.TryGetValue(type, out pInfo);
                return pInfo;
            }
        }
</code>```

In the above example I have a MyBigObject which contains some properties and some other objects and I have a storage class which keeps all the limits of properties which will be required to validate a property.

As described in the above example I have to get ParameterInfo for each property and then compare, I am looking for some kind of automatic way/dynamic way of doing the same.


答:
I think the answer here is fairly simple - the key feature of technical debt is that its something we incur by choice.

We choose to make architectural, design or implementation decisions that we expect will cause us issues later in order to achieve specific objectives sooner.

A bug is not something we choose to have in our code - so de-facto its not technical debt.

Of course one can make all kinds of interesting (and possibly valid) arguments about choices made post discovery but fundamentally (and particularly in the context of the question) no, bugs are not technical debt - sounds more like abuse of buzzword bingo to me.

As a postscript - I don't agree with the assertion that its a given that technical debt will lead to bugs in and of itself as that makes far to many assumptions about the nature of the choices made. For example you can have well written, well structured, test covered code that still makes - say - architectural compromises for early delivery. Similarly you could choose not automate your deployment processes which won't lead to bugs but will probably lead to a lot of stress and pain. Of course if the debt is that you've written code that's not SOLID (or whatever) then yes... but that's by no means always the case.

Title: Are bugs part of technical debt?


问:
Solving which bugs will give greatest cost benefit
I wanted to get an idea of categorizing bugs based on how easy is it to solve and how much benefit it will give me. for e.g., if there is a bug which will take say an hour (double file close etc.) to solve vs another which takes a day (segmentation fault). But if solving the first bug is not very important, then I'll probably work on the second one.

Is there a practical method or an approach to categorize bugs based on cost-benefit or similar metric?

Let's say it is possible to categorize bugs based on bug characteristics e.g. security vulnerability, memory error, logic error etc. On the other dimension there could be parameters like difficulty (easy, medium, hard). Are there other dimensions I should be looking for. To simplify things, I can assume two things:

Every programmer in the team is equally capable of solving any bug

There is no deadline

答:
The typical bug tracking system has two, maybe three fields identifying bug cost benefit ratio:

Priority (assigned by business owner)

Severity (classification of bug - critical to low)

Estimated hours (a guess at how long it will take to do)

As you note, this does identify which bug is the important one to work on.

The system put forth in PEF/REV: A Multi-dimensional bug tracking metric adds more information on the business and developer components to bug cost benefit.

All values are on a 1 .. N scale (same top value for each).

PEF is identified by the business:

Pain - How painful the bug is

Effort - How much effort it takes to work around the bug

Frequency - How often does the bug occur

REV comes from the developer:

Risk - How risky is the fix to the system

Effort - How much effort is there to fix the bug

Verifiability - How easy is it to verify the bug fix

If, for example, you have a rarely happening crash that is easy to work around (turn on autosave), that could be a PEF of 7,1,1 (score 9).  While fixing it may involve a change to a core module and have a REV of 9,3,2 (score 14).

On the other hand, you could have a annoyance that is always there (3,3,9 - score 15) that has a trivial fix (1,1,3 - score 5).

In this example, the annoyance looks to be a better cost/benefit thing to work on.

ContentLicense: CC BY-SA 4.0


问:
Elegant ways to handle if(if else) else
This is a minor niggle, but every time I have to code something like this, the repetition bothers me, but I'm not sure that any of the solutions aren't worse.

if(FileExists(file))
{
    contents = OpenFile(file); // <-- prevents inclusion in if
    if(SomeTest(contents))
    {
        DoSomething(contents);
    }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}
```

Is there a name for this kind of logic?

Am I a tad too OCD?

I'm open to evil code suggestions, if only for curiosity's sake...

答:
For this particular case, the answer is easy enough...

There is a race condition between FileExists and OpenFile: what happens if the file is removed?

The only sane way to deal with this particular case is to skip FileExists:

contents = OpenFile(file);
if (!contents) // open failed
    DefaultAction();
else (SomeTest(contents))
    DoSomething(contents);
```

This neatly solves this problem and makes the code cleaner.

In general:
Try to rethink the problem and devise another solution which avoids the issue entirely.

Title: Elegant ways to handle if(if else) else

Body:
For this particular case, the answer is easy enough...

There is a race condition between FileExists and OpenFile: what happens if the file is removed?

The only sane way to deal with this particular case is to skip FileExists:

contents = OpenFile(file);
if (!contents) // open failed
    DefaultAction();
else (SomeTest(contents))
    DoSomething(contents);

This neatly solves this problem and makes the code cleaner.

In general:
Try to rethink the problem and devise another solution which avoids the issue entirely.


答:
In addition to what others have said about the classification of bugs, etc, also consider looking at Afferent Coupling (Ca) for determining the level of criticalness a particular bug might represent.  If you have a bug in a module with a high Ca count, I might be looking at fixing that one first as it could benefit other components in the system.  Ca helps you determine the level of responsibility, and responsible modules with bugs in them hurt the whole application (read more about Ca here: http://www.ibm.com/developerworks/java/library/j-cq04256/index.html).

With that in mind, we tend to categorize bugs and place them in priority based on their impact to the customer.  Your customer will vary, but having them involved in the discussion will ultimately drive what bugs should be fixed over others.  It's not real scientific, but as a whole team we tend to come to consensus on the priority and categorization of bugs, everyone has input on the "big ones" (all the stakeholders can give input), and we stack and rack from there.

Title: Solving which bugs will give greatest cost benefit

Body:
I wanted to get an idea of categorizing bugs based on how easy is it to solve and how much benefit it will give me. for e.g., if there is a bug which will take say an hour (double file close etc.) to solve vs another which takes a day (segmentation fault). But if solving the first bug is not very important, then I'll probably work on the second one.

Is there a practical method or an approach to categorize bugs based on cost-benefit or similar metric?

Let's say it is possible to categorize bugs based on bug characteristics e.g. security vulnerability, memory error, logic error etc. On the other dimension there could be parameters like difficulty (easy, medium, hard). Are there other dimensions I should be looking for. To simplify things, I can assume two things:

Every programmer in the team is equally capable of solving any bug

There is no deadline


答:
You can't determine the actual cost of all bugs. Some you can, for many it's very hard to quantify. For example, say you have a bug that results in all of the text on buttons are slightly misaligned. It makes your 1.0 product look a little sloppy. This doesn't cause your program to crash, or your users to lose data. Probably a pretty cheap bug, right?

Now, what if every customer of yours notices this problem, and every reviewer mentions it in reviews of your product. And what if this bug carries over from version 1.0 to 1.1 and 1.2. Your company may now have a reputation of being a bit sloppy in quality control. How expensive might this simple bug be in terms of potential lost sales for your company for future products? Or, how might this affect a review that your product gets -- your product may perfectly meet the needs of your customers, but only gets an 9 out of 10 because it looks a little sloppy.

So, you need to not only look at the cost of a specific bug in terms of what it costs to fix and it's direct impact on the user, but you have to consider it in the larger context of how it affects the perception of your product in the marketplace, and how that perception affects future sales.

This may seem far-fetched but it isn't. At the time that I write this you can go to another site on the web that has an article about how Apple has moved the "1" on their calendar icon over by a pixel or two. If you do a search you'll see several negative articles about this tiny little bug. Of course, this hasn't directly affected Apple's bottom line, but they promote themselves as the pinnacle of good design, so having a design bug affects that perception, even if only slightly.


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
Obviously after reading some business magazine on an airplane about how XML was the hot new technology (this was circa 2002), one of our executives asked me if our application used XML, when I said no he asked me if we could add it.

Now, I'm not talking about a feature to import/export files in XML format, he simply wanted it to be part of the architecture for no reason other than it was popular at the moment and would lend credibility to our app.

ContentLicense: CC BY-SA 2.5


问:
Why would you use MVC over Web Forms?
Recently an architect described our company as offering a Rolls-Royce solution (MVC) when all he needed was a Toyota (Web Forms).

I'm curious to find out what you think about web forms vs MVC as an architectural choice.

答:
The Rolls-Royce/Toyota analogy is terribly flawed and misleading. One (ASP.NET MVC) is not simply a fancier or more expensive version of the other (ASP.NET WebForms). They are vastly different approaches to building web applications using ASP.NET.

To me, the biggest architectural difference between MVC and WebForms is how they work with the stateless environment of the web: WebForms works hard to build a set of abstractions that hide the stateless nature of web programming, whereas MVC embraces the stateless environment and works with it.

Each approach has its benefits and detriments, but I really enjoy how building web sites with MVC feels much more natural than WebForms (with its layer upon layer of leaky abstractions).

Title: Why would you use MVC over Web Forms?


问:
Exceptions vs ErrorCodes when working with devices
Out team is at the cusp of a new project.
One of the components at the boundary of the system is the component which interacts with a printer through an external COM component (referenced as a usual dll).

The COM component returns integer codes if there were an error whilst command execution.
Lets consider a concrete code.

```<code>  public class OperationException:Exception {
    public int ErrorCode { get; private set; }
    public string ErrorDescription { get; private set; }

    public OperationException(int errorCode, string errorDescription) {
        ErrorCode = errorCode;
        ErrorDescription = errorDescription;
    }
}

//The exception throwing way
public class Provider1:IFrProvider {
    private readonly IDrvFR48 driver;

    public string GetSerialNumber() {
        //must read status before get SerialNumber
        int resultCode = driver.ReadEcrStatus();
        if (resultCode != 0) {
            throw new OperationException(resultCode, driver.ErrorDescription);
        }
        return driver.SerialNumber;
    }
}

//The way of out parameters returning.
public class Provider2 : IFrProvider
{
    private readonly IDrvFR48 driver;

    public string GetSerialNumber(out Result result) {
        //must read status before get SerialNumber
        int resultCode = driver.ReadEcrStatus();
        if (resultCode != 0) {
            result = new Result(resultCode, driver.ErrorDescription);
            return null;
        }
        result = new Result(0, null);
        return driver.SerialNumber;
    }
}

//The way of LastResult property setting.
public class Provider3 : IFrProvider
{
    private readonly IDrvFR48 driver;

    public Result LastResult {
        get {
            return new Result(driver.ErrorCode, driver.ErrorDescription);
        }
    }

    public string GetSerialNumber() {
        //must read status before get SerialNumber
        if (driver.GetECRStatus() == 0)
            return driver.SerialNumber;
        return null;
    }
}

public class Result {
    public int ResultCode { get; private set; }
    public string Description { get; private set; }

    public Result(int resultCode, string description) {
        ResultCode = resultCode;
        Description = description;
    }
}

public class Caller {
    public void CallProvider1() {
        var provider = new Provider1();
        try {
            string serialNumber = provider.GetSerialNumber();
            //success flow
        }
        catch (OperationException e) {
            if (e.ErrorCode == 123) {
                //handling logic
            }
        }
    }

    public void CallProvider2() {
        var provider = new Provider2();

        Result result;
        string serialNumber = provider.GetSerialNumber(out result);
        if (result.ResultCode == 123) {
            //error handling
        }
        //success flow
    }

    public void CallProvider3()
    {
        var provider = new Provider3();

        string serialNumber = provider.GetSerialNumber();
        if (provider.LastResult.ResultCode == 123) {
            //handling
        }
        //success flow
    }
}
</code>```

So we have three ways of error handling. The most specific thing in all this stuff is that each operation can fail, because it depends on a device.

Our team think of using out parameters, because of unhandled exceptions propagation fear. The other reason, connected with the fear, is that we will have to cover all calls by try\catch blocks to stop to be afraid, but such a code will be pretty ugly.

What pros and cons do you see and what could you advice?

答:
Very debatable question, that depends on many conditions of your project, workflow, whether your code will be used by other developers, etc.

Yes, the common .Net practice is to throw exceptions instead of returning an error code. Very good comment about it here.

Error codes are old skool, you needed them back in the bad old days of COM and C programming, environments that didn't support exceptions. Nowadays, you use exceptions to notify client code or the user about problems. Exceptions in .NET are self-descriptive, they have a type, a message and diagnostics.

Thought, you need to have in mind other aspect - if the code of the error itself is also self-descriptive (like http codes, 404, 503, etc), then you can return the code. And the .Net framework actually returns such code with HttpWebResponse.StatusCode (though still wrapped with enum). But do it if you know for sure (he-he) that these codes won't change in future.

In other cases, what sense to user of your code to know that it was -lets say - error #23452, that was occurred. Besides, it can be changed in future, that causes the user to override his code because of number changed.


答:
The fear with exception can be eased by learning proper exception handling programming style (and also general error handling techniques).

Proper error handling (applicable to all mechanisms, and particular applicable to exception handling) requires careful reasoning as to the consequences and interpretation of each failed operation. Such reasoning entail:

After encountering an error, which line of code will it execute next?

After encountering an error, what does it say about the current state of the device?

Can the device resume normal operation?

Does the device need a reset?

Does the human user need to be notified?

After encountering an error, is the program state still consistent?

Should the program do some cleanup to restore the program state's consistency?

This reasoning can be extended to any programming black-boxes such as a third-party library.

Code example.

To ensure that every successful call to QueryStatusStart is followed up with a call to QueryStatusFinish with other calls in between:

```<code>bool queryStatusStarted = false;
try
{
    // throws exception if fails
    device.QueryStatusStart();

    // this line is not executed unless the previous line succeeded.
    queryStatusStarted = true;

    // might throw exception
    device.MakeMoreQueryStatusCalls();
}
finally
{
    // Whether or note MakeMoreQueryStatusCalls() throws an exception,
    // we will reach here. Hence we can restore the device to a
    // known state.

    if (queryStatusStarted)
    {
        device.QueryStatusFinish();
    }
}
</code>```

In general programming, status cleanup methods (such as
the QueryStatusFinish method above) should not
throw exception (because throwing an exception in a catch{}
or finally{} block will indeed cause the uncaught exception
problem you feared.

However, when dealing with a physical device, there is a
need to interpret what a failed cleanup (restoration) means:

Device has disconnected

Device has malfunctioned and require human intervention (such as a power reset)

In either case, the program will not be able to continue its
normal operation. The correct way to handle this situation varies
from case to case.

Title: Exceptions vs ErrorCodes when working with devices

Body:
Out team is at the cusp of a new project.
One of the components at the boundary of the system is the component which interacts with a printer through an external COM component (referenced as a usual dll).

The COM component returns integer codes if there were an error whilst command execution.
Lets consider a concrete code.

```<code>  public class OperationException:Exception {
    public int ErrorCode { get; private set; }
    public string ErrorDescription { get; private set; }

    public OperationException(int errorCode, string errorDescription) {
        ErrorCode = errorCode;
        ErrorDescription = errorDescription;
    }
}

//The exception throwing way
public class Provider1:IFrProvider {
    private readonly IDrvFR48 driver;

    public string GetSerialNumber() {
        //must read status before get SerialNumber
        int resultCode = driver.ReadEcrStatus();
        if (resultCode != 0) {
            throw new OperationException(resultCode, driver.ErrorDescription);
        }
        return driver.SerialNumber;
    }
}

//The way of out parameters returning.
public class Provider2 : IFrProvider
{
    private readonly IDrvFR48 driver;

    public string GetSerialNumber(out Result result) {
        //must read status before get SerialNumber
        int resultCode = driver.ReadEcrStatus();
        if (resultCode != 0) {
            result = new Result(resultCode, driver.ErrorDescription);
            return null;
        }
        result = new Result(0, null);
        return driver.SerialNumber;
    }
}

//The way of LastResult property setting.
public class Provider3 : IFrProvider
{
    private readonly IDrvFR48 driver;

    public Result LastResult {
        get {
            return new Result(driver.ErrorCode, driver.ErrorDescription);
        }
    }

    public string GetSerialNumber() {
        //must read status before get SerialNumber
        if (driver.GetECRStatus() == 0)
            return driver.SerialNumber;
        return null;
    }
}

public class Result {
    public int ResultCode { get; private set; }
    public string Description { get; private set; }

    public Result(int resultCode, string description) {
        ResultCode = resultCode;
        Description = description;
    }
}

public class Caller {
    public void CallProvider1() {
        var provider = new Provider1();
        try {
            string serialNumber = provider.GetSerialNumber();
            //success flow
        }
        catch (OperationException e) {
            if (e.ErrorCode == 123) {
                //handling logic
            }
        }
    }

    public void CallProvider2() {
        var provider = new Provider2();

        Result result;
        string serialNumber = provider.GetSerialNumber(out result);
        if (result.ResultCode == 123) {
            //error handling
        }
        //success flow
    }

    public void CallProvider3()
    {
        var provider = new Provider3();

        string serialNumber = provider.GetSerialNumber();
        if (provider.LastResult.ResultCode == 123) {
            //handling
        }
        //success flow
    }
}
</code>```

So we have three ways of error handling. The most specific thing in all this stuff is that each operation can fail, because it depends on a device.

Our team think of using out parameters, because of unhandled exceptions propagation fear. The other reason, connected with the fear, is that we will have to cover all calls by try\catch blocks to stop to be afraid, but such a code will be pretty ugly.

What pros and cons do you see and what could you advice?

Body:
The fear with exception can be eased by learning proper exception handling programming style (and also general error handling techniques).

Proper error handling (applicable to all mechanisms, and particular applicable to exception handling) requires careful reasoning as to the consequences and interpretation of each failed operation. Such reasoning entail:

After encountering an error, which line of code will it execute next?

After encountering an error, what does it say about the current state of the device?

Can the device resume normal operation?

Does the device need a reset?

Does the human user need to be notified?

After encountering an error, is the program state still consistent?

Should the program do some cleanup to restore the program state's consistency?

This reasoning can be extended to any programming black-boxes such as a third-party library.

Code example.

To ensure that every successful call to QueryStatusStart is followed up with a call to QueryStatusFinish with other calls in between:

bool queryStatusStarted = false;
try
{
    // throws exception if fails
    device.QueryStatusStart();

    // this line is not executed unless the previous line succeeded.
    queryStatusStarted = true;

    // might throw exception
    device.MakeMoreQueryStatusCalls();
}
finally
{
    // Whether or note MakeMoreQueryStatusCalls() throws an exception,
    // we will reach here. Hence we can restore the device to a
    // known state.

    if (queryStatusStarted)
    {
        device.QueryStatusFinish();
    }
}

In general programming, status cleanup methods (such as
the QueryStatusFinish method above) should not
throw exception (because throwing an exception in a catch{}
or finally{} block will indeed cause the uncaught exception
problem you feared.

However, when dealing with a physical device, there is a
need to interpret what a failed cleanup (restoration) means:

Device has disconnected

Device has malfunctioned and require human intervention (such as a power reset)

In either case, the program will not be able to continue its
normal operation. The correct way to handle this situation varies
from case to case.


问:
Will high reputation in Stack Overflow help to get a good job?
In a post, Joel Spolsky mentioned that 5 digit Stack Overflow reputation can help you to earn a job paying $100k+. How much of that is real?

Would anyone like to share their success in getting a high paid job by virtue of their reputations on Stack Exchange sites?

I read somewhere that, a person got an interview offer from Google because a recruiter found his Stack Overflow reputation to be impressive. Anyone else with similar stories?

答:
I've gotten job offers before solely based on participation in online forums. The way I see it, it doesn't automatically get you hired, but it can be a way to get noticed.

However, I've been at my first and only job for exactly 6 years today, and am not planning to jump ship. Therefore, I don't participate in online forums to pad my resume. I do it to help people and to check whether I really am as clever as I think I am ;)

I don't think participation in stackoverflow is a particularly efficient way to get an "in" with prospective employers. I can think of lots of better ways to make myself more "marketable", if I wanted to do that. If marketability is your motivation to be here, you might as well not bother.


问:
Flat addressing vs. segmented addressing
Is flat addressing model generally superior to a segmented one? If so, why? If not, what instances would call for each over the other and why?

My understanding of memory models surrounds the IA32/x86-64 Architecture. So if you give architecture specific examples, they will be most helpful if kept relevant to that.

答:
Segmented addresses allow a denser and more efficient use all CPU resources.  All those meaningless zeros in a 64 bit address are "unnecessary" and consume resources - data paths must be wider, adders have to have more bits, and memories have to be bigger to hold all the redundant zeros.

Back in the stone age that was very important.  The PDP-8 (my first real machine) packed everything into a 12-Bit "word", a 4K word address space, and a 128 word page size.  Despite these extreme limitations, you could run a timesharing system on one.

These days CPU resources are not so precious, but not entirely irrelevant.  You could probably pack a pdp-8 into a computer the size of a grain of sand.  I'm sure the NSA has one on order.


答:
I don't see that using error codes is going to gain you anything over exceptions.  It's just as easy to miss checking an error code, and then what?

Also, consider the following example:

```<code>public void CallProvider2() {
    var provider = new Provider2();

    Result result;
    string serialNumber = provider.GetSerialNumber(out result);
    if (result.ResultCode != 0) {
        //error handling
        switch(result.ResultCode)
        {
            case 123:
            break;
            //more cases
            default:
                //what now?
            break;
        }
    }
    //success flow
}
</code>```

The above is how you might handle errors, and the "default" case would catch unchecked error codes and would be the equivalent of an unhandled exception.  It would be worthwhile to ask what should be done if that case is ever reached.  You can't continue, but you've got to safely exit that method or what?  Are you just going to return the Result object all the way up the stack and check if ResultCode !=0 everywhere?  Might as well stick to exceptions.

Other benefits of exceptions to consider:

1) You get a stack trace automatically, which can be enormously useful in debugging.

2) If you need to handle an error further up the call stack, exceptions propagate upwards automatically.  You can also handle and rethrow them.  In the ResultCode examples you'd have to write additional code to pass them around if needed.

3) .NET runtime projects have some variation of an UnhandledException event you can subscribe to and do some centralized error logging.  Even if your app goes down, you can still get some information about why.  The plumbing to do that is already built in, you just have to attach to it.

4) An app crash from an unhandled exception, while undesirable, is USEFUL.  No one can mistake that something went wrong.

Body:
I don't see that using error codes is going to gain you anything over exceptions.  It's just as easy to miss checking an error code, and then what?

Also, consider the following example:

public void CallProvider2() {
    var provider = new Provider2();

    Result result;
    string serialNumber = provider.GetSerialNumber(out result);
    if (result.ResultCode != 0) {
        //error handling
        switch(result.ResultCode)
        {
            case 123:
            break;
            //more cases
            default:
                //what now?
            break;
        }
    }
    //success flow
}

The above is how you might handle errors, and the "default" case would catch unchecked error codes and would be the equivalent of an unhandled exception.  It would be worthwhile to ask what should be done if that case is ever reached.  You can't continue, but you've got to safely exit that method or what?  Are you just going to return the Result object all the way up the stack and check if ResultCode !=0 everywhere?  Might as well stick to exceptions.

Other benefits of exceptions to consider:

1) You get a stack trace automatically, which can be enormously useful in debugging.

2) If you need to handle an error further up the call stack, exceptions propagate upwards automatically.  You can also handle and rethrow them.  In the ResultCode examples you'd have to write additional code to pass them around if needed.

3) .NET runtime projects have some variation of an UnhandledException event you can subscribe to and do some centralized error logging.  Even if your app goes down, you can still get some information about why.  The plumbing to do that is already built in, you just have to attach to it.

4) An app crash from an unhandled exception, while undesirable, is USEFUL.  No one can mistake that something went wrong.


答:
A bug is not technical debt.  Technical debt is skimping on quality, not the absence of it.  Software should not be delivered with bugs in it in the first place.  You know, that whole working software over comprehensive documentation thing.

The biggest offenders of technical debt are "temporary bug fixes", you know the ones you put into to pass the test and get the story accepted  The ones that that you have promised yourself you will refactor later, but then never do.  As these temporary fixes, patches and other things accumulate, the code becomes unnecessary cluttered, difficult to update and test and in general is a nightmare, but it still does it's job.

For support of this opinion, I went straight to the source, Ward Cunningham.  Regarding this, Ward did a good interview a while back with Capers Jones, it's worth a watch.

Technical Debt Debate, with Ward Cunningham & Capers Jones

Another article worth a read is by Martin Fowler

Martin Fowler on Technical Debt

Within Martin's article, please find the link to the original mention of technical debt by Ward Cunningham, from OOPSLA92:

The WyCash Portfolio Management System

A quote from the above article:

Although immature code may work fine and be completely acceptable to
  the customer, excess quantities will make a program unmasterable,
  leading to extreme specialization of programmers and finally an
  inflexible product. Shipping first time code is like going into debt.

In the end, Technical Debt may have come to include bugs for some folks, and I guess that's fine.  I just don't think that was the original intention.

Title: Are bugs part of technical debt?


问:
Does "cc", "vv", "^^" have a special meaning in code?
Occasionally in code at GitHub I see tags "cc", "vv" and "^^".  Do these have any special meaning?

Example:

```<code>// cc MaxTemperatureMapper Mapper for maximum temperature example
// vv MaxTemperatureMapper
import java.io.IOException;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

public class MaxTemperatureMapper
  extends Mapper<LongWritable, Text, Text, IntWritable> {

{snip}

}
// ^^ MaxTemperatureMapper
</code>```

From https://github.com/tomwhite/hadoop-book/blob/master/ch02/src/main/java/MaxTemperatureMapper.java

答:
I've not seen this before.  It is certainly not part of the Java standards.

I suspect it is something to do with the electronic version of the book that those example files belong to; i.e. some publisher-specific markup for creating an index for the example code.

Ignore it :-)


答:
In my opinion, it really doesn't matter whether you say that bugs are part of technical debt ... or not.

The plain fact is that existing bugs represent extra work that may need to be performed in the future, either to fix them or to work around them.

Technical debt (as the label is typically used) also represents extra work that may need to be performed in the future ... one way or another.

So whether you say known (or unknown) bugs are technical debt ... or not ... is really just a matter of definitions.  And since there is no authoritative definition1 of "technical debt", the whole discussion is kind of pointless.

As Lewis Carroll wrote:

'When I use a word,' Humpty Dumpty said, in rather a scornful tone, 'it means just what I choose it to mean — neither more nor less.'.

That's actually how natural language works.  Words mean what people think they mean.  Dictionary definitions and so on merely document the way that words are used, and they are not necessarily accurate documentation.  If your Scrum Master wants to refer to known bugs as technical debt, who is to say that he is "wrong"?

1 - Quoting people such as Ward Cummingham and Caper Jones does not help either.  At best it tells us what they mean (or meant) when they use (used) the phrase.  They don't "own" the phrase.  While they are undoubtedly authorities on these issues, this is still just their opinion.

Title: Are bugs part of technical debt?


问:
Explanation of the definition of interface inheritance as described in GoF book
I am reading the first chapter of the Gof book. Section 1.6 discusses about class vs interface inheritance:

Class versus Interface Inheritance

It's important to understand the difference between an object's class
  and its type. An object's class defines how the object is
  implemented.The class defines the object's internal state and the
  implementation of its operations.In contrast,an object's type only
  refers to its interface--the set of requests on which it can respond. An
  object can have many types, and objects of different classes can have
  the same type.

Of course, there's a close relationship between class and type. Because
  a class defines the operations an object can perform, it also defines
  the object's type . When we say that an object is an instance of a
  class, we imply that the object supports the interface defined by the
  class.

Languages like c++ and Eiffel use classes to specify both an object's
  type and its implementation. Smalltalk programs do not declare the
  types of variables; consequently,the compiler does not check that the
  types of objects assigned to a variable are subtypes of the variable's
  type. Sending a message requires checking that the class of the
  receiver implements the message, but it doesn't require checking that
  the receiver is an instance of a particular class.

It's also important to understand the difference between class
  inheritance and interface inheritance (or subtyping). Class inheritance
  defines an object's implementation in terms of another object's
  implementation. In short, it's a mechanism for code and representation
  sharing. In contrast,interface inheritance(or subtyping) describes when
  an object can be used in place of another.

I am familiar with the Java and JavaScript programming language and not really familiar with either C++ or Smalltalk or Eiffel as mentioned here. So I am trying to map the concepts discussed here to Java's way of doing  classes, inheritance and interfaces.

This is how I think of of these concepts in Java:

In Java a class is always a blueprint for the objects it produces and what interface(as in "set of all possible requests that the object can respond to") an object of that class possess is defined during compilation stage only because the class of the object would have implemented those interfaces. The requests that an object of that class can respond to is the set of all the methods that are in the class(including those implemented for the interfaces that this class implements).

My specific questions are:

Am I right in saying that Java's way  is more similar to C++ as described in the third paragraph.

I do not understand what is meant by interface inheritance in the last paragraph. In Java interface inheritance is one interface extending from another interface. But I think the word interface has some other overloaded meaning here. Can some one provide an example in Java of what is meant by interface inheritance here so that I understand it better?

答:
Java classes are similar to C++ as described in the third paragraph.  Java interfaces are a different concept.

In Java, a class implicitly specifies both an interface in the GoF sense and the implementation.  By contrast a Java interface explicitly specifies an interface in the GoF sense and doesn't specify an implementation.  In both cases inheritance implies interface inheritance.  Only in the case of class inheritance does it imply implementation inheritance.

For a better example of the distinction, I highly recommend learning just enough Ruby to understand how a class can use method_missing to proxy off of an unrelated object.  This provides a very explicit example of interface inheritance without implementation inheritance.  (Bonus, Ruby's OO model is the same as Smalltalk's while having a more familiar syntax, which gives you a leg up on the rest of the book.)


答:
Yes, Java classes are similar to C++ classes in this regard.

Yes, in this case, interface doesn't really mean interface language construct present in Java and C#. In this case it has more abstract meaning. I think you can equate it to public methods and fields, that can be called on the object.

Class inheritance here means standard subtyping, where child class inherits behavior of it's parent. Interface inheritance is much more related to polymorphism and virtual method calls. It means child class can "accept and respond to messages" that parent can accept and respond to. The whole "describes when an object can be used in place of another" is basically definition of subtype polymorphism.

Title: Explanation of the definition of interface inheritance as described in GoF book

Body:
I am reading the first chapter of the Gof book. Section 1.6 discusses about class vs interface inheritance:

Class versus Interface Inheritance

It's important to understand the difference between an object's class
  and its type. An object's class defines how the object is
  implemented.The class defines the object's internal state and the
  implementation of its operations.In contrast,an object's type only
  refers to its interface--the set of requests on which it can respond. An
  object can have many types, and objects of different classes can have
  the same type.

Of course, there's a close relationship between class and type. Because
  a class defines the operations an object can perform, it also defines
  the object's type . When we say that an object is an instance of a
  class, we imply that the object supports the interface defined by the
  class.

Languages like c++ and Eiffel use classes to specify both an object's
  type and its implementation. Smalltalk programs do not declare the
  types of variables; consequently,the compiler does not check that the
  types of objects assigned to a variable are subtypes of the variable's
  type. Sending a message requires checking that the class of the
  receiver implements the message, but it doesn't require checking that
  the receiver is an instance of a particular class.

It's also important to understand the difference between class
  inheritance and interface inheritance (or subtyping). Class inheritance
  defines an object's implementation in terms of another object's
  implementation. In short, it's a mechanism for code and representation
  sharing. In contrast,interface inheritance(or subtyping) describes when
  an object can be used in place of another.

I am familiar with the Java and JavaScript programming language and not really familiar with either C++ or Smalltalk or Eiffel as mentioned here. So I am trying to map the concepts discussed here to Java's way of doing  classes, inheritance and interfaces.

This is how I think of of these concepts in Java:

In Java a class is always a blueprint for the objects it produces and what interface(as in "set of all possible requests that the object can respond to") an object of that class possess is defined during compilation stage only because the class of the object would have implemented those interfaces. The requests that an object of that class can respond to is the set of all the methods that are in the class(including those implemented for the interfaces that this class implements).

My specific questions are:

Am I right in saying that Java's way  is more similar to C++ as described in the third paragraph.

I do not understand what is meant by interface inheritance in the last paragraph. In Java interface inheritance is one interface extending from another interface. But I think the word interface has some other overloaded meaning here. Can some one provide an example in Java of what is meant by interface inheritance here so that I understand it better?


问:
Wikipedia confusion about ExtJS
I'm looking at the wiki on ExtJS, the wiki on List of rich Internet application frameworks, and the wiki on Comparison of web application frameworks. I'm confused. The first line of the ExtJS wiki page says:

Ext JS is a pure JavaScript application framework for building interactive web applications[1] using techniques such as Ajax, DHTML and DOM scripting.

So I assume it's a web app framework.
But in the right hand side summary box it says:

Type:       JavaScript library

Is ExtJS a web app framework or a Javascript library or both? (Can it be both?)

ExtJS is also missing from the web app framework lists...

Thanks for reading

答:
A framework keeps control of the application flow and makes calls to your code. A library (vs a framework) is something your code calls when needed and your code is in control of the flow.

What makes this interesting is that anything that exposes an API is a library in the broader sense. This essentially makes everything a library.

This puts ExtJS in the framework camp. But ExtJS is also a library, since it is an api.

Title: Wikipedia confusion about ExtJS


答:
The top reason you would use ASP.NET MVC over ASP.NET WebForms is testability. Sure you can kind of unit test WebForms but this requires mocking frameworks and a lot pain. The second reason is MVC does make it a bit easier to separate concerns.  This can provide a great deal of code reuse and make your code loosely coupled.  This does not mean it's impossible to do the same in ASP.NET with patterns like MVP.

The downside of MVC is that you lose a lot of the functionality and that has been built into WebForms over the past decade (well almost).  MVC has come a long way since its inception to provided similiar features.

As far as performance, does anyone have proof one way or another of which tech is "faster"?

I don't think one is better than the other. I do really like the MVC framework and have used it with great success but I always make sure that I choose the tech that matches the project.

Title: Why would you use MVC over Web Forms?

Body:
Recently an architect described our company as offering a Rolls-Royce solution (MVC) when all he needed was a Toyota (Web Forms).

I'm curious to find out what you think about web forms vs MVC as an architectural choice.


答:
Strictly speaking, the answer to your question is No.

Technical debt can (and probably will) lead to bugs, but concluding that any bug is the result of technical debt is putting an interpretation between two facts: there's a bug and there's technical debt (assuming that can be concluded as fact).

If your Scrum Master is stating 'as a theory' that bugs are the result of technical debt, he is cutting corners. If he is saying this about specific bugs that keep re-appearing he may well be right - we cannot see the code quality from here ;-)

He may also have an ongoing complaint about people not listening to him about the technical debt, and therefore labeling every bug as technical debt, but now I'm speculating.

Title: Are bugs part of technical debt?


问:
Should multi-threading be used for tasks which does not involve IO operation?
I was reading a book on OS and got confused between different terminologies.
I hope i will get my doubt cleared here.
These questions might be very basic for some experts, but i find this platform best suitable for such clarifications.

Processes are run by CPU and this whole operation is managed by OS.
For Single core CPU, at any instant only one process will be running.
CPU saves the state of a process to Process Control Block and starts running another process which was waiting and this switching is so fast that it feels like all processes are running simultaneously.

Need of different threads in a process was felt to get more fine-grained control over process , that means if process is waiting because of some I/O bound operation then even if this process is selected by CPU, it will not do anything.

So, if multiple threads are running under one process, then if one thread takes care of I/O activity , other threads can do some real computation, provided this process is selected by CPU.

Here are my questions:
Is Multi-threading effective only if task involved I/O activity?
Why is Multi-threading preferred over Multi-processing ? (is it because threads will share same memory space? )

Why Multi-core processors are better for multi-threading? (I think they will be better even if you don't use multi-threading, why so excitement in name of multi-threading?). And anyway threads in different processes will not share same memory, so two threads running in different processes on different cores are like running different processes. It is just that they will be parallel, and the real parallel, not the pseudo parallel.

答:
There are several reasons why people started using threads besides doing I/O. One of the reasons is that it is supposedly easier to program if you are used to a single-threaded world. Working with lots of I/O in a single process in the old times would mean creating very elaborate state machines that were difficult to debug and understand. Also, if you do such a state machine you have to break-up your computations into small pieces since a long computation can make your application unresponsive. The old Netscape Navigator was done like that.

Different threads can usually use different cores, so if you have CPU-bound operations without much I/O those operations can run in a different core without blocking the rest of your application. It's the opposite of what you said, so I think what you are thinking of threads is what in some places is called green threads, i.e., threads that are not scheduled by the operating system. A piece of code runs until it gives up controle, i.e., performs I/O or yields.

Now, there are several reasons why people would sometimes prefer multithreading to multi-processing. Processes usually don't share memory, so lots of programming styles are not possible. Instead of updating a data structure in memory you have to send a message to another process and the other process has to interpret it. That's how many languages work today and they are great for many things, but it's a different programming style. Another reason is that processes are usually heavier and more resource-intensive than threads. You can have your application have hundreds of threads, but you usually can't have hundreds of processes.


问:
Are "Clean Code" practices really that clean and useful?
I am currently doing an internship in a large corporation and they are undergoing many changes in software delivery structure (moving to Agile).

In the past couple of months I have noticed this religious attachment to Clean Code practices and the book  being like a bible for the developers.

Now, one of the most important features of the clean code is self-explanatory code which is based on understandable naming and rigorous re-factoring.  This is followed by no commenting rule.

I understand that this clean code is a long term investment which will ease following code maintenance and improvement, but... is this really worth all this fuss?

Would anyone share their experience on Clean Code and any opinion whether I am just too conservative or it is just a temporary trend.

答:
I was originally writing a comment.  I'll try to give less of an answer than perspectives to consider.  However, I absolutely endorse "Clean Code" practices like understandable naming and refactoring.

I've always disliked the no comments rules, as there are cases where comments are necessary to prevent future code breakage.  They normally should be restricted to what is being done and why.  Use them sparingly when the code is doing something unexpected, or an algorithm needed to be replaced.

Consider productivity when you are reading or maintaining code.  In the lifetime of the code, this may be more important than productivity when writing the code.  Will these practices help productivity in these tasks?

With experience, these practices should become ingrained, and less of a productivity killer.  Choosing the right name may take longer because you are clarifying what the code needs to do.  (This clarification may make coding and debugging go faster.) Does this result in code that does only what is require or that has less bugs?  What effect does this have on productivity?

The time taken in choosing the right method name will likely pay off immediately in better understanding what the method's purpose is.  Compare the method names "iterateOverCustomers" to "locateActiveCustomers".  Which one conveys the intent of the function?  Which one will be easier to refactor if necessary?


答:
A flat memory model is generally easier for people to understand, because it is possible to construct a simple mapping between addresses and numbers. This makes it possible to mentally model the address space as a large array and addresses as indices into that array.
In a segmented memory model, this mental image of the address space only works within a segment, but not between segments. So far, I have not found a mental model that can accurately describe a segmented memory model.

OTOH, a segmented memory model is far superior in preventing buffer overflows. The size of a segment is not fixed, but can be determined at runtime, so it is possible to allocate your buffers in dedicated segments that are sized exactly right for the buffer contained therein. Any attempt to go outside the buffer would immediately result in an error, because you are forming an illegal address. This is not possible with a flat memory model, because you might be addressing an unrelated variable that happens to be located adjacent to the buffer.

The reason that the flat memory model is used so much more probably comes from several factors:

The better understanding by programmers

On the x86 (including IA32) architecture, pointers within a segment are smaller and more efficient that pointers that can refer to different segments. This resulted in near and far pointers (which were a mess to work with) and a wish to keep as much as possible within one segment. In fact, IA32 has a segmented memory model, but in practice, only a single segment is ever used, giving it the appearance of a flat memory model.

Most processors with a segmented memory model (including the x86 architecture) did not support enough different segments to really take advantage of the fact that one segment per buffer is beneficial for security.

As a side note, it can be argued that the Java VM uses a segmented memory model, where each Java object occupies its own segment.

Title: Flat addressing vs. segmented addressing

Body:
Is flat addressing model generally superior to a segmented one? If so, why? If not, what instances would call for each over the other and why?

My understanding of memory models surrounds the IA32/x86-64 Architecture. So if you give architecture specific examples, they will be most helpful if kept relevant to that.


答:
I understand that this clean code is a long term investment which will ease following code maintenance and improvement, but... is this really worth all this fuss?

Absolutely.

Re-factoring is very important, but spending 75% of your time moving the methods and spending loads of time to decide its proper title does not seem to be that productive.

Sure, but consider that the large company probably has years or decades of bad code to clean up. It's going to take a lot of time and effort to do that.

The main thing to realize is that you're both right. "clean code" is very important, and Clean Code is a universally respected way to get there. Since the company has just started along the path, they're going to be beholden to the book more than a group that has more experience. Once they've done it for a short while, they'll begin to learn what works and what doesn't. Once they understand that better, they'll (hopefully) follow a more pragmatic  and natural approach that maintains clean code, but doesn't lead to 70 char function names.

Title: Are "Clean Code" practices really that clean and useful?

Body:
I am currently doing an internship in a large corporation and they are undergoing many changes in software delivery structure (moving to Agile).

In the past couple of months I have noticed this religious attachment to Clean Code practices and the book  being like a bible for the developers.

Now, one of the most important features of the clean code is self-explanatory code which is based on understandable naming and rigorous re-factoring.  This is followed by no commenting rule.

I understand that this clean code is a long term investment which will ease following code maintenance and improvement, but... is this really worth all this fuss?

Would anyone share their experience on Clean Code and any opinion whether I am just too conservative or it is just a temporary trend.


问:
Is it fair to call a database or a document a "Model", as in Model/View/Controller?
Part of my job is working on line-of-business applications built around client-side databases, such as Access or FoxPro.  Other times these local LOBA's have direct document access, such as an exact one-to-one mapping between a logical object an an XML node or references to bookmarks in Word Documents or ranges Excel spreadsheets.

While the code is about as messy as one would expect, it's usually fairly stable and the platforms these applications are built upon all have one thing in common: they translate program data to physical storage directly and transparently, from the programmer's point of view.

Would it be fair to refer to the database or document in one of these LOBA's as a "Model", when referring to the Model/View/Controller separation of concerns?  Or would it be improper to call separation of UI and business-logic MVC unless we make intermediate objects that in turn map to either the UI or the database?

答:
MVC is a design pattern.

They (design patterns) are not meant to restrain you in how they are used and/or implemented. They are supposed to be a communication mechanism that allows you to convey ideas about your application to other programmers (not an implementation).

And though normally I would expect the model to be more than just data (as the view needs to be updated when the model changes). But as a documentation or description processes I would be OK with you referring to the "Data" as the model as long as it helps you explain how the system works.


问:
What is the difference between a Future and a Promise?
What is the difference between a Future and a promise? (In Akka and Gpars.)

They look the same to me as both block and return the value of the future when get is called and a promise is to get the result of a future.

答:
I'll talk about Akka/Scala, because I'm not familiar with Gpars nor with Akka/Java.

In Scala 2.10, which includes the relevant part of Akka in the standard distribution, a Future is essentially a read-only reference to a yet-to-be-computed value.  A Promise is a pretty much the same except that you can write to it as well.  In other words, you can read from both Futures and Promises, but you can only write to Promises.  You can get the Future associated with a Promise by calling the future method on it, but conversion in the other direction is not possible (because it would be nonsensical).


答:
According to wikipedia, they are the same concept:

In computer science, future, promise, and delay refer to constructs used for synchronizing in some concurrent programming languages. They describe an object that acts as a proxy for a result that is initially unknown, usually because the computation of its value is yet incomplete.

Some libraries may choose to call them one way, some may choose to call them another. And each time, they may be implemented in different flavors. Some libraries may choose to use these synonyms to distinguish different flavors. While I would argue that this is a bad choice (because evidently it confuses people), this link suggests that in Scala this common practice.

As @Ptharien's Flame suggested, in Scala a Future is a read-only operation, while a Promise gives you the ability to yield a result (or failure) for the operation it represents.

A Promise is thus best used by the code responsible to carry out the operation to propagate the result, while a Future is used to expose it to client code, that will in turn await the result. But again, please note that this distinction is Scala specific and may confuse outsiders.

Title: What is the difference between a Future and a Promise?

Body:
What is the difference between a Future and a promise? (In Akka and Gpars.)

They look the same to me as both block and return the value of the future when get is called and a promise is to get the result of a future.