问:
How should pagination allowing links to arbitrary pages be handled in a RESTful API?
How should a RESTful API handle pagination in the situation where a client may want the ability to jump to arbitrary pages? Let's assume we are using the Link header in the way the GitHub API does:

```<code>Link: <https://api.github.com/user/repos?page=3&per_page=100>; rel="next", <https://api.github.com/user/repos?page=50&per_page=100>; rel="last"
</code>```

The API, like many others, returns links to the next page, previous page, first page and last page. This does not account for the relatively common use-case of providing on the client-side links to a range of pages, and not just the next/previous/first/last. If, for example, the request returns 100 pages worth of results, the client may want to allow the ability to jump to an arbitrary page. How should this be done while adhering closely to the concepts of REST?

Some possible options:

Just let the client infer the other links. You have the first and last page, it may be a reasonable assumption to modify the link to obtain the other pages. This seems to go against HATEOAS (which is always the principle of REST that seems to cause problems).

Return a link to every page. This seems unwieldy as the potential number of pages could be high.

Return a link to a small range of pages (perhaps 2 either side of the current page). This seems like a relatively sensible approach but it limits the options clients have when it comes to displaying pagination information.

答:
##The problem is the URL is not RESTful in the GitHub example:

I would rather see actual URL that represent the resource exclusively. It is not that hard if you put a little thought into it.

###To be truly RESTful the URI should be a resource identifier and nothing else

Parameters make it RPC over HTTP which is the opposite of the REST paradigm.

```<code>http://example.com/{user_id}/posts/first
http://example.com/{user_id}/posts/09/previous
http://example.com/{user_id}/posts/10
http://example.com/{user_id}/posts/11
http://example.com/{user_id}/posts/12
http://example.com/{user_id}/posts/13
http://example.com/{user_id}/posts/14
http://example.com/{user_id}/posts/15/next
http://example.com/{user_id}/posts/last
</code>```

Using parameters as part of the identifier is a bad practice, regardless of who is doing it.

```<code>http://example.com/{user_id}/posts/09/to/04/ <- previous
http://example.com/{user_id}/posts/14/to/19/ <- next
</code>```

No parameters and more concise and self describing as well.

###If the list is totally client side then fragment identifiers would be the correct choice:

Since fragments are never set to the server on requests they are totally client side references. Fragment Identifier is considered a sub-location of the resource, which semantically previous and next are sub-locations of posts/

The specific example of RFC 5147 is applicable here http://example.com/document.txt#line=10,20

RFC7233 specifies the binary RANGE header. That is a very compelling argument for a custom PAGINATION_RANGE header using the RFC5988 Link Header in the same spirit.

```<code>http://example.com/{user_id}/posts/first
http://example.com/{user_id}/posts/09/#previous=5
http://example.com/{user_id}/posts/10
http://example.com/{user_id}/posts/11
http://example.com/{user_id}/posts/12
http://example.com/{user_id}/posts/13
http://example.com/{user_id}/posts/14
http://example.com/{user_id}/posts/15/#next=5
http://example.com/{user_id}/posts/last
</code>```

###Fragments do not reload the page but do create history:

So you get correct forward/back button behavior for free!

Body:
##The problem is the URL is not RESTful in the GitHub example:

I would rather see actual URL that represent the resource exclusively. It is not that hard if you put a little thought into it.

###To be truly RESTful the URI should be a resource identifier and nothing else

Parameters make it RPC over HTTP which is the opposite of the REST paradigm.

http://example.com/{user_id}/posts/first
http://example.com/{user_id}/posts/09/previous
http://example.com/{user_id}/posts/10
http://example.com/{user_id}/posts/11
http://example.com/{user_id}/posts/12
http://example.com/{user_id}/posts/13
http://example.com/{user_id}/posts/14
http://example.com/{user_id}/posts/15/next
http://example.com/{user_id}/posts/last

Using parameters as part of the identifier is a bad practice, regardless of who is doing it.

http://example.com/{user_id}/posts/09/to/04/ <- previous
http://example.com/{user_id}/posts/14/to/19/ <- next

No parameters and more concise and self describing as well.

###If the list is totally client side then fragment identifiers would be the correct choice:

Since fragments are never set to the server on requests they are totally client side references. Fragment Identifier is considered a sub-location of the resource, which semantically previous and next are sub-locations of posts/

The specific example of RFC 5147 is applicable here http://example.com/document.txt#line=10,20

RFC7233 specifies the binary RANGE header. That is a very compelling argument for a custom PAGINATION_RANGE header using the RFC5988 Link Header in the same spirit.

http://example.com/{user_id}/posts/first
http://example.com/{user_id}/posts/09/#previous=5
http://example.com/{user_id}/posts/10
http://example.com/{user_id}/posts/11
http://example.com/{user_id}/posts/12
http://example.com/{user_id}/posts/13
http://example.com/{user_id}/posts/14
http://example.com/{user_id}/posts/15/#next=5
http://example.com/{user_id}/posts/last

###Fragments do not reload the page but do create history:

So you get correct forward/back button behavior for free!


问:
How do I model this relationship so that it is valid by construction?
Imagine a device class that represents a physical real world mobile device, with fields like Enabled, Platform, Model IMEI, etc. Then, an operation class, which is something that needs to be done to a certain device, like DeviceEnablementOperation or LockOperation. This is a 'one device to many operations' relationship, and an operation cannot exist without being related to an existing device. Can I model this in such a way that the system will not allow certain types of operations to devices with certain platforms? For example, an Android device would not allow a DeviceEnablementOperation attached to it, while a Windows Phone device would.

Our current modeling started out considering only Android devices. At the time, we created the concept of operations as a poor man's event source, so that we could track what was done against a certain device via our API. Later on, we started supporting iOS devices too, and we introduced the Platform field using an enumeration class to differentiate them, like this:

public enum PlatformType : short
{
    ///
    /// Device is an Android.
    ///
    Android = 0,

    ///
    /// Device is an Windows platform.
    ///
    Windows = 1,

    //// Can not place the name iOS.

    ///
    /// Device is an iOS platform.
    ///
    Ios = 2,
}
```

<p>At that point in time, the requirements were being met correctly, but now we need to restrict certain types of operations to certain platforms. The current model does not automatically restrict this, so the current implementation considers a hardcoded list of supported operations for each platform, and uses this to reject the creation of some operations to certain devices.</p>

<p>What I'd like to do is change the modelling so that this restriction is more robustly enforced. I thought about using inheritance and creating <code>AndroidDevice</code>, <code>IosDevice</code> and <code>WindowsPhoneDevice</code> classes, but I still fail to see how I could restrict the relationship with operations themselves to cover this requirement. A device has operations, but not all devices support all operations.</p>

<p>The modelling for the operations themselves is very straightforward inheritance, like this:</p>

<pre class="lang-cs prettyprint-override"><code>public abstract class Operation
{
    protected Operation()
    {
        this.Logs = new List<OperationLog>();
    }

    public DateTime? CreationDate { get; set; }

    public virtual Device Device { get; set; }

    public int DeviceId { get; set; }

    public OperationStatus GeneralStatus { get; set; }

    public int Id { get; set; }

    public DateTime? LastUpdate { get; set; }

    public ICollection<OperationLog> Logs { get; internal set; }

    public DateTime? ReceiveDate { get; set; }
}
</code>```

And then derived operation types, like the ones I mentioned:

public sealed class LockOperation : Operation
{
    ///
    /// Gets or sets a value indicating whether the device must be locked or not.
    ///
    public bool Lock { get; set; }

    ///
    /// Gets or sets the device's lock password.
    ///
    public string Password { get; set; }
}
```

<p>and</p>

<pre class="lang-cs prettyprint-override"><code>public sealed class EnablementOperation : Operation
{
    /// <summary>
    /// Gets or sets a value indicating whether the device should be enabled or disabled.
    /// </summary>
    public bool Enabled { get; set; }
}
</code>```

Is it possible to model this to better reflect the new requirement that I want? I'd somehow need a way to tell if a given operation is supported for a given device, and only allow the relationship to exist if the operation was supported.

I suppose I could try something using generics and inheritance on both the device and operation classes, for example:

public abstract class Device<TOperation>
{
    public ICollection<TOperation> Operations { get; set; }
    ...
}

public sealed class AndroidDevice : Device<AndroidOperation> {...}

public abstract class Operation {...}

public abstract class AndroidOperation {...}

public sealed LockOperation : AndroidOperation {...}
```

But this particular approach would need multiple inheritance to work, and since I'm using C# it is not possible. I could then try using interfaces to differentiate operations, but them I suspect it would be a problem when mapping this to a database later using an ORM.

I also can't really break everything into their own completely isolated classes, because I need the general concept of "devices that have operations", regardless of platform or operation type. That's why the base classes exist in our current model.

答:
How about adding interfaces for platform specific Operations? ie.

public interface IAndroidOperation : IOperation {}
public interface IIoSOperation : IOperation {}
```

<p>Then have the operations implement the interfaces they are good for</p>

<pre class="lang-cs prettyprint-override"><code>public class LockOperation : IAndroidOperation, IIoSOperation {}
</code>```

Then have the device only allow adding of the correct interface

public class AndroidDevice : Device
{
    public List<IAndroidOperation> Operations {get;,set;}
}
```

<p>Update:</p>

<p>you are right the exposure of the generic Operations is non trivial. There are a number of approaches. I have included a simple one below, which is not perhaps ideal. but does avoid having to make your own IEnumberable</p>

<pre class="lang-cs prettyprint-override"><code>using System.Linq;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject2
{
    public interface IOperation
    {
        void DoStuff();
    }
    public interface IAndroidOperation : IOperation { }
    public interface IoSOperation : IOperation { }

    public class LockOperation : IAndroidOperation
    {
        public void DoStuff(){}
    }

    public class BendOperation : IoSOperation
    {
        public void DoStuff() { }
    }
    public interface IDevice
    {
        IEnumerable<IOperation> GetOperations();
    }
    public abstract class Device<T> : IDevice where T : IOperation
    {
        public abstract List<T> Operations { get; set; }

        public IEnumerable<IOperation> GetOperations()
        {
            return this.Operations.Select(o => (IOperation)o);
        }
    }

    public class IoSDevice : Device<IoSOperation>
    {
        public override List<IoSOperation> Operations { get; set; }
    }

    public class AndroidDevice : Device<IAndroidOperation>
    {
        public override List<IAndroidOperation> Operations { get; set; }
    }

    public class TestMe
    {
        [TestMethod]
        public void test()
        {
            List<IDevice> devices = new List<IDevice>();
            AndroidDevice a = new AndroidDevice();
            IoSDevice i = new IoSDevice();

            devices.Add(a);
            devices.Add(i);

            LockOperation l = new LockOperation();
            BendOperation b = new BendOperation();

            a.Operations = new List<IAndroidOperation>();
            i.Operations = new List<IoSOperation>();

            a.Operations.Add(l); //ok
            //a.Operations.Add(b); //compilation error
            i.Operations.Add(b); // ok

            foreach (IDevice d in devices)
            {
                foreach (IOperation o in d.GetOperations())
                {
                    o.DoStuff();
                }
            }

        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How about adding interfaces for platform specific Operations? ie.

public interface IAndroidOperation : IOperation {}
public interface IIoSOperation : IOperation {}

Then have the operations implement the interfaces they are good for

public class LockOperation : IAndroidOperation, IIoSOperation {}

Then have the device only allow adding of the correct interface

public class AndroidDevice : Device
{
    public List<IAndroidOperation> Operations {get;,set;}
}

Update:

you are right the exposure of the generic Operations is non trivial. There are a number of approaches. I have included a simple one below, which is not perhaps ideal. but does avoid having to make your own IEnumberable

using System.Linq;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject2
{
    public interface IOperation
    {
        void DoStuff();
    }
    public interface IAndroidOperation : IOperation { }
    public interface IoSOperation : IOperation { }

    public class LockOperation : IAndroidOperation
    {
        public void DoStuff(){}
    }

    public class BendOperation : IoSOperation
    {
        public void DoStuff() { }
    }
    public interface IDevice
    {
        IEnumerable<IOperation> GetOperations();
    }
    public abstract class Device<T> : IDevice where T : IOperation
    {
        public abstract List<T> Operations { get; set; }

        public IEnumerable<IOperation> GetOperations()
        {
            return this.Operations.Select(o => (IOperation)o);
        }
    }

    public class IoSDevice : Device<IoSOperation>
    {
        public override List<IoSOperation> Operations { get; set; }
    }

    public class AndroidDevice : Device<IAndroidOperation>
    {
        public override List<IAndroidOperation> Operations { get; set; }
    }

    public class TestMe
    {
        [TestMethod]
        public void test()
        {
            List<IDevice> devices = new List<IDevice>();
            AndroidDevice a = new AndroidDevice();
            IoSDevice i = new IoSDevice();

            devices.Add(a);
            devices.Add(i);

            LockOperation l = new LockOperation();
            BendOperation b = new BendOperation();

            a.Operations = new List<IAndroidOperation>();
            i.Operations = new List<IoSOperation>();

            a.Operations.Add(l); //ok
            //a.Operations.Add(b); //compilation error
            i.Operations.Add(b); // ok

            foreach (IDevice d in devices)
            {
                foreach (IOperation o in d.GetOperations())
                {
                    o.DoStuff();
                }
            }

        }
    }
}


问:
is OOP the dominant programming model in real world?
Objects Never? Well, Hardly Ever

In the VIEWPOINT section of Communications of The ACM, I found an
interesting article entitled "Objects Never? Well, Hardly Ever".
It’s a radically different perspective than objects-first or objects-late. He suggests "objects-never" or maybe "objects-graduate school".

The author talked about OOP and made a question about how OOP is used
in real world programming environments. He thinks that OOP is not the
dominant programming model. For example, he claims, 70% of
programmings are done for Embedded Systems where OOP is not really
suited.

When some professors in universities wants to talk about the benefits
of OOP, they talk about code-reuse. As another example, again, he
claims, this is not the real case in real world. code-reuse is harder
than what's claimed in universities:

I claim that the use of OOP is not as prevalent as most people believe, that it is not as successful as its proponents claim, and, therefore, that its central place in the CS curriculum is not justified.

It's interesting for me to know how people in stack-overflow think
about this? Is OOP the dominant programming model from programmers'
point of view?

If I should choose/learn/use just one approach, is it OOP or not? why?

答:
In the VIEWPOINT section of Communications of The ACM

If you're interested in practical programming, the proceedings of ACM and the likes is the last source you want to read. These are often [pseudo]-scientific publications with no application in the real world. These are quite often unorthodox opinions made for publicity, for the writer to differentiate himself from the crowd and promote his own person.

I claim that the use of OOP is not as prevalent as most people believe, that it is not as successful as its proponents claim, and, therefore, that its central place in the CS curriculum is not justified.

I tend to disagree with your point. OOP is widely spread and works just fine. By the number OOP-based projects have likely surpassed developments done with other strategies (let's speak about modern time, 15-20 years).

However OOP is not a silver bullet. It works for some developments, doesn't work for others. Just like any other approach.

But one thing I need to mention is that a curriculum should communicate knowledge of different approaches. If it's OOP-based, it's wrong. If it's FP-based, it's wrong. It should cover them all or don't touch this topic altogether.

P.S. Why care about what is dominant and what is not? Just take what is suitable for the project at hand and leave the numbers to "researchers".

ContentLicense: CC BY-SA 2.5


答:
Whether or not OOP is the dominant programming model is irrelevant, simply put different models fit different cases.

There is no silver bullet.

What Moti Ben Ari is arguing about is an academic assertion, which is already meaningless. However, he states himself that he never found OOP to "make sense", clearly it does to thousands of developers and software engineers and has been used in many many systems...

But, really the point of my answer is this, what good is it to state that one model or another is dominant or not, is that then good rationale for blindly using it? Of course, it isn't.

Title: is OOP the dominant programming model in real world?

Body:
Objects Never? Well, Hardly Ever

In the VIEWPOINT section of Communications of The ACM, I found an
interesting article entitled "Objects Never? Well, Hardly Ever".
It’s a radically different perspective than objects-first or objects-late. He suggests "objects-never" or maybe "objects-graduate school".

The author talked about OOP and made a question about how OOP is used
in real world programming environments. He thinks that OOP is not the
dominant programming model. For example, he claims, 70% of
programmings are done for Embedded Systems where OOP is not really
suited.

When some professors in universities wants to talk about the benefits
of OOP, they talk about code-reuse. As another example, again, he
claims, this is not the real case in real world. code-reuse is harder
than what's claimed in universities:

I claim that the use of OOP is not as prevalent as most people believe, that it is not as successful as its proponents claim, and, therefore, that its central place in the CS curriculum is not justified.

It's interesting for me to know how people in stack-overflow think
about this? Is OOP the dominant programming model from programmers'
point of view?

If I should choose/learn/use just one approach, is it OOP or not? why?


问:
I believe my solution is better than my boss's, so should I ignore him?
I'm working with php and sql.

I think that my method of implementing functions is better than what my boss proposes. Just now he explained me how to do a check on a list of email addresses, and I do not like his idea. I proposed mine which is better and quicker to implement, but he disagreed.

Now I think I will go ahead and implement my idea, because his idea was not clear enough to me. Do you think he will be mad?

答:
It seems your in conflict over something, so you have to focus on being constructive.

If you sincerally do not believe in his solution you should find a constructive way to tell him how you feel about it. There are a few things to consider in this. Your responsible for your delivery, but his is responsible for the team's delivery. You will have to show that your interest is that of the teams delivery and your own (that these two align).

Make a list of pro's and con's with the two solutions and dicuss it with your boss in a constructive manner. Sometimes it easier to show that your or he is missing a key component of the solution with a list.

Try to understand what he wants, it's the end goal that is the purpose. If you get in conflict over this then your not focusing on the right goal.


答:
Having been "the boss" and, as it turned out, actually better than my staff in all cases bar one - yes, he will be mad - or annoyed or frustrated and in any case, quite possibly, right in the first place.

If you're genuinely better than him then you should be able to understand his proposed solution and to see why yours is better and then to explain why.

But you state:

because his idea was not clear enough to me

In which case you need to go back and understand what he wants and why and whether - as has been the case both in me making suggestions to my staff and my staff proposing solutions to me - you or he has missed something. But don't assume that he's wrong and you're right unless and until you understand what he's asking for and whether he's covering something you haven't thought of (yet).

Oh and in the one case - he's a better programmer but he's not so good a couple of steps back from the problem where I'm better and we had great fun working together for that very reason.

Title: I believe my solution is better than my boss's, so should I ignore him?

Body:
I'm working with php and sql.

I think that my method of implementing functions is better than what my boss proposes. Just now he explained me how to do a check on a list of email addresses, and I do not like his idea. I proposed mine which is better and quicker to implement, but he disagreed.

Now I think I will go ahead and implement my idea, because his idea was not clear enough to me. Do you think he will be mad?


问:
What's the most important feature of quality software?
This question is along the same lines as this one, but instead of talking about quality of code, I'm talking about the final product from the users' perspective. If you had limited time / budget, and could only guarantee one attribute of the software (other than the basic requirements) that take it from decent software to good quality software, what would you consider most important?

Is it having as few bugs as possible? An intuitive interface? Helpful error messages? Good technical support and documentation? If we don't want our software looking like cheap crap to our users, what should we always remember to include?

答:
Making it easy to improve. High quality software is built when you build it to allow you to cheaply take care of defects (UI/Performance/Crashes/etc).

Any software will have defects, so build so that improving quality is easy and low cost.

Everything else will just follow from this.


问:
Refactoring in domain driven design
I've just started working on a project and we're using domain-driven design (as defined by Eric Evans in Domain-Driven Design: Tackling Complexity in the Heart of Software.  I believe that our project is certainly a candidate for this design pattern as Evans describes it in his book.

I'm struggling with the idea of constantly refactoring.

I know refactoring is a necessity in any project and will happen inevitably as the software changes.  However, in my experience, refactoring occurs when the needs of the development team change, not as understanding of the domain changes ("refactoring to greater insight" as Evans calls it).  I'm most concerned with breakthroughs in understanding of the domain model.  I understand making small changes, but what if a large change in the model is necessary?

What's an effective way of convincing yourself (and others) you should refactor after you obtain a clearer domain model?  After all, refactoring to improve code organization or performance could be completely separate from how expressive in terms of the ubiquitous language code is. Sometimes it just seems like there's not enough time to refactor.

Luckily, SCRUM lends it self to refactoring.  The iterative nature of SCRUM makes it easy to build a small piece and change and it.  But over time that piece will get larger and what if you have a breakthrough after that piece is so large that it will be too difficult to change?

Has anyone worked on a project employing domain-driven design? If so, it would be great to get some insight on this one.  I'd especially like to hear some success stories, since DDD seems very difficult to get right.

Thanks!

答:
If you get something wrong in the Domain Model its important to correct it. In my experience we missed a bit in how the domain model connects to it's different entities when we implemented some of it.

What this resulted in was that people used to model in ways it wasn't inteded for and thus breaks other parts of the model to try to "get it to work".

As soon as you realise that there is something wrong in the domain model, change it as fast as possible. The longer it takes before you refactor it the harder it will be to change with respect to the users, whos mental models now are adapted.

Title: Refactoring in domain driven design


答:
As many answers already provided, I don't advise you to code a solution your lead hasn't approved. You first have to prove him that your solution is better in a constructive way. If he's a good manager and deeply thinks his solution is better than yours, you can expect from him to explain why. Don't forget that as manager, he may have other criteria than you to define what an efficient solution is. Maintainability or easiness of reading may be one of them.

Besides, if he's a good manager, it won't be a dishonor for him to choose your solution if you have objectively succeeded in proving that it is really better.

But at the end, even if you still disagree with him, don't deceive him; don't do something he will ignore. Team management is also based on trust and transparency so you could screwed up your relationship with and the team efficiency. And the team objectives should be your first priority.

If the situation occurs again and again, and his choices are always bad, he shouldn't stay your boss for a long time. If it's just occasional, don't be too overproud...


问:
How would you design a programming language?
If you were to design a programming language, how would you do it? What features would you put in? What would you leave out? Statically or dynamically typed? Strongly or weakly typed? Compiled or interpreted? Justify your answers.</p>

答:
If I had the time, I would design a localizable programming language that is based on Scala, so it would have most of its features, except probably for XML. My goal is to make a language that reads almost naturally in languages with a different structure than English, such as Arabic (my mother-tongue). I am thinking of the following features:

A pre-processor #lang directive, used to inform the pre-processor of the human language used for programming. For example: #lang ar would allow the use of the word فئة instead of class, عرف instead of def, and so on. The human-language-specific keywords would be defined in standard preprocessor files.

The pre-processor would remove some optional keywords whose sole purpose is to add clarity to the code. For example, it would remove "is composed of" in class MyClass is composed of { to become class MyClass {, and remove "as" in def MyMethod(x: Int) as { to become def MyMethod(x: Int) {. In some (human) languages, this would make the code much more easier to understand, especially for students.

The compiler would allow the use of prefix notation for property access. This might not make sense for most Latin-based language speakers, but for some other languages it makes perfect sense. For example, property access in Arabic is normally prefix, as in اعرض طول اسم محمد, which is equivalent to print(length(name(Mohammad))) in programming-English. (The parenthesis are for clarity.)

I believe that these minimal changes to the pre-processor and compiler would make programming much simpler to non-English speakers.


问:
What default features is Windows missing that are required for programmers?
What features is Windows missing that can improve the productivity of a programmer. I know a lot of people would want some features from Linux and OSX ported or being created for Windows as well. What is missing for you ?

An example would be the option to have multiple workspaces. When not having the possibility to use dual monitors that can come in handy.

答: Support for longer command line arguments. You'll quickly run into issues when building complex java solutions that doesn't use Microsofts build systems.</p>


问:
Is using YouTube a good, inexpensive solution to building a website that requires users to post videos?
I'm diving into web development after ten years of desktop development and I have an idea for a Rails website that will rely on users posting short videos (5 -15 mins) they've recorded.  The website will be ad-supported and probably won't generate enough revenue to support hosting video based on how expensive I understand it to be, so the idea I had was to allow users to specify a link to the video they recorded and have posted on Youtube.  This way, YouTube funds all the resources (storage, bandwidth, etc.) needed for the videos and I simply embed them in my website.  My questions are...

Is it worth the poor design choice to separate the user's content service provider (in this case, YouTube) from my website in order to save the money it would cost me to host the videos myself?

Is there an inexpensive way for me to host the videos myself if the answer to my first question is "No!"?

If it's not a bad idea, do you see any other potential problems with this approach?

I apologize if this question is absurd in any way, I'm still getting familiar with the workings of web businesses.  Thanks so much in advance for your wisdom, I'm going to continue researching my questions right now.

答:
Is it worth the poor design choice to separate the user's content service provider (in this case, YouTube) from my website in order to save the money it would cost me to host the videos myself?

It really depends on the purpose of your website. Being dependent on YouTube means being dependent on a service that you don't control. Although YouTube is an excellent service, you have no control over what they do to the videos or the users.

The fact that you will depend on a third party service in this way, will make your website less valuable. This is something to consider in case you would ever want to make a business out of your website.

However, if you're not that serious, YouTube will do just fine.

Is there an inexpensive way for me to host the videos myself if the answer to my first question is "No!"?

Probably not. First you'd need to build something that can receive them and transcode them to a format more suitable for your website. Next you'd have to host them somewhere, perhaps using Amazon S3 or a CDN.


答:
The most important feature is that the customer can do what he asked. That means that is not only fulfills basic requirements, but does so in a way that the customer can understand.

I guess we would call that "Usability", which then becomes the answer.

The rest, like looks and features, and bugs (withing reason) can be improved afterwards. If the customer can do what he asked, he is also usually going to be happy, and more likely to ask you to make these improvements.

A pretty software that doesn't help the customer do his job isn't gonna get you more work, in my experience.

Title: What's the most important feature of quality software?

Body:
This question is along the same lines as this one, but instead of talking about quality of code, I'm talking about the final product from the users' perspective. If you had limited time / budget, and could only guarantee one attribute of the software (other than the basic requirements) that take it from decent software to good quality software, what would you consider most important?

Is it having as few bugs as possible? An intuitive interface? Helpful error messages? Good technical support and documentation? If we don't want our software looking like cheap crap to our users, what should we always remember to include?


问:
What is proven as a good maximum length of a function?
Does function length affect the productivity of a programmer? If so, what is a good maximum number of lines to avoid productivity loss?

Since this is a highly opinionated topic please back up the claim with some data.

答: Most compilers do not mind a function's length. A function should be functional, but be both easy to understand, change and reuse to human beings. Choose a length that suits you best.</p>

ContentLicense: CC BY-SA 4.0


问:
How do I determine if customers have already received a newsletter?
The problem: When we were sending newsletters to customers, there was no way to confirm if the customer already received the mail. We have come up with two different approaches:

(Boss's Idea) Each time mail was being sent, do an INSERT in a db with the title of the newsletter being sent and the email address which is receving the email address. To ensure that any email address does not receive the same email twice, do a SELECT in the table and find the title of the newsletter being sent:

```<code>if (title of newsletter is found)
{
  check to see of the email we are sending mail to is already present. if it does, do not send mail
}
else
{
  send mail
}
</code>```

(My idea) create a column called unique and mark it as UNIQUE. Each time mail was being sent, concatenate email + newsletter id and record it in the UNIQUE row. The next time we do a "mysql_affected_rows" check to see if our INSERT was successful, we send the mail, else, there is already a duplicate and no need to send it.

Is either approach objectively superior? If yes, which one and why?

答: Your solution may be faster and typed with lesser code, but also is somewhat of a hack or workaround. It works only exactly for this problem. Think of later extension. What if you want later output all newsletters a customer got. In your solution it is a complicated select over a part of the UNIQUE-string. I personally would prefer the solution of your boss.</p>


问:
Suggestions for Programs to develop for learning
i wonder apart from those very simple hello world apps, what other programs should i try developing for learning. i am entering uni next year and wonder what kind of programs will be developed in that environment.

this is not really a language specific thing, but if you want to know what i use currently mainly

windows: C#/WPF - i studied java/vb etc in poly but i think C# is the way to go, maybe even F#

web: PHP/MySQL, Zend Framework/Doctrine, + HTML/CSS/JS(jQuery) of course. looking to try google app engine with python too.

for now, i am thinking of

todo lists

apps that integrate with api eg. twitter/tumblr which i use

text editor - i am currently trying to develop a text editor that uses markdown and generates html files for viewing (link to blog entry). not very pratical after i started developing it. cos when editing theres no formatting and in HTML format, i cannot edit directly

blog software (for web)

答:
I'm currently writing a regex parser/matcher and its teaching me a huge amount about parsing and finite state machines and regular expressions themselves, among other things. The reason I particularly think a regex parser is useful is because the regex language is small, and is fairly limited in what it can do.

Another thing I did was to write an interpreter for Ook!, which is a simple task, but once again, teaches you a ton.


答:
I prefer the boss solution because it's easier to comprehend.
I immediately understood it, while your own solution is less obvious.

For the people that will have to maintain/alter this in the future, this is important.

Title: How do I determine if customers have already received a newsletter?

Body:
The problem: When we were sending newsletters to customers, there was no way to confirm if the customer already received the mail. We have come up with two different approaches:

(Boss's Idea) Each time mail was being sent, do an INSERT in a db with the title of the newsletter being sent and the email address which is receving the email address. To ensure that any email address does not receive the same email twice, do a SELECT in the table and find the title of the newsletter being sent:

```<code>if (title of newsletter is found)
{
  check to see of the email we are sending mail to is already present. if it does, do not send mail
}
else
{
  send mail
}
</code>```

(My idea) create a column called unique and mark it as UNIQUE. Each time mail was being sent, concatenate email + newsletter id and record it in the UNIQUE row. The next time we do a "mysql_affected_rows" check to see if our INSERT was successful, we send the mail, else, there is already a duplicate and no need to send it.

Is either approach objectively superior? If yes, which one and why?


答:
Personally, I don't like reliance on UNIQUE constraints. I'd go the SELECT way your boss proposes. It's probably easier to read, too.

BTW, you have to know the rules:

The boss is always right

If the boss isn't right, apply rule #1


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
Don't get rid of short open tags, specially the echo one =(. This:

```<code><?=$myvar?>
</code>```

...is way better than this:

```<code><?php echo $myvar;?>
</code>```

Body:
Don't get rid of short open tags, specially the echo one =(. This:

<?=$myvar?>

...is way better than this:

<?php echo $myvar;?>


问:
Black box or white box testing - which do you do first?
On a very small team, where the black box and white box testing is done by the same person, which should the tester do first?</p>

答:
First do it white box testing.

Second go for Black box testing.

> Black Box Testing

I. The tester should check functional of the application, such Text box, Radio button, listbox, Command button,... etc.,,

II. The tester should check non functional of the application, such logo, Image, spelling,.. etc.,,

III. The tester should check entire flow of the application.

Note:
To check Positive and Negative conditions.

OwnerDisplayName: Narayanan

LastEditorDisplayName: Narayanan


问:
Is using ELSE bad programming?
I've often come across bugs that have been caused by using the ELSE construct.  A prime example is something along the lines of:

```<code>If (passwordCheck() == false){
    displayMessage();
}else{
    letThemIn();
}
</code>```

To me this screams security problem.  I know that passwordCheck is likely to be a boolean, but I wouldn't place my applications security on it. What would happen if its a string, int etc?

I usually try to avoid using ELSE, and instead opt for two completely separate IF statements to test for what I expect.  Anything else then either gets ignored OR is specifically handled.

Surely this is a better way to prevent bugs / security issues entering your app.

How do you guys do it?

答:
Then just replace them, </p>

```<code>If (passwordCheck == true)
{
     letThemIn();
}
else
{
     displayMessage();
}
</code>```

Title: Is using ELSE bad programming?

Body:
Then just replace them,

If (passwordCheck == true)
{
     letThemIn();
}
else
{
     displayMessage();
}


问:
How do you manage your knowledge base?
As programmers we have a lot of inputs:

Ebooks

Code snippets

Interesting emails

Documents

Web articles

Blog posts

StackOverflow questions

Podcasts
...

Which tools do you use to store, organize, search and consult all of this stuff?

Is there a silver bullet solution to handle this huge amount of data?

答:
Freemind

It does a great job of storing lots of ideas in a semantic hierarchical manner. Plus, any node can also be a link to a website. Learning how to completely manipulate the Mind Map using only keys is a must (including, adding meaningful color coding skills).

I use this in conjunction with Dropbox to make it the mind maps available on all my computers. I only wish the project had more development effort going into polishing it.

Title: How do you manage your knowledge base?


答:
The else block should always consist of what you want the default behaviour to be.

There's no need to avoid them, just be careful to use them appropriately.

In your example, the default state should be to not allow access. A little refactoring leaves you with:

```<code>If (passwordCheck)
{
   letThemIn();
}
else
{
   displayMessage();
}
</code>```

i.e. if the password check works, let them in, otherwise it's always valid to show some error message.

You can of course add additional checks to you logic by using else if rather than completely separate if statements.

Title: Is using ELSE bad programming?

Body:
I've often come across bugs that have been caused by using the ELSE construct.  A prime example is something along the lines of:

```<code>If (passwordCheck() == false){
    displayMessage();
}else{
    letThemIn();
}
</code>```

To me this screams security problem.  I know that passwordCheck is likely to be a boolean, but I wouldn't place my applications security on it. What would happen if its a string, int etc?

I usually try to avoid using ELSE, and instead opt for two completely separate IF statements to test for what I expect.  Anything else then either gets ignored OR is specifically handled.

Surely this is a better way to prevent bugs / security issues entering your app.

How do you guys do it?

Body:
The else block should always consist of what you want the default behaviour to be.

There's no need to avoid them, just be careful to use them appropriately.

In your example, the default state should be to not allow access. A little refactoring leaves you with:

If (passwordCheck)
{
   letThemIn();
}
else
{
   displayMessage();
}

i.e. if the password check works, let them in, otherwise it's always valid to show some error message.

You can of course add additional checks to you logic by using else if rather than completely separate if statements.


答:
There is always an ELSE. If you write

```<code>if(foo)
  bar();
</code>```

you actually write

```<code>if(foo)
{
  bar();
}
else
{
   // do nothing
}
</code>```

Whatever you put in the ELSE-path is your responsibility.

Title: Is using ELSE bad programming?

Body:
There is always an ELSE. If you write

if(foo)
  bar();

you actually write

if(foo)
{
  bar();
}
else
{
   // do nothing
}

Whatever you put in the ELSE-path is your responsibility.


答:
No, there is nothing wrong with ELSE. ELSE is not the new GOTO.
In fact, using two IFs instead of ELSE can lead to several problems.

Example one:

```<code>if (this(is(a(very())==complex(check())))) {
   doSomething();
}

if (!this(is(a(very())==complex(check())))) {
   doTheOtherThing();
}
</code>```

You see the copy-paste? It just waits for the day when you change one and forget the other.

Example two:

```<code>foreach(x in y) {
  if (first_time) {
    first_time = false;
    doSomething();
  }

  if (!first_time) {
    doTheOtherThing();
  }
}
</code>```

As you can see, the second IF will also be executed for the first item, because the condition has already changed. In real world programs, such bugs are harder to spot.

Title: Is using ELSE bad programming?

Body:
No, there is nothing wrong with ELSE. ELSE is not the new GOTO.
In fact, using two IFs instead of ELSE can lead to several problems.

Example one:

if (this(is(a(very())==complex(check())))) {
   doSomething();
}

if (!this(is(a(very())==complex(check())))) {
   doTheOtherThing();
}

You see the copy-paste? It just waits for the day when you change one and forget the other.

Example two:

foreach(x in y) {
  if (first_time) {
    first_time = false;
    doSomething();
  }

  if (!first_time) {
    doTheOtherThing();
  }
}

As you can see, the second IF will also be executed for the first item, because the condition has already changed. In real world programs, such bugs are harder to spot.


答: As Mnementh said. Indeed, the purpose of the database is very likely not only to prevent having mails sent twice. And the danger of hacking around this way is that you'll end up with a database full of unique columns, all for a different purpose. It's a common mistake in DB design, and one the boss rightfully avoids. So I wouldn't be so sure about your statement regarding who is the best programmer. You definitely never had to maintain/update/refactor a database where some wizzkid has been hacking away in your style.</p>


答:
My only criticism of your boss's approach is that if you ever happen to want to send a newsletter with the same title as a previous one it will not get delivered. How about using something you know will be unique (UUID per newsletter)?

Your solution is more fragile.

It relies on the correctness of the append operation between the two data formats;

Which would require work to be unambiguous (where does the title end and the email start?)

It has to manipulate user generated data (the email address), which means you have to deal with anything the user decides to put in there.

Is not very self-documenting, future maintainers would have to look at the code and the database schema to understand what the data is.

If you do decide you want to change the way your algorithm works in the future, upgrading your database data will involve having to un-concatenate all the rows. Which is unnecessary pain. Whereas it would be comparatively easier to go from you boss's solution to your solution (or some other solution)


答:
First, there is no general purpose way to determine if an email has been received. You can only determine if an email has been sent.

Second, the way the codeblock is presented makes it appear as if you would break this conditional into two parts. No need. You would simply do a query like so:

SELECT count(*) from newsletter_sent WHERE title = '$title' AND email = '$email'

There is no need to check for the title first. Also, the title of a newsletter might change. Will this affect the reliability of this solution? Most definitely. For that reason, none of the solutions are ideal.

The ideal solution is to assign an ID to each newsletter, whether this be obtained from a third party site (if you're using third party newsletter management) or otherwise.


答:
There is nothing wrong with using ELSE. However it can lead to overly complex code that is hard to read and understand. It may indicate a bad design. It certainly indicates additional use cases that will need to be tested.

Try to remove ELSEs if you can - but don't be paranoid about it. Steve McConnell calls this straight line code in Code Complete. I.e. there is a simple clear path through your code.

Approachs to try for your particular problem:

use polymorphism. At the boundary to your system validate the security credentials of the user. If they are legitimate then return a session object - with access to the relevant parts of the system or throw an exception. However this could make you system more complex. So you decide what's easier to understand and maintain.

In general - the following may help to reduce ELSEs in your code:

good requirements may reduce the need for such decisions in the code. You may not need to implement the use case (else) at all.

clearer design. Maximum cohesion and minimize coupling. This ensures components are not duplicating decisions made in other components.

exception handling to manage error cases.

polymorphism (see example above).

switch statements - these are glorified ELSEs but are better in certain situations.

Title: Is using ELSE bad programming?


答:
I personally tend to avoid else as much I can, but it's not for any security problem.

When reading code, nested statements make it harder to follow the logic, because you need to remember which set of conditions will lead there. For this reason, I am a huge fan of early exit:

```<code>if (checkPassword != OK) { displayMessage(); return; }

letThemIn();
</code>```

This also applies to for and while loops in which I will use continue and break whenever it avoids a level of indentation.

Chris Lattner says it better than I do in the LLVM Coding Standards.

Title: Is using ELSE bad programming?

Body:
I personally tend to avoid else as much I can, but it's not for any security problem.

When reading code, nested statements make it harder to follow the logic, because you need to remember which set of conditions will lead there. For this reason, I am a huge fan of early exit:

if (checkPassword != OK) { displayMessage(); return; }

letThemIn();

This also applies to for and while loops in which I will use continue and break whenever it avoids a level of indentation.

Chris Lattner says it better than I do in the LLVM Coding Standards.


问:
Why does it matter that HTML and CSS are not programming languages?
Example here:

What languages should I know if I'm interested in building web applications?

Yes, I understand that HTML and CSS are not Turing-complete.  Yes, I understand that they are declarative, not imperative languages.  But why are people always clubbed over the head with this pedantic (and arguably obvious) fact when they ask a question about these languages?

答:
What is the difference, really?

The real and important difference between a programming language and these other languages is this:

HTML and CSS describe presentation,
  whereas programming languages describe
  function

I intend to illustrate why this difference matters, but that pedantry on this issue is sometimes misplaced.

A true story:

I once spent a few months developing a complex performance management system using a "proper" programming language. It automated the process of gathering data from various other systems, performed various manipulations on that data and then presented the results in a simple table.

Once it was live, a senior manager saw a tool written for a similar business, and asked if we could replace what I had written using their alternative. Furthermore, he was upset that I'd spent weeks developing my solution, where this new app had been written in a matter of days.

Further investigation revealed that the manager's preferred option was all presentation with no substance: there were lots of colours and icons and graphs, but there was absolutely no logic behind them. All the data had to be gathered and manipulated manually. Despite the pretty interface, the application was essentially useless.

I'm happy to say that the manager in question was persuaded that my approach was the one that met his real business needs.

The importance of presentation:

There is often an implication that skills in HTML, CSS etc. are somehow inferior to skills in "real" programming languages. This is a serious mistake.

In my story, the senior manager felt that design was very important to him, to the extent that he was initially prepared to overlook function in its favour. Now, if this were an isolated incident, I might suggest that the manager was just being silly. But it wasn't. Time and again, I've met users who are impressed by flashy graphics and whizzy widgets, but unimpressed by raw functionality and my technical achievements. I think that there are several lessons to learn here:

People evaluate software on criteria that they understand. They often understand the difference between good-looking and ugly, but rarely appreciate technical nuances.

People are fooled by appearances. This may not be a good thing, but it is a reality that we must live with.

Appearances influence the way people feel about software. The way people feel about software is important to them. Indeed, people sometimes prefer software that makes them feel good over software that is functionally superior. Indeed, they might well be more productive with feel-good tools than with technically superior tools. To this extent, our users are not being fooled. They are actually making a wise and thoughtful choice.

As programmers, we often neglect the role of presentation as we focus on function. To some extent, this is right and proper. However, it is important to recognize that there is another dimension to our work that is important to our customers.

So, presentation-oriented languages (HTML, CSS) are important. The value added by those who can use these tools effectively should not be underestimated.

The importance of real programming languages

As the OP pointed out, "real" programming languages are Turing Complete. As a proper sad geek, I find this sublimely fascinating. It means that, for any program written in a T-C language, a functionally equivalent program can be written in any other T-C language. Of course, this isn't to say that all languages are the same. They each have their strengths and weaknesses that make them more or less suitable for certain tasks. However, I/O aside, this means that all programs can be written in all true programming languages.

(Incidentally, the important thing is T-C. The declarative vs imperative is a red-herring here. SQL, for example, is declarative but is also a proper programming language because it is T-C.)

Of course, the same isn't true of a markup language like HTML or CSS. In fact, there are whole classes of problem that these languages simply can't solve. Where I can program anything I want in a true programming language - including layout engines - it just isn't possible to achieve the same things with languages that aren't T-C.

As highlighted in my story, HTML and its ilk are used to produce presentation. Real programming languages are used to produce functionality.

Why are programmers pedantic about it all?

Programmers spend a great deal of time, effort and money developing their skills. People naturally value the things in which they invest ("your heart is where your money is").

Programmers often feel the need to justify the amount of time it takes to produce results compared to the rapid results achieved by UI designers. In order to do this, they need to draw a distinction between what the two groups actually do.

Because employers need to apply the right people to the right jobs. Unless we clarify the (often technical) differences, managers easily make the wrong calls.

Because there is a real and fundamental difference, as outlined above.

Is it always appropriate to be pedantic?

Let's face it, as programmers we're a naturally pedantic lot. It goes with the territory. It doesn't help that many of us have been burned when non-programmers have failed to understand what we do.

Nevertheless (and to be honest, this goes against my natural instincts), I don't think we need to call people out whenever they slip over every little distinction.

The important things here are context
  and perspective.

I'm told that, from the perspective of a biologist, a tomato is a fruit. But when I buy them in the supermarket, I look for them amongst the vegetables. Why? Because the technical distinction doesn't matter in that particular context. Moreover, the distinction would actually get in the way of their usefulness: if I was daft enough to include tomatoes in a fruit salad, for example.

It is the same with computer languages. There are times when the difference between programming languages and other languages really does matter. Quite often, however, we can all communicate perfectly effectively when just lump them all in together. In the case of the question linked by the OP, it really didn't matter what languages were true programming languages and which were not. Pointing out the distinction didn't advance the discussion in any way. Thankfully, other than adding a little noise (and becoming the stimulus for an interesting discussion!) the pedantry linked by the OP was of little consequence. At its worst, however, pedantry can stir up negative feelings and damages relationships... at least according to my wife.
 :-)

How to deal with pedantry amongst programmers

A preacher friend of mine once delivered a sermon entitled:

is this a hill worth dying to be on?

He was referring to generals who make a strategic assessment over which battles are worth fighting: are the gains worth the costs?

Is it really worth interrupting the flow of the discussion to make this distinction?

Does my pedantry stem from a sense of arrogance or from past hurt?

Do my comments value the skills of others as well as my own?

Of course, there are times when distinctions need to be made. My aim is that, when I make a contribution, it will add value to our collective endeavors.

That is, after all, the job of every real programmer.


答:
valgrind and gcov ?

I use PowerShell when developping on windows (as a hobby) and I have installed the GnuWin32 tools (sed, awk, grep, etc...) and Python to get some easy scripting, so no issue there.

But I find myself hitting a wall whenever I want to inspect my program... Sure I can use the debugger (a bit) but:

how does one spot a memory leak ?

how does one identifies the memory hogs ?

how does one identifies the hot spots ?

how does one identifies unused / untested parts of the code ?

I have seen some tools here and there and there was a good question on StackOverflow and the number of tools listed is pretty frightening... and their limitations too.

Linux has been made by developers for developers, so it got a lot more developers' friendly tools :)

Title: What default features is Windows missing that are required for programmers?

Body:
What features is Windows missing that can improve the productivity of a programmer. I know a lot of people would want some features from Linux and OSX ported or being created for Windows as well. What is missing for you ?

An example would be the option to have multiple workspaces. When not having the possibility to use dual monitors that can come in handy.


答:
Ok,

What happens should the client change their email address? The two column solution enables a simple update to be applied

Test by exception (which is what your unique method implies) is a generally considered poor, if I were to go with the concatenated string I'd still want to explicitly test for existence before doing the insert rather than throwing the data at the db and looking for something to break.

And as a belt and braces check you could always have a unique constraint across both columns (assuming that is supported by MySQL).

In terms of your code, you want to start with a query that says give me all the users that match my selection criteria that haven't already been sent this newsletter - again the split column facilitates this.

In terms of design, I'm with @Zenph - user table (with unique ID), newsletter table (with unique ID) and NewsletterSentToUser table (NewsletterID, UserID and possibly its own unique ID 'cos that can make some things easier). Queries are a teeny bit more complex but its a lot more resilient.

Oh, and in terms of reporting which user (email address) has been sent which newsletter (subject) the two column solution makes that far more elegant


答:
Copy/paste with history function.

Luckily ClipX offers a solution:

PS I am not affiliated with ClipX ;)


答:
My advice is to first determine if his solution is in fact better. Post the two solutions, ask SE for an unbiased opinion.

I would NEVER ignore my boss. If he has the technical know-how, then there is no harm in a healthy discussion. He pits his idea and you propose your's.

However, if you do determine that in fact his method is inferior and he won't allow you to do the job he hired you for, quit. There is nothing worse than having a knucklehead stand over you telling you how you should do something when they clearly have no idea what they're talking about.


答:
A good language is a language which is:

easy to reason about (no obscure syntax)

let you express your ideas with minimum distortion

hide the nitty gritty details from you (optimization / resources management)

easily parallelizable (multiple cores, distributed computing)

It's pretty hard to turn this into a list of features, but I think Functional Programming, despite not feeling natural, is closer to this than imperative programming (especially in hiding the nitty gritty details)

C-interfacing: C is the lingua franca of programming languages and the number of libraries developped in C is amazing. By having an easy interface (like Python) to C, the language automatically benefits from all those libraries and it also allows to send heavy-tasks that could not be optimized enough to a close to metal language.

Distributed: I like Go's take at multi-threading, with lightweight routines that the runtime dispatches on threads depending on their activity. Such a language encourages the programmer to reason about tasks and to isolate them from one another.

Garbage Collection: goes without saying nowadays ;)

Immutable: much easier to reason about something that can never mutate, much easier to implement multithreading / distributed computing too (you only need synchronization to handle the lifetime, which is the compiler task)

Lambdas: goes with first class functions I guess

Message Passing: immutability means no mutex, therefore we follow Tony Hoares' suggestion

Modules: somewhat similar to namespaces, but with better encapsulation

Reflexion: distributed computation requires serialization, which should be left to the compiler, and deserialization is more easily achieved with some form of reflexion.

Static Strong Typing: the earlier an error is detected, the least it costs

At the moment, the language closer to this list is probably Haskell, though:

it lacks Routines: I have not seen a natural way to express parallelism in Haskell yet (though it may be my ignorance...)

it's got an Obscure Syntax: somehow it looks like Haskell programmers thrive on using weird operators rather than words. It may seem slick, but it doesn't help much to understand what's going on.

Title: How would you design a programming language?

Body: If you were to design a programming language, how would you do it? What features would you put in? What would you leave out? Statically or dynamically typed? Strongly or weakly typed? Compiled or interpreted? Justify your answers.</p>


答:
Saying that using else when programing is bad is like saying that using otherwise when speaking is bad.

Sure, they can both be used in bad ways, but that doesn't mean they are to be avoided just because you made a mistake which happened to include them. I wouldn't be surprised if many bugs depended on a missing default case in a switch statement.

Title: Is using ELSE bad programming?


答:
I would say Black Box testing first, simply because as a proponent of TDD, the tests are written before the code (or box) exist anyway :)

White Box testing (as far as I understand) is more useful in a debugging mindset.

Title: Black box or white box testing - which do you do first?

Body: On a very small team, where the black box and white box testing is done by the same person, which should the tester do first?</p>


答:
Like Matthieu M., I prefer early exit to deeply nested else blocks... It illustrates well defensive programming (if bad conditions, no point to continue). Lot of people will disagree with us, preferring a unique exit point; it is not the point of the debate (I think).

Now, I certainly use else when it makes sense, particularly for simple, short alternatives. As said, duplicating the test is a waste of time (programmer's and CPU's), a source of confusion and, later, of bugs (when one is changed, not the other).

Sometime, I add a comment on the else part, reminding what was the condition (particularly if the if part is long, eg. in legacy code) or what is the alternative.

Note that some extreme proponents of functional programming propose to get rid entirely of if, in favor of pattern matching... A bit too extreme for my taste. :-)

Title: Is using ELSE bad programming?


问:
place to propose a open source project and collaborate on software requirements before start to coding
I'm searching for a web site to start a new open source project.
I want to start the developing of a "SPORT training log".
I have some developing skill but not all I need (I dont know web coding).

Anyone know a good starting point to meet some people, propose the software and then (in another place also) start the development all together?

For example, I have python, c, c++ skills and a little training experience, but I want to make it in web, so I can't do all the stuff alone. I dont think I'm the only one who wants to make a training log but dont have necessary skills. I'm searching for a site to manage the idea behind a training log and get interested people to contribute in the idea and then eventualy contribute also in the code.

What I mean is a step before actualy FOSS approach.

The question is:

Why start to code software I need if I can start global software requirements about a "sport traning log" and after a useful and global review, we can start all together to developt it? Why should I need to start developing the software with XYZ features and other people who need features YZQ need to start to write another one? Why not put the opensource comunity a step before in a more professional way starting an opensource project with a collaborative approach also in software requirements?

答:
I'm not aware of such a site, and I would be very interested to know if anything like that exists.

But I guess your best bet is searching for which are already doing something similar and see if/how you could work together.

You could eg take pytrainer, which is not a web application but has done already quite a lot of thinking on presenting results, importing from devices/...
http://sourceforge.net/projects/pytrainer/

Or the other way around, search for logbook web software and adjust that for sports logging.


答:
Your supposition about the code being a security leak may or may not be true depending on the language you are using.  In C code it could be a problem (particularly because in C a boolean is just an int that is non-zero or zero)--but in most strongly typed languages (i.e. runtime type checking) if the passwordCheck variable was declared as a boolean, there is no way to assign something else to it.  In fact, everything in an if predicate must resolve to a boolean, whether you use the boolean operators or simply use the value.  If you managed to have another type of object bound to passwordCheck the runtime would throw some type of illegal cast exception.

Simple if/else constructs are much easier to read than if/if constructs--and less prone to inadvertant problems if someone tries to flip the construct.  Let's take the same example for a second:

```<code>if(passwordCheck == false) {
    denyAccess();
}

if(passwordCheck) {
    letThemIn();
}
</code>```

The meaning of the mutually exclusive clauses you want to execute above is lost.  That's what the if/else construct conveys.  Two mutually exclusive branches of execution, where one of them will always run.  This is an important part of security--ensuring there is no way to letThemIn after you've called denyAccess.

For the purpose of code clarity, and for the purpose of ensuring critical sections are most protected, they should be inside the primary clause (the if part).  The default non-compliant behavior should be in the alternate clause (the else part).  For example:

```<code>if(passwordCheck) {
    letThemIn();
} else {
    denyAccess();
}
</code>```

NOTE: in working with different languages, I've developed a coding habbit that does help avoid the question of "what if it's a string?"  Essentially,  it is to put the constant first in the boolean expression.  For example, instead of checking passwordCheck == false I am checking false == passwordCheck.  This also avoids the accidental assignment problem possible in C++.  Using this approach, the compiler will complain if I type = instead of ==.  In languages like Java and C#, the compiler would treat the assignment in the if clause as an error, but C++ will happily accept it.  That's why I also tend to do null checking with the null first.

If you routinely change languages placing the constant first is very helpful.  However, on my team it is opposite the coding standard and the compiler catches those problems anyway.  It can be a hard habbit to break.

Title: Is using ELSE bad programming?

Body:
Your supposition about the code being a security leak may or may not be true depending on the language you are using.  In C code it could be a problem (particularly because in C a boolean is just an int that is non-zero or zero)--but in most strongly typed languages (i.e. runtime type checking) if the passwordCheck variable was declared as a boolean, there is no way to assign something else to it.  In fact, everything in an if predicate must resolve to a boolean, whether you use the boolean operators or simply use the value.  If you managed to have another type of object bound to passwordCheck the runtime would throw some type of illegal cast exception.

Simple if/else constructs are much easier to read than if/if constructs--and less prone to inadvertant problems if someone tries to flip the construct.  Let's take the same example for a second:

if(passwordCheck == false) {
    denyAccess();
}

if(passwordCheck) {
    letThemIn();
}

The meaning of the mutually exclusive clauses you want to execute above is lost.  That's what the if/else construct conveys.  Two mutually exclusive branches of execution, where one of them will always run.  This is an important part of security--ensuring there is no way to letThemIn after you've called denyAccess.

For the purpose of code clarity, and for the purpose of ensuring critical sections are most protected, they should be inside the primary clause (the if part).  The default non-compliant behavior should be in the alternate clause (the else part).  For example:

if(passwordCheck) {
    letThemIn();
} else {
    denyAccess();
}

NOTE: in working with different languages, I've developed a coding habbit that does help avoid the question of "what if it's a string?"  Essentially,  it is to put the constant first in the boolean expression.  For example, instead of checking passwordCheck == false I am checking false == passwordCheck.  This also avoids the accidental assignment problem possible in C++.  Using this approach, the compiler will complain if I type = instead of ==.  In languages like Java and C#, the compiler would treat the assignment in the if clause as an error, but C++ will happily accept it.  That's why I also tend to do null checking with the null first.

If you routinely change languages placing the constant first is very helpful.  However, on my team it is opposite the coding standard and the compiler catches those problems anyway.  It can be a hard habbit to break.


答:
OOP is definitely one of the more dominant programming models in the real world.

Lets face it, even people who design digital hardware, the chip designers themselves, are making a transition to the duo of SystemVerilog and SystemC. These are object oriented programming languages.

Where would OOP not be used? Well if you are coding device drivers its hard to imagine why you'd need generic programming or multiple inheritance OR if you are doing AI functional programming techniques make it a lot easier on the head. There are loads of other situations too, suffice to say though that OOP is a pretty powerful place to be in an oligopolistic programming world.


答:
Don't bite the hand that feeds you.

If you think yours is better, even after exhaustive analysis, then sure, do as you believe but you will live with the consequences.


问:
Documenting higher-level concepts
I will be leaving my current project in a few days, and as part of securing my knowledge I have been asked to add comments to the code wherever I feel that can add value.

The problem I am running into now is that the comments I want to write are not really suitable as comments, because they do not pertain to a single entity in the code (a few lines, a function, a class or even a file), but they are more about how two or more entities interact with each other or about a feature whose implementation is spread over multiple entities.

So, how do you go about documenting the stuff that does not belong to a single entity but is important to know to understand the bigger picture?

And also: Where do you document it? In the source file or in an external document?

As an example, we have a client-server architecture in C (with the client and server both running on the same embedded device). To avoid flooding the server, the client has a mechanism to throttle the sending of similar requests to the server such that a request can only be sent if the previous one has been answered.

The innards of this mechanism are spread over multiple functions.

Where would you place the documentation of such a feature, especially if the file with the functionality also has some other, unrelated, functions?

Edit: Extended the question a bit.

答:
+1 for Wiki.

If it is a message passing system then I suggest generating sequence diagrams to show the interaction between the different components. I have used the following website to generate diagrams from simple text so no need to fiddle with any tools.

http://www.websequencediagrams.com/

One thing we have found useful is to ask the person leaving (you in this case) to come up with a quiz related to your area of expertise and then have a separate session to go over the questions and the answers.

HTH

Title: Documenting higher-level concepts


问:
Two possible solutions to a problem, DB design
I saw the recent post about the person questioning his boss's solution (I believe my solution is better than my boss, so should I ignore him?) and decided to ask something similar but not as "clashing" as it sounded in the above link.

To put it simply and more conceptually:

We have a web app that does phone billing for many different clients. The thing is, the person that started the project didn't consider that there are only 9999 possible phone extensions in our design (a bit naive, I know). We have come across a point where different clients's users will have to share the same extension number. In the DB level, the extension number is fixed as unique and the Extensions table has a foreign key to Users.

The easiest solution as we saw was to remove this unique constraint and allow extension numbers to be duplicated because we can still check and validate to see which Client the User belongs to. However, the person that oversees my work believed it would cause future problems if we simply allowed for duplication. He suggested I create an intermediary table that links two tables together, namely UserProfile (which has a foreign key to User and Client) and the Extension table.
Since my way seemed easier to do, I created a branch of the project to test if it works fine, which it does.
Then I started implementing the other way and came across some complications, system-wide modifications, but I still think it's doable. The person that oversees my work is a sys admin that does some programming. I'm the full-time programmer, though without much experience (still young ;)  ). It would be cool if I had some outside perspective on my dilemma?

Thanks a lot guys.

答:
I think that dimensionally the link table is better, because you don't duplicate data. That extension table will not grow at all, giving more space for the client data. However, that would require changing your queries, and if you're not using prepared statements or PL/SQL, then it would require quite afew changes.

I'd say to make the changes. It will save you time later, when another client has the same issue. I share a phone too, btw - sounds like a common scenario. If you have a good suite of automated tests, it should be easy to find problems associated with the change.


答:
I would add the Client ID in the Extensions table and create a unique index for (Extension number, Client ID; this should avoid all problems related to completely dropping the unique constraint while making it possible to share the extension number between clients.

There is a bit of redundancy because the Client could be found through the User, too; but I think this is not much of a problem and it allows you to e.g. to remove the connection to the User (i.e. the user has been fired, the extension is currently not used) without running into new problems.

Title: Two possible solutions to a problem, DB design

Body:
I saw the recent post about the person questioning his boss's solution (I believe my solution is better than my boss, so should I ignore him?) and decided to ask something similar but not as "clashing" as it sounded in the above link.

To put it simply and more conceptually:

We have a web app that does phone billing for many different clients. The thing is, the person that started the project didn't consider that there are only 9999 possible phone extensions in our design (a bit naive, I know). We have come across a point where different clients's users will have to share the same extension number. In the DB level, the extension number is fixed as unique and the Extensions table has a foreign key to Users.

The easiest solution as we saw was to remove this unique constraint and allow extension numbers to be duplicated because we can still check and validate to see which Client the User belongs to. However, the person that oversees my work believed it would cause future problems if we simply allowed for duplication. He suggested I create an intermediary table that links two tables together, namely UserProfile (which has a foreign key to User and Client) and the Extension table.
Since my way seemed easier to do, I created a branch of the project to test if it works fine, which it does.
Then I started implementing the other way and came across some complications, system-wide modifications, but I still think it's doable. The person that oversees my work is a sys admin that does some programming. I'm the full-time programmer, though without much experience (still young ;)  ). It would be cool if I had some outside perspective on my dilemma?

Thanks a lot guys.


问:
Why do people still say Java is slow?
For a long time in SO and in other places Java has the reputation of being slow. From jokes to many comments in questions and answers, people still believe Java is slow based solely on experience with it in the 90s.

This is my issue: we have disproved (most) of the reasons that people believe Java is slow. Outside of small things, Java is pretty fast.

So why is it that people still refuse to believe Java is fast now? Is it part of their mindset that anything thats not C/C++ is slow? Is it because people don't check over time? Is it because people are just biased?

答:
Because it takes a generation to change peoples perceptions about a product

It has nothing to do with how fast Java becomes. In people's minds Java is a const identifier associated with the word 'slow'. There's little, nothing you or Oracle can do about it.

Just be happy that Oracle hasn't destroyed the Java programming culture (yet) by doing anything rash or stupid. Like charging excessive licensing costs to use it. Or suing people based on software patents previously owned by Sun. ::sigh::

I hate to be the naysayer here but, unless Oracle and Google settle the Java struggle on nice terms, or Google is forced to purchase Java and makes it a 'proper' open source platform, Java is well on it's way to being the kid on the playground that has lice. IE, no one will want to touch it with a 20ft pole.

Note: Just to be clear, when I say generation I'm talking in people terms not computer terms. IE, until the people who hold that perception die of old age or replaced by a younger generation the perception will hold true. Think in terms of 5 decades not 5 years.

Title: Why do people still say Java is slow?


答:
Think of Else as white-listing your application flow. You check for conditions that SHOULD allow application flow to continue, and if these are not met, then your Else is executed to either resolve the problem, discontinue the application execution, or something similar.

Else in itself is not bad, but if you use it poorly, you can see undesired effects.

Also, in regards to your statement about

"I know that passwordCheck is likely to be a boolean, but I wouldn't place my applications security on it."

For methods that you develop, ALWAYS return one data type. Although PHP Core is littered with code that returns two or more datatypes, this is a bad practice as it makes guesswork of function calls.  If you have to return more than one datatype, consider throwing an exception (I find this is often the reason I would want to return another data type - something went horribly, horribly wrong), or consider re-structuring your code so that you can return only one data-type.

Title: Is using ELSE bad programming?


答:
From a database perspective, I would say he is correct.  It is better to not duplicate data, and business rules (eg: "Users belonging to the same client can not have the same extension") should be enforced on the back-end.

Just dropping the uniqueness may be the quick and dirty solution, but in the long-run has the possibility (however unlikely) of causing issues.


答: This is a bit of an abstract answer, but I would go with the design that most closely models the business.  In your case, it seems like in reality, you do have situations where people share extensions, because you are modeling many distinct phone systems.  Therefore I would drop the unique constraint.  This means that extension is no longer a natural key for a person, but I don't really see that as a problem.


答:
Compromise

Why not implement your idea AND his idea... go a step further?

Assuming you have a customer table with unique customer id's + customer email address... create a table with NewsletterID, NewsletterDescription.

Then you can make a third table that has a unique FK of CustomerID + NewsletterID.

What if customer changes email? Are you going to send all the newsletters to the new address? Are you going to change all the email address? What if you change the newsletter name to correct a typo?

In your solution, it's greatly complicated by having to parse out the email to update part of one field. Same for newsletter name.

In his solution, you are going to have to dance around changing email addresses and/or names in separate columns (much easier than changing a single column, but still changing what is likely to be more than is needed).

Database Normalization

You need to normalize the database to remove the need to change redundant information, specifically data that WILL change: like email's (and less likely, but still likely, newsletter names). The fact that this isn't in either option presented tells me that you both need to buy a SQL book that describes Database Normalization and read it from beginning to end.


答:
A little of topic butr, hey maybe you have found something greater than your main goal. What if you digg a bit more on the "open source pre project site", i think that could be an amazing idea and would be more than exited to participate in.

As an enthuast on those matters, i would really like to have an open source place where you could share ideas and start projects in a collaborative way.

Like having open source intelectual right policy, so people could use those ideas to improve our every day internet experience without the fear of someone stealing whats yours.

Think about it!

Title: place to propose a open source project and collaborate on software requirements before start to coding

Body:
I'm searching for a web site to start a new open source project.
I want to start the developing of a "SPORT training log".
I have some developing skill but not all I need (I dont know web coding).

Anyone know a good starting point to meet some people, propose the software and then (in another place also) start the development all together?

For example, I have python, c, c++ skills and a little training experience, but I want to make it in web, so I can't do all the stuff alone. I dont think I'm the only one who wants to make a training log but dont have necessary skills. I'm searching for a site to manage the idea behind a training log and get interested people to contribute in the idea and then eventualy contribute also in the code.

What I mean is a step before actualy FOSS approach.

The question is:

Why start to code software I need if I can start global software requirements about a "sport traning log" and after a useful and global review, we can start all together to developt it? Why should I need to start developing the software with XYZ features and other people who need features YZQ need to start to write another one? Why not put the opensource comunity a step before in a more professional way starting an opensource project with a collaborative approach also in software requirements?


问:
I believe my solution is better than my boss's, so should I ignore him?
I'm working with php and sql.

I think that my method of implementing functions is better than what my boss proposes. Just now he explained me how to do a check on a list of email addresses, and I do not like his idea. I proposed mine which is better and quicker to implement, but he disagreed.

Now I think I will go ahead and implement my idea, because his idea was not clear enough to me. Do you think he will be mad?

答:
Let's start with the fact that it is the boss's job to make decisions, not yours. You go against those decisions behind his back and it's a quick path to being fired for cause.

You can and should present your ideas before the decision is made, but once it's made, it is your job to make the decision work even if you don't agree with it. If you can't do that you will have a very short career.


问:
Language agnostic programming books
Are there any great programming or software development books that are language agnostic?  Why should I read it?</p>

答: Clean Code - Robert Martin</p>

Title: Language agnostic programming books

Body: Clean Code - Robert Martin


问:
What non-programming books should a programmer read to help develop programming/thinking skills?
There are a lot of questions about what programming books should be on the programmer's bookshelf. How about non-programming related books that can help you become a better programmer or developer? It would also be interesting to know why they would help.

My first choice would be Sun Tzu's "Art of War" (however cliché), because it made it obvious that the success of any project depends on the strength of its weakest link (and warfare is a big project).

答: Predictably Irrational

Body: Predictably Irrational


问:
is OOP the dominant programming model in real world?
Objects Never? Well, Hardly Ever

In the VIEWPOINT section of Communications of The ACM, I found an
interesting article entitled "Objects Never? Well, Hardly Ever".
It’s a radically different perspective than objects-first or objects-late. He suggests "objects-never" or maybe "objects-graduate school".

The author talked about OOP and made a question about how OOP is used
in real world programming environments. He thinks that OOP is not the
dominant programming model. For example, he claims, 70% of
programmings are done for Embedded Systems where OOP is not really
suited.

When some professors in universities wants to talk about the benefits
of OOP, they talk about code-reuse. As another example, again, he
claims, this is not the real case in real world. code-reuse is harder
than what's claimed in universities:

I claim that the use of OOP is not as prevalent as most people believe, that it is not as successful as its proponents claim, and, therefore, that its central place in the CS curriculum is not justified.

It's interesting for me to know how people in stack-overflow think
about this? Is OOP the dominant programming model from programmers'
point of view?

If I should choose/learn/use just one approach, is it OOP or not? why?

答:
This is actually a difficult question to answer reliably. The biggest reason is people like me, who work in custom, in-house applications, where the code never leaves our building. Do we use OO here? I'm not saying. How many other programmers have similar jobs? They're not saying either. We do have job sites, but not all jobs are posted, and not all postings are for real jobs as opposed to recruiters trying to gather lists of names.

Even if I did say we use OO where I work, does that mean the traditional definition from the linked article: Objects, Classes, Inheritance? Or does it mean that I use objects primarily as a means of organizing code? Or does it mean that I really just program to interfaces and hardly use inheritance at all? I'm still not saying, but which of these really counts as OO?

It's not even meaningful to ask if OO is useful until the questions above have been answered, let alone dominant.


问:
How do you scale your integration testing?
I am investigating techniques and strategies for scaling our growing number of integration tests on our current product, so that they can (humanly) remain part of our development, and CI process.

At about 200+ integration tests we are already hitting the 1hr mark to complete a full test run (on aa desktop dev machine), and this is negatively affecting a developer's ability to tolerate running the whole suite as part of the routine push processes. Which is affecting motivation to be disciplined about creating them well. We integration test only key scenrios front to back, and we use an environment that mirrors production, that is built from scratch each test run.

Because of the time it takes to run, it is making for a terrible feedback loop and many wasted cycles waiting on machines to finish test runs, no matter how focused the test runs are. Nevermind the more expensive negative impact on flow and progress, sanity and sustainability.

We expect to have 10x fold more integration tests before this product begins to slow down (no idea really, but it does not feel like we are even getting started in terms of features yet). We have to resaonably expect to be in the few hundreds or or couple thousands of integration tests, I reckon at some point.

To be clear, to try to prevent this becoming a discussion on unit testing versus integration testing, (which should never be traded). We are doing both unit testing with TDD AND integration testing in this product. In fact, we do integration testing at the various layers in the services architecture that we have, where it makes sense to us, as we need to to verify where we introduce breaking changes when changing the patterns in our architecture to the other areas of the system.

A little about our tech stack. We are currently testing on a (CPU and memory intensive) emulation environment to run our tests from end to end. Which is composed of Azure REST web services fronting a noSql backend (ATS). We are simulating our production environment by running in the Azure desktop Emulator + IISExpress. We are limited to one emulator and one local backend repository per dev machine.

We also have a cloud-based CI as well, which runs the same test in the same emulated environment, and the test runs are taking twice as long (2hrs+) in the cloud with our current CI provider. We have reached the limits of the cloud CI providers SLA in terms of hardware performance, and exceeded their allowance on test run time. To be fair to them, their specs are not bad, but half as good as an inhouse grunty desktop machine clearly.

We are using a testing strategy of rebuilding our data store for each logical group of tests, and preloading with test data. While comprehensively insuring data integrity, this adds 5-15% impact on each test. So we think there is little to be gained optimizing that testing strategy at this point in the product development.

The long and the short of it is that: whilst we could optimize the throughput of each test (even if by as much as 30%-50% each), we still wont scale effectively in the near future with several hundred tests. 1hr now is even still far in excess of humanly tolerable, we need an order of magnitude-ish improvement in the overall process to make it sustainable.

So, I am investigating what techniques and strategies we can employ to drastically reduce testing time.

Writing less tests is not an option. Lets please not debate that one in this thread.

Using faster hardware is definately an option, although very expensive.

Running groups of tests/scenarios on separate hardware in parrallel is also definately a preferred option.

Creating grouping of tests around features and scenarios under development is plausible, but ultimately not reliable in proving full coverage or confidence that the system is not affected by a change.

Running in a cloud-scaled staging environment instead of running in the desktop emulator is technically possible, although we start adding deployment times to test runs (~20mins each at the start of the test run to deploy the stuff).

Dividing the components of the system into independent logial pieces is plausible to a degree but we expect limited mileage on that, since the interractions between components is expected to increase with time. (i.e. a change is ine is likely to affect others iin unexpected ways - as often happens when a system is developed incrementally)

I wanted to see what strategies (and tools) others are using in this space.

(I have to believe others may be seeing this kind of difficulty using certain technology sets.))

[Update: 12/16/2016: We ended up investing more in CI parallel testing, for a discussion of the outcome: https://web.archive.org/web/20200114101702/http://www.mindkin.co.nz/blog/2015/12/16/16-jobs ]

答:
I worked at a place that took 5 hours (across 30 machines) to run integration tests. I refactored the codebase and did unit tests instead for the new stuff. The unit tests took 30 seconds (across 1 machine). Oh, and bugs went down too. And development time since we knew exactly what broke with granular tests.

Long story short, you don't. Full integration tests grow exponentially as your codebase grows (more code means more tests and more code means all of the tests take longer to run as there's more "integration" to work through). I would argue that anything in the "hours" range loses most of the benefits of continuous integration since the feedback loop isn't there. Even an order of magnitude improvement isn't enough to get you good - and it's nowhere close to get you scalable.

So I would recommend cutting the integration tests down to the broadest, most vital smoke tests. They can then be run nightly or some less-than-continuous interval, reducing much of your need for performance. Unit tests, which only grow linearly as you add more code (tests increase, per-test runtime does not) are the way to go for scale.