问:
Whats the best way to handle errors in code?
So I'm a little concerned about my error handling... Currently my execution path looks something like this:

Users.aspx -> App_Code/User.cs -> Data Layer/User.cs

So now when I try to update a user record, I put my Try/Catch block in the event handler and ensure that only the App_Code class interacts with the data layer. Exceptions that happen on the data layer, to my understanding, should bubble up to the event handler below.

In the data layer, I started off with this:

```<code>public void Update()
{
    var product = (from p in db.products
                        where p.productid == id
                        select p).FirstOrDefault();

    if (product != null)
    {
        // update the thing
    }
}
</code>```

More info on reddit.

After chatting with a friend, he recommended something like this:

```<code>public void Update()
{
    int count = db.users.Count(u => u.userid == id);

    if (count == 0) // no user found
    {
        throw new ValidationException(String.Format("User not found for id {0}.", id));
    }
    if (count > 1) // multiple users
    {
        throw new ValidationException(String.Format("Multiple users found for id {0}.", id));
    }

    var user = db.users.FirstOrDefault(u => u.userid == id);
    // update the user record
}
</code>```

Then I went onto IRC where they suggested I create my own Exceptions.

I can see the pros here, but it seems a bit unnecessary when my friend's option will work just fine.

Basically I'm just really confused as to how I should handle this... Obviously my initial option is insufficient, but it seems like creating my own exceptions might be complicating things too much.

So what should I do here?

答:
What makes the most sense to you? Does a ValidationException accurately describe the problem? If so, there's nothing wrong with using that as is and passing a good, valid message along with it. If you want to make a more specific error message, create an Exception class that inherits ValidationException, say, "UserNotFoundException" and "ManyUsersFoundException". These are probably poor names and not what you want, but you get the idea.

Also...

```<code>var user = db.users.FirstOrDefault(u => u.userid == id);
</code>```

Your code here is a bit redundant to use "FirstOrDefault". You already know, by this point, you have a record. So you can safely use:

```<code>var user = db.users.First(u => u.userid == id);
</code>```

And get away with it with no consequences.

Other than that, I'd say your modifications based on your chat with your friend seem more than enough to me. But that's a personal opinion.

Body:
What makes the most sense to you? Does a ValidationException accurately describe the problem? If so, there's nothing wrong with using that as is and passing a good, valid message along with it. If you want to make a more specific error message, create an Exception class that inherits ValidationException, say, "UserNotFoundException" and "ManyUsersFoundException". These are probably poor names and not what you want, but you get the idea.

Also...

var user = db.users.FirstOrDefault(u => u.userid == id);

Your code here is a bit redundant to use "FirstOrDefault". You already know, by this point, you have a record. So you can safely use:

var user = db.users.First(u => u.userid == id);

And get away with it with no consequences.

Other than that, I'd say your modifications based on your chat with your friend seem more than enough to me. But that's a personal opinion.


问:
Is inheritance that adds rules bad?
I got into a debate on this question which distilled to if it is a good idea for a specialization of a class to add business rules. Unfortunately this point got trampled in the comments so I'm asking it again as a separate question.

I believe two things:

An object is responsible for its internal consistency

A specialization/child class has more specific rules than the super class which can be seen as the general case.

The logical result of this is that a specialization might only accept some values of input for its method or might change some values in order to stay consistent. But isn't that OK, since guarding its internal consistency is what an object should do?

A point many people were making is that some code could break if it would make assumptions. For example that setting the width would not change the height of a square. However wouldn't that be bad code? Since you make assumptions on how the object does something instead of just telling it what to do and not worry about it?

If we would not write code like that almost all overloading would have problems. How often doesn't overloading add an extra fail condition or more internal logic that might be seen via other parts of the interface? Maybe the point an old professor of me once made is correct: "you should only ever use inheritance to overload the constructor". At the time that seemed a bit strict but now it seems like the only way to guarantee these kinds of problem never happening. To use the old square: rectangle analogy again:

```<code>public class Rectangle
{
    private int width, height;

    public Rectangle(int width, int height){this.width = width; this.height = height;}

    public void SetWidth... SetHeight...
}

public class Square : Rectangle
{
    public Square(int diameter) : base(diameter, diameter) {}

    public void SetDiameter...
}
</code>```

Note: I hope we can play this question a little bit less 'on the man' than the question that inspired it. I've been on Stack Exchange for more than three years but I was quite intimidated by the type of responses here.

答:
A point many people were making is that some code could break if it would make assumptions. For example that setting the width would not change the height of a square. However wouldn't that be bad code? Since you make assumptions on how the object does something instead of just telling it what to do and not worry about it?

I'm allowed to assume the object follows its specifications. If the specification for Rectangles says that the width and height are independently modifiable, then any implementation must conform. (If you don't require conformance, it's impossible to reason about your program.) Now, you could argue that the specification for Rectangles never said that setWidth can't change the height, but if you attempt to list all the things something must not do you'll find that the list is infinite:

setWidth musn't reformat my hard drive

setWidth musn't delete files in my home folder

setWidth musn't make changes to the Windows Registry

setWidth musn't change another object's state

setWidth musn't go into an infinite loop

setWidth musn't post to Twitter on my behalf

...

The only sensible way to specify something is to list the things it must and may do and assume anything not listed is forbidden. So if the spec for setWidth says it changes the rectangle's width, I assume it doesn't change the height.

How often doesn't overloading add an extra fail condition...

Doing this will definitely bring you pain and misery. Any program written according to the specifications is assuming a certain operation can only fail because of A, B, and C. If you introduce a new fail condition D, no one can possibly handle it.

A word to the wise, though - if you need this kind of substitutability, inheritance is probably not what you want. You start with some type Foo and then you realize you want a ShinyFoo. Later you want a TransparentFoo. Eventually you'll want a ShinyTransparentFoo and then you'll be in trouble. You don't run into this sort of problem if you use an interface and rely on composition to reuse behavior.

ContentLicense: CC BY-SA 3.0

Title: Is inheritance that adds rules bad?


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答:
The first time someone, usually management says "we don't have time to .."

Usually preceding something that we don't have time not to, like documentation or code reviews (which statistically find and correct more bugs that anything else, including all forms of testing)

ContentLicense: CC BY-SA 2.5


答:
Basically it depends on how you want to handle your catch statements. The advantage of having your own custom exceptions is you can catch them separately and execute separate pieces of code, see below. However if you just plan on handling all types of exceptions the same like dumping the message to a log file or message box, using a generic exception is fine.</p>

```<code>catch (UserNotFoundException ex)
{
    //handle code for user's not found
}
catch (MultipleUsersFoundException ex)
{
    //handle code for multiple users
}
catch (Exception ex)
{
    //handle other badness
}
</code>```

Title: Whats the best way to handle errors in code?

Body:
So I'm a little concerned about my error handling... Currently my execution path looks something like this:

Users.aspx -> App_Code/User.cs -> Data Layer/User.cs

So now when I try to update a user record, I put my Try/Catch block in the event handler and ensure that only the App_Code class interacts with the data layer. Exceptions that happen on the data layer, to my understanding, should bubble up to the event handler below.

In the data layer, I started off with this:

```<code>public void Update()
{
    var product = (from p in db.products
                        where p.productid == id
                        select p).FirstOrDefault();

    if (product != null)
    {
        // update the thing
    }
}
</code>```

More info on reddit.

After chatting with a friend, he recommended something like this:

```<code>public void Update()
{
    int count = db.users.Count(u => u.userid == id);

    if (count == 0) // no user found
    {
        throw new ValidationException(String.Format("User not found for id {0}.", id));
    }
    if (count > 1) // multiple users
    {
        throw new ValidationException(String.Format("Multiple users found for id {0}.", id));
    }

    var user = db.users.FirstOrDefault(u => u.userid == id);
    // update the user record
}
</code>```

Then I went onto IRC where they suggested I create my own Exceptions.

I can see the pros here, but it seems a bit unnecessary when my friend's option will work just fine.

Basically I'm just really confused as to how I should handle this... Obviously my initial option is insufficient, but it seems like creating my own exceptions might be complicating things too much.

So what should I do here?

Body:
Basically it depends on how you want to handle your catch statements. The advantage of having your own custom exceptions is you can catch them separately and execute separate pieces of code, see below. However if you just plan on handling all types of exceptions the same like dumping the message to a log file or message box, using a generic exception is fine.

catch (UserNotFoundException ex)
{
    //handle code for user's not found
}
catch (MultipleUsersFoundException ex)
{
    //handle code for multiple users
}
catch (Exception ex)
{
    //handle other badness
}


答:
In this particular situation, a better option may be to use LINQ's Single method, as so:

```<code>public void Update()
{
    var user = db.users.Single(u => u.userid == id);
    // update the user record
}
</code>```

Single already does exactly what you want: it throws an Exception if there are 0 or more than 1 results matching the predicate.

At this point you can decide whether you're happy for the exception thrown by Single to bubble up, or whether you want to wrap it in one with a more useful message, or a specific type. The general pattern for this would be:

```<code>public void Update()
{
    try
    {
        var user = db.users.Single(u => u.userid == id);
    }
    catch(SomeExceptionType ex)
    {
        throw new SomeOtherExceptionType("Useful message here", ex);
    }
    // update the user record
}
</code>```

(Notice passing ex to the SomeOtherExceptionType constructor here. This allows the information about the original exception to be preserved, as is usually good general practice)

As I said in the comment, the choice of how exactly you do this is probably not overly important. My advice would be to start with the simplest option- in this case allowing Single to throw its own exception- and refactor as needed.

If you find yourself with the need to display or log a more specific exception message, either wrap the exception in this method, or higher up the call chain as appropriate. The principle to where you do this should be avoiding leaking between your abstraction levels. Consider the following:

```<code>public void HighLevelMethod()
{
    try
    {
        DataAccessClass.Update();
    }
    catch(Exception ex)
    {
        throw new SomeKindOfException("What should I say here?", ex);
    }
}
</code>```

The message here should be at an appropriate abstraction level for HighLevelMethod. Something along the lines of "The update failed" (though ideally something a bit more useful!). The exact reason for the update to fail is hidden within Update, so for the message to be "The update failed because no user was found" would be causing a leak of implementation details between the abstraction layers. If you wanted to specify that level of detail, that message would need to go in an exception thrown by Update itself.

Likewise, only refactor to throwing your own Exception sub-class if that provides some useful information that you find yourself needing higher up the call chain. Will the code calling Update() have a different way of handling a UserNotFoundException than it would a ValidationException? If not, then don't bother with your own Exception type.

If you're writing a library to be used by some other, external, code, you have to be a little more pro-active in working out when providing special messages or custom Exception types will be useful, rather than just waiting until there's a need. But the same general principles will apply.

Body:
In this particular situation, a better option may be to use LINQ's Single method, as so:

public void Update()
{
    var user = db.users.Single(u => u.userid == id);
    // update the user record
}

Single already does exactly what you want: it throws an Exception if there are 0 or more than 1 results matching the predicate.

At this point you can decide whether you're happy for the exception thrown by Single to bubble up, or whether you want to wrap it in one with a more useful message, or a specific type. The general pattern for this would be:

public void Update()
{
    try
    {
        var user = db.users.Single(u => u.userid == id);
    }
    catch(SomeExceptionType ex)
    {
        throw new SomeOtherExceptionType("Useful message here", ex);
    }
    // update the user record
}

(Notice passing ex to the SomeOtherExceptionType constructor here. This allows the information about the original exception to be preserved, as is usually good general practice)

As I said in the comment, the choice of how exactly you do this is probably not overly important. My advice would be to start with the simplest option- in this case allowing Single to throw its own exception- and refactor as needed.

If you find yourself with the need to display or log a more specific exception message, either wrap the exception in this method, or higher up the call chain as appropriate. The principle to where you do this should be avoiding leaking between your abstraction levels. Consider the following:

public void HighLevelMethod()
{
    try
    {
        DataAccessClass.Update();
    }
    catch(Exception ex)
    {
        throw new SomeKindOfException("What should I say here?", ex);
    }
}

The message here should be at an appropriate abstraction level for HighLevelMethod. Something along the lines of "The update failed" (though ideally something a bit more useful!). The exact reason for the update to fail is hidden within Update, so for the message to be "The update failed because no user was found" would be causing a leak of implementation details between the abstraction layers. If you wanted to specify that level of detail, that message would need to go in an exception thrown by Update itself.

Likewise, only refactor to throwing your own Exception sub-class if that provides some useful information that you find yourself needing higher up the call chain. Will the code calling Update() have a different way of handling a UserNotFoundException than it would a ValidationException? If not, then don't bother with your own Exception type.

If you're writing a library to be used by some other, external, code, you have to be a little more pro-active in working out when providing special messages or custom Exception types will be useful, rather than just waiting until there's a need. But the same general principles will apply.


答:
I don't use Entity Framework but I think the same rule applies. What I usually do is wrap all the database calls within a lambda and reuse that block of code for every operation. Outside the lambda I use a try/catch block, so any exception gets routed to the same path, therefore I don't need to explicity treat each error on their own. If the result happens to throw an exception, I rollback otherwise I commit.

If there is a special message that I need to send information to the client, usually I throw an inner exception into the lambda code so it gets bubbled outside the lambda and the client recieves a non-technical message.

In my opinion all the exceptions should be logged somehow, again I do this at a higher level, outside the lambda as a warning (e.g. a referential integrity error is not necessary a bug, but a missing value).

As for the Insert / Update logic you're showing it depends whether you are using one method for create and another method for update. If this is the case, then you should raise an exception if the id is not found on the update method. However, I usually like to "upsert" rather than having two methods so like you do, if the id is not found on the database, I assume this is an insert.

Maybe looking into this example it will be clear what I mean: Database Wrapper


答:
The point of writing custom exceptions is that you intend to do something useful with them.

Is showing them to the user "useful"?

Probably not.  They look scary.

Is logging them to a file for later examination "useful"?

Possibly, especially if the application is about to keel over and die because you're doing this in a "global" exception handler (which is about all they're good for).

Is catching a particular Type of exception and handling it (i.e. writing code to deal with the problem as it happens and to correct that problem, preferably without the user knowing anything about it) "useful"?

Oh yes!

Why use custom Exception Types?  Because that's how most languages expect to identify exceptions.  Look at "catch" clauses - they look for specific Types of Exception.  Sorry to say it but I would vehemently disagree with your friend's recommendation - throwing the same [class of] ValidationException [objects] all over the place but relying on the Text property to explain what's going on.  That's only useful in one scenario - where you show Exceptions directly to the user and that's a pretty poor practice, in my book anyway.


问:
Hide admin menu if no admin option is available
If you have a menu "Admin tasks" and different admin tasks (like 10) that you could separately assign to each user, but there are users who don't have any admin tasks, how would you deal with "Hiding admin menu"  for those users?

I was thinking of 3 ways:

1) Javascript, check if Admin menu is empty and then hide it.

2) Check for all permissions in Admin menu, with a counter, and show it if counter > 0. And then also re-check the permissions for each item to show.

3) Save all permissions in associative array. Test all and assign ' true' to granted items. When building the menu, have a function that tests if there is at least one permission granted. I wouldn't need to re-check permissions against DB, just against the array for each item.

Is there any better way?

答:
Id depends. Do we have users that are not admin and can't have admin tasks? Then it's option 3) because the logic for displaying any admin-associated things should not even be called.

If we have admins with an empty task list, then Option 1) is correct/best. Option 2) would have the drawback that if it comes, that you later want to port it to another environment with different view and you want to show an empty admin-task-menu (for whatsoever reason) you have a problem. It is about how data are displayed not what data are to be displayed and that would be CSS or if CSS is not sufficient then CSS with javascript support.


答:
You haven't specified neither the template engine you use, nor the framework, so it's difficult to be more specific, but usually, template engines let you display specific HTML for a list, and a different HTML if the list contains nothing. In Django, for example, the syntax is the following:

```<code><ul>
{% for task in administrative_tasks %}
    <li>{{ task.name }}</li>
{% empty %}
    <li>You should be an administrator to access the tasks.</li>
{% endfor %}
</ul>
</code>```

Note: you added "security" tag to your question. Displaying or not a link reserved to administrators on a web page has nothing to do with security. If you need to be sure that non-administrators cannot access a specific resource, you should check their permissions during the request and return 401 Unauthorized or 403 Forbidden accordingly.

Title: Hide admin menu if no admin option is available

Body:
If you have a menu "Admin tasks" and different admin tasks (like 10) that you could separately assign to each user, but there are users who don't have any admin tasks, how would you deal with "Hiding admin menu"  for those users?

I was thinking of 3 ways:

1) Javascript, check if Admin menu is empty and then hide it.

2) Check for all permissions in Admin menu, with a counter, and show it if counter > 0. And then also re-check the permissions for each item to show.

3) Save all permissions in associative array. Test all and assign ' true' to granted items. When building the menu, have a function that tests if there is at least one permission granted. I wouldn't need to re-check permissions against DB, just against the array for each item.

Is there any better way?

Body:
You haven't specified neither the template engine you use, nor the framework, so it's difficult to be more specific, but usually, template engines let you display specific HTML for a list, and a different HTML if the list contains nothing. In Django, for example, the syntax is the following:

<ul>
{% for task in administrative_tasks %}
    <li>{{ task.name }}</li>
{% empty %}
    <li>You should be an administrator to access the tasks.</li>
{% endfor %}
</ul>

Note: you added "security" tag to your question. Displaying or not a link reserved to administrators on a web page has nothing to do with security. If you need to be sure that non-administrators cannot access a specific resource, you should check their permissions during the request and return 401 Unauthorized or 403 Forbidden accordingly.


问:
Send mapped data from server-side code to client-side code
I'm developing a application based on two technologies: ASP.net (SharePoint) and JavaScript.

I use server-side code for retrieve data from database and manipulate it whereas I use client-side code for build front-end(I'm using JSON format).

I have very problem with this "architecture" because ASP.net is strong-type whereas JavaScript is less-type. My data "jumps" from front-end to back-and and vice versa.

How can I have my model class in client-side code too?

答:
As of today there are many (much many if that's the case) javascript frameworks that allow you to model on the client. Among all the features they offer you can validate/calculate the data is correct before sending it to the server.

However when the data gets into the server, it is your responsability to make sure everything is ok. You should never trust 100% on client side validations, because some skilled user might change that logic for you.

I would suggest to dive into KnockoutJs framework and play with it until you got the point. Later move to AngularJs which is more powerful but more complex also.


问:
Why would Square inheriting from Rectangle be problematic if we override the SetWidth and SetHeight methods?
If a Square is a type of Rectangle, than why can't a Square inherit from a Rectangle? Or why is it a bad design?

I have heard people say:

If you made Square derive from Rectangle, then a Square should be
  usable anywhere you expect a rectangle

What is the problem here? And why would Square be usable anywhere you expect a rectangle? It would only be usable if we create the Square object, and if we override the SetWidth and SetHeight methods for Square than why would there be any issue?

If you had SetWidth and SetHeight methods on your Rectangle base class
  and if your Rectangle reference pointed to a Square, then SetWidth and
  SetHeight don't make sense because setting one would change the
  other to match it. In this case Square fails the Liskov Substitution
  Test with Rectangle and the abstraction of having Square inherit from
  Rectangle is a bad one.

Can someone explain the above arguments? Again, if we over-ride SetWidth and SetHeight methods in Square, wouldn't it resolve this issue?

I have also heard/read:

The real issue is that we are not modeling rectangles, but rather
  "reshapable rectangles" i.e., rectangles whose width or height can be
  modified after creation (and we still consider it to be the same
  object). If we look at the rectangle class in this way, it is clear
  that a square is not a "reshapable rectangle", because a square cannot
  be reshaped and still be a square (in general). Mathematically, we
  don't see the problem because mutability doesn't even make sense in a
  mathematical context

Here I believe "re-sizeable" is the correct term. Rectangles are "re-sizeable" and so are squares. Am I missing something in the above argument? A square can be re-sized like any rectangle.

答:
Subtypes and, by extension, OO programming, often rely on the Liskov Substitution Principle, that any value of type A can be used where a B is required, if A <= B. This is pretty much an axiom in OO architecture, ie. it is assumed that all subclasses will have this property (and if not, the subtypes are buggy and need to be fixed).

However, it turns out that this principle is either unrealistic/unrepresentative of most code, or indeed impossible to satisfy (in non-trivial cases)! This problem, known as the square-rectangle problem or the circle-ellipse problem ( http://en.wikipedia.org/wiki/Circle-ellipse_problem ) is one famous example of how difficult it is to fulfil.

Note that we could implement more-and-more observationally-equivalent Squares and Rectangles, but only by throwing away more and more functionality until the distinction is useless.

As an example, see http://okmij.org/ftp/Computation/Subtyping/


问:
How to deal with team members writing bad code
Our team consits of junior and senior developers. Problem I am facing is with the code written by seniors. They are not following MINIMUM coding standards. I am also still learning but I wouldn't declare the inline style or give improper names for variables and controls. I tried to mention it indirectly but they were like we can take it up later and since its agile, we should move on. But my problem is when I start working on my task, it makes me feel bad and I would focus more on refactor rather than on my task. I am not sure how to deal with this situation.

PS: I am sure this question has been asked many times. But any advise is much appreciated.

答:
A couple of things.

Don't assume that your seniors don't know what they're doing.  They may have very good reasons why they made the decisions that they did; ask them why (in a non-argumentative way).

Code that is already written, backed by unit tests, and declared functionally complete by your superiors can be safely ignored.  That's what you should do with it: ignore it, until it becomes necessary to further maintain it, for whatever reason.

Based on your cursory description, it sounds like your team is under significant time pressure.  Compromises are made under those conditions; that's just the way it is.

Choose your battles wisely.  Only fight the ones that need fighting.


答:
What you're describing runs afoul of what's called the Liskov Substitution Principle. The basic idea of the LSP is that whenever you use an instance of a particular class, you should always be able to swap in an instance of any subclass of that class, without introducing bugs.

The Rectangle-Square problem isn't really a very good way to introduce Liskov. It tries to explain a broad principle using an example that is actually quite subtle, and runs afoul of one of the most common intuitive definitions in all of mathematics. Some call it the Ellipse-Circle problem for that reason, but it's only slightly better as far as this goes. A better approach is to take a slight step back, using what I call the Parallelogram-Rectangle problem. This makes things much easier to understand.

A parallelogram is a quadrilateral with two pairs of parallel sides. It also has two pairs of congruent angles. It's not hard to imagine a Parallelogram object along these lines:

class Parallelogram {
    function getSideA() {};
    function getSideB() {};
    function getAngleA() {};
    function getAngleB() {};
    function setSideA(newLength) {};
    function setSideB(newLength) {};
    function setAngleA(newAngle) {};
    function setAngleB(newAngle) {};
}
```

<p>One common way to think of a rectangle is as a parallelogram with right angles. <strong>At first glance, this might seem to make Rectangle a good candidate for inheriting from Parallelogram</strong>, so that you can reuse all that yummy code. However:</p>

<pre class="lang-js prettyprint-override"><code>class Rectangle extends Parallelogram {
    function getSideA() {};
    function getSideB() {};
    function getAngleA() {};
    function getAngleB() {};
    function setSideA(newLength) {};
    function setSideB(newLength) {};

    /* BUG: Liskov violations ahead */
    function setAngleA(newAngle) {};
    function setAngleB(newAngle) {};
}
</code>```

Why do these two functions introduce bugs in Rectangle? The problem is that you can't change the angles in a rectangle: they're defined as always being 90 degrees, and so this interface doesn't actually work for Rectangle inheriting from Parallelogram. If I swap a Rectangle into code that expects a Parallelogram, and that code tries to change the angle, there will almost certainly be bugs. We've taken something that was writeable in the subclass and made it read-only, and that's a Liskov violation.

Now, how does this apply this to Squares and Rectangles?

When we say that you can set a value, we generally mean something a little stronger than just being able to write a value into it. We imply a certain degree of exclusivity: if you set a value, then barring some extraordinary circumstances, it will stay at that value until you set it again. There are a lot of uses for values that can be written to but do not stay set, but there are also many cases that depend on a value staying where it is once you set it. And that is where we run into another problem.

class Square extends Rectangle {
    function getSideA() {};
    function getSideB() {};
    function getAngleA() {};
    function getAngleB() {};

    /* BUG: More Liskov violations */
    function setSideA(newLength) {};
    function setSideB(newLength) {};

    /* Liskov violations inherited from Rectangle */
    function setAngleA(newAngle) {};
    function setAngleB(newAngle) {};
}
```

Our Square class inherited bugs from Rectangle, but it has some new ones. The issue with setSideA and setSideB is that neither of these is truly settable anymore: you can still write a value into either one, but it will change out from under you if the other one is written to. If I swap this for a Parallelogram in code that depends on being able to set sides independently of one another, it's going to freak out.

That's the issue, and it's why there's a problem with using Rectangle-Square as an introduction to Liskov. Rectangle-Square depends on the difference between being able to write to something and being able to set it, and that's a much more subtle difference than being able to set something versus having it be read-only. Rectangle-Square still has value as an example, because it documents a fairly common gotcha that has to be watched out for, but it shouldn't be used as an introductory example. Let the learner get some grounding in the basics first, and then throw something harder at them.

Title: Why would Square inheriting from Rectangle be problematic if we override the SetWidth and SetHeight methods?

Body:
If a Square is a type of Rectangle, than why can't a Square inherit from a Rectangle? Or why is it a bad design?

I have heard people say:

If you made Square derive from Rectangle, then a Square should be
  usable anywhere you expect a rectangle

What is the problem here? And why would Square be usable anywhere you expect a rectangle? It would only be usable if we create the Square object, and if we override the SetWidth and SetHeight methods for Square than why would there be any issue?

If you had SetWidth and SetHeight methods on your Rectangle base class
  and if your Rectangle reference pointed to a Square, then SetWidth and
  SetHeight don't make sense because setting one would change the
  other to match it. In this case Square fails the Liskov Substitution
  Test with Rectangle and the abstraction of having Square inherit from
  Rectangle is a bad one.

Can someone explain the above arguments? Again, if we over-ride SetWidth and SetHeight methods in Square, wouldn't it resolve this issue?

I have also heard/read:

The real issue is that we are not modeling rectangles, but rather
  "reshapable rectangles" i.e., rectangles whose width or height can be
  modified after creation (and we still consider it to be the same
  object). If we look at the rectangle class in this way, it is clear
  that a square is not a "reshapable rectangle", because a square cannot
  be reshaped and still be a square (in general). Mathematically, we
  don't see the problem because mutability doesn't even make sense in a
  mathematical context

Here I believe "re-sizeable" is the correct term. Rectangles are "re-sizeable" and so are squares. Am I missing something in the above argument? A square can be re-sized like any rectangle.

Body:
What you're describing runs afoul of what's called the Liskov Substitution Principle. The basic idea of the LSP is that whenever you use an instance of a particular class, you should always be able to swap in an instance of any subclass of that class, without introducing bugs.

The Rectangle-Square problem isn't really a very good way to introduce Liskov. It tries to explain a broad principle using an example that is actually quite subtle, and runs afoul of one of the most common intuitive definitions in all of mathematics. Some call it the Ellipse-Circle problem for that reason, but it's only slightly better as far as this goes. A better approach is to take a slight step back, using what I call the Parallelogram-Rectangle problem. This makes things much easier to understand.

A parallelogram is a quadrilateral with two pairs of parallel sides. It also has two pairs of congruent angles. It's not hard to imagine a Parallelogram object along these lines:

class Parallelogram {
    function getSideA() {};
    function getSideB() {};
    function getAngleA() {};
    function getAngleB() {};
    function setSideA(newLength) {};
    function setSideB(newLength) {};
    function setAngleA(newAngle) {};
    function setAngleB(newAngle) {};
}

One common way to think of a rectangle is as a parallelogram with right angles. At first glance, this might seem to make Rectangle a good candidate for inheriting from Parallelogram, so that you can reuse all that yummy code. However:

class Rectangle extends Parallelogram {
    function getSideA() {};
    function getSideB() {};
    function getAngleA() {};
    function getAngleB() {};
    function setSideA(newLength) {};
    function setSideB(newLength) {};

    /* BUG: Liskov violations ahead */
    function setAngleA(newAngle) {};
    function setAngleB(newAngle) {};
}

Why do these two functions introduce bugs in Rectangle? The problem is that you can't change the angles in a rectangle: they're defined as always being 90 degrees, and so this interface doesn't actually work for Rectangle inheriting from Parallelogram. If I swap a Rectangle into code that expects a Parallelogram, and that code tries to change the angle, there will almost certainly be bugs. We've taken something that was writeable in the subclass and made it read-only, and that's a Liskov violation.

Now, how does this apply this to Squares and Rectangles?

When we say that you can set a value, we generally mean something a little stronger than just being able to write a value into it. We imply a certain degree of exclusivity: if you set a value, then barring some extraordinary circumstances, it will stay at that value until you set it again. There are a lot of uses for values that can be written to but do not stay set, but there are also many cases that depend on a value staying where it is once you set it. And that is where we run into another problem.

class Square extends Rectangle {
    function getSideA() {};
    function getSideB() {};
    function getAngleA() {};
    function getAngleB() {};

    /* BUG: More Liskov violations */
    function setSideA(newLength) {};
    function setSideB(newLength) {};

    /* Liskov violations inherited from Rectangle */
    function setAngleA(newAngle) {};
    function setAngleB(newAngle) {};
}

Our Square class inherited bugs from Rectangle, but it has some new ones. The issue with setSideA and setSideB is that neither of these is truly settable anymore: you can still write a value into either one, but it will change out from under you if the other one is written to. If I swap this for a Parallelogram in code that depends on being able to set sides independently of one another, it's going to freak out.

That's the issue, and it's why there's a problem with using Rectangle-Square as an introduction to Liskov. Rectangle-Square depends on the difference between being able to write to something and being able to set it, and that's a much more subtle difference than being able to set something versus having it be read-only. Rectangle-Square still has value as an example, because it documents a fairly common gotcha that has to be watched out for, but it shouldn't be used as an introductory example. Let the learner get some grounding in the basics first, and then throw something harder at them.


答:
They are not following MINIMUM coding standards.

If it's not your job to police the coding of others, then don't do it.  It's a classic way for juniors to make a bad name for themselves.

See this question for a similar discussion: https://softwareengineering.stackexchange.com/questions/78100/how-do-i-tell-a-senior-programmer-that-i-disagree-with-him

Related: A blog post I wrote about disagreeing, and part of that is knowing your place and when it's appropriate to disagree and when it's not: How to disagree without being disagreeable

Title: How to deal with team members writing bad code

Body:
Our team consits of junior and senior developers. Problem I am facing is with the code written by seniors. They are not following MINIMUM coding standards. I am also still learning but I wouldn't declare the inline style or give improper names for variables and controls. I tried to mention it indirectly but they were like we can take it up later and since its agile, we should move on. But my problem is when I start working on my task, it makes me feel bad and I would focus more on refactor rather than on my task. I am not sure how to deal with this situation.

PS: I am sure this question has been asked many times. But any advise is much appreciated.


问:
Programming language constructs for cache optimization?
Clearly optimizing cache usages is bound to improve my program efficiency. Surprisingly, I don't see too many programming languages actually having this sort of a feature. So here's my question:

What kind of language constructs have you seen that help improving cache usage?

How to innovate on cache usage since most systems won't easily reveal stuff like their L1 cache size easily? (Windows does have API or maybe /proc/cpuinfo on Linux, but I am looking for something simpler for the intermediate developer)

答:
there's no trivial answer here. in a multiprocessing system (i.e. any modern OS), you can't make many assumptions about the state of virtual memory. you can make some general observations regarding data structures though. hashing techniques may allow you to develop a more reliable affinity between data and storage, whereas data structures like trees will tend to employ offsets that degrade the effectiveness of caching...BUT take this all with a huge caveat...profiling the benefits of one technique over another is going to be extremely difficult and specific to your own architecture and memory hierarchy.

the shortest answer here is for the "intermediate developer", you are far better off using well-tested libraries that have clearly stated performance bounds and well-understood memory consumption patterns. trying to optimize for caching on a specific hardware platform would seem to be a painful last resort for the most difficult problems.


问:
Is there a specific name for the "Square inherits from Rectangle" paradox?
A certain failure of OOP is shown with a class Square inheriting from Rectangle, where logically Square is a specialization of Rectangle and should therefore inherit from it, but everything falls apart when you attempt to change a Square's length or width.

Is there a specific term for describing what is going wrong with that case?

答:
At a more fundamental level than the Liskov Substitution Principle, this is a category error or category mistake

In the context of modeling behaviour a square simply is not a type of rectangle.

When you realize this the problem evaporates since the initial assumption (a square is a type of rectangle) is removed from play.

The issue with this answer is that since school it is drilled into anyone doing geometry that a square is a type of rectangle. But it is very important to understand that this is only true within a very specific context (the classification of geometric shapes based on the properties of their internal angles). In terms of behaviour a square is not a rectangle. To view one set of classification in the wrong context is a category mistake.


问:
Is it okay to define a [] method in ruby's NilClass?
Ruby by default does not include the method [] for NilClass

For example, to check if foo["bar"] exists when foo may be nil, I have to do:

```<code>foo = something_that_may_or_may_not_return_nil
if foo && foo["bar"]
  # do something with foo["bar"] here
end
</code>```

If I define this method:

```<code>class NilClass
  def [](arg)
    nil
  end
end
</code>```

Something like that would make this possible, even if foo is nil:

```<code>if foo["bar"]
  # do something with foo["bar"]
end
</code>```

Or even:

```<code>if foo["bar"]["baz"]
  # do something with foo["bar"]["baz"] here
end
</code>```

Question:
Is this a good idea or is there some reason ruby doesn't include this functionality by default?

EDIT July 2017: My core complaint was the unwieldy foo && foo["bar"] && foo ["bar"]["baz"] idiom required to access nested values when at any point the value may be nil. As of Ruby 2.3, Array#dig and Hash#dig exist, which addresses my concern. Now I can use the following idiom!

```<code>if foo && foo.dig("bar", "baz")
  # do something
end

# Note that errors will still occur if a value isn't what you expect. e.g.
foo = { "a" => { "b" => "c" } }
foo && foo.dig("a", "b", "c") # raises TypeError: String does not have #dig method
</code>```

答:
I wrote a gem designed for just this case. I came across this question when looking for a solution, so I thought I'd post here on what I ended up with.

Them gem is called Dottie and is available at https://github.com/nickpearson/dottie.

Here's a quick sample of how it's designed to be used:

```<code>car = {
  'type' => {
    'make' => 'Tesla',
    'model' => 'Model S'
  }
}

# normal Hash access assumes a certain structure
car['type']['make']     # => "Tesla"
car['specs']['mileage'] # => # undefined method `[]' for nil:NilClass

# Dottie lets you reach deep into a hash with no assumptions
d = Dottie(car)
d['type.make']     # => "Tesla"
d['specs.mileage'] # => nil
</code>```

There's lots more documentation on the GitHub project page. Hope this helps someone.

Body:
I wrote a gem designed for just this case. I came across this question when looking for a solution, so I thought I'd post here on what I ended up with.

Them gem is called Dottie and is available at https://github.com/nickpearson/dottie.

Here's a quick sample of how it's designed to be used:

car = {
  'type' => {
    'make' => 'Tesla',
    'model' => 'Model S'
  }
}

# normal Hash access assumes a certain structure
car['type']['make']     # => "Tesla"
car['specs']['mileage'] # => # undefined method `[]' for nil:NilClass

# Dottie lets you reach deep into a hash with no assumptions
d = Dottie(car)
d['type.make']     # => "Tesla"
d['specs.mileage'] # => nil

There's lots more documentation on the GitHub project page. Hope this helps someone.


答:
The logical result of this is that a specialization might only accept some values of input for its method or might change some values in order to stay consistent. But isn't that OK, since guarding its internal consistency is what an object should do?

The issue isn't really what the object does internally to implement the message it is asked to perform (eg setWidth). The issue is what the caller understands the end result of the message to be.

Both a setWidth method on a rectangle that only sets width, and a setWidth method on a square that sets both width and height, are perfectly valid so long as it is clear to anyone making the calls what these methods do.

The problem is when you say a square is a rectangle, and then look at the setWidth method of a rectangle. That method puts the object into a particular state. It is understood by all who call the method that it will update the width and only the width.

When you say a square is a rectangle you are saying to anyone working with the square that everything you knew about rectangles still holds when working with squares. And one of the things that the programmer knew about rectangles was that setWidth updated only the width. That is known behaviour.

So the programmer knows what this method does, she knows that square is a rectangle, so she knows that setWidth will only update width.

Except it doesn't only update width, it now updates height as well. The program has just lied to the programmer, it has broken its contract.

This example might seem trivial, but it becomes much more important when you factor in polymorphism.

You might not know what shape you have, you might not know if you have a rectangle or a square. If you know that a square is a rectangle then you know that what ever object you have it will behave the way you expect a rectangle to behave if you apply rectangle behaviour to it.

But of course if it doesn't then you have a serious problem because you now cannot trust your objects to behave the way you expect them to, and thus you cannot trust your code to do what you expect it to do.

Instead what you need to do is break the connection, tell the programmer that a square is NOT a rectangle and that the programmer needs to know if they have a square or not and they need to understand what behaviour a square specifically has because it is not the same as a rectangle.

Title: Is inheritance that adds rules bad?

Body:
I got into a debate on this question which distilled to if it is a good idea for a specialization of a class to add business rules. Unfortunately this point got trampled in the comments so I'm asking it again as a separate question.

I believe two things:

An object is responsible for its internal consistency

A specialization/child class has more specific rules than the super class which can be seen as the general case.

The logical result of this is that a specialization might only accept some values of input for its method or might change some values in order to stay consistent. But isn't that OK, since guarding its internal consistency is what an object should do?

A point many people were making is that some code could break if it would make assumptions. For example that setting the width would not change the height of a square. However wouldn't that be bad code? Since you make assumptions on how the object does something instead of just telling it what to do and not worry about it?

If we would not write code like that almost all overloading would have problems. How often doesn't overloading add an extra fail condition or more internal logic that might be seen via other parts of the interface? Maybe the point an old professor of me once made is correct: "you should only ever use inheritance to overload the constructor". At the time that seemed a bit strict but now it seems like the only way to guarantee these kinds of problem never happening. To use the old square: rectangle analogy again:

```<code>public class Rectangle
{
    private int width, height;

    public Rectangle(int width, int height){this.width = width; this.height = height;}

    public void SetWidth... SetHeight...
}

public class Square : Rectangle
{
    public Square(int diameter) : base(diameter, diameter) {}

    public void SetDiameter...
}
</code>```

Note: I hope we can play this question a little bit less 'on the man' than the question that inspired it. I've been on Stack Exchange for more than three years but I was quite intimidated by the type of responses here.


问:
Is it okay to not completely understand code functionality?
As I am currently struggling with learning WCF for a project at work, for the past several days I have been looking at online tutorials and examples on the best way to make a WCF client; and today, when I told my boss I was having a hard time finding good tutorials because some of them would not go into details with their examples (for instance showing a piece of code that works but not explaing why exactly, or making an example with just a few lines instead of at a larger scale), he told me that I should not try to understand them completely, because there are times where a code will just do what it does and I should leave it at that (he gave me the example that when doing calculus, for instance, we use formulas that we don't know how they were conceived or how they work, we just know that they do and we use them).

And this bothered me because I have always been told that it's really important to understand your code, and that just copying and pasting without knowing HOW it works is practically a sin; which is why I always take my time in understanding something before moving forward with it. And it's not like I'm trying to understand how a particular class works at an assembly language level, I just want to know why a set of instructions does the trick, and why another one doesn't, or why both do and under what circumstances. But my boss tells me that I will end up wasting time obsessing over these little details, and I should just skip it. So my question is, is he right? Is it okay to understand your code only to a certain extent and keep going, and have I only been obsessing over little things that don't matter?

答:
In the great book pragmatic programmer this is called "programing by coincidence" (http://pragprog.com/the-pragmatic-programmer/extracts/coincidence)

The bigger problem with this is, if you don't know why a piece of code works when this piece of code fails for whatever reason, you don't know why fails and you can't fix it.


问:
Do you have to have boxing of primitives in OO language?
Is boxing of primitives required in OO languages to keep them consistent with the rest of the object system (generics etc.)?

Or is it avoidable - is it possible to avoid any additional performance cost of having both primitives and objects in a language?

One solution I can come up on the spot is having references big enough to store values of every possible primitive type.

Are there other (better) solutions and are there implemented in popular languages?

答:
Depends on the language.

In C# 1.0/1.1, boxing was unavoidable quite often - when a method has an object parameter and one tried to pass in a value type (think primitive type, though not exactly), it had to be boxed in order to be passed in as a reference type.

With C# 2 and generics support, most such boxing went away, as a generic type could be used.


答:
Because of the way processors are architected, you need boxing at some level in order to get both reasonable efficiency and a unified type model.  However, the boxing doesn't need to be manually specified by the programmer, and in some languages it is handled automatically behind the scenes for you.

Take Scala, for example.  Int is derived from an AnyVal, which is derived from an Any, which is Scala's top-level class.  Syntactically, you can treat it like any other object, but the compiler will treat it like a primitive in appropriate contexts, internally doing boxing and unboxing as necessary.  The point is, the programmer doesn't have to care.  Even nicer, in Scala this is implementing using implicits, so programmers can seamlessly implement their own custom automatic boxing and unboxing if the built-in ones aren't sufficient.

If you're not fortunate enough to be using a language like Scala, generics can obviate the need for manual boxing in many situations.

Title: Do you have to have boxing of primitives in OO language?

Body:
Is boxing of primitives required in OO languages to keep them consistent with the rest of the object system (generics etc.)?

Or is it avoidable - is it possible to avoid any additional performance cost of having both primitives and objects in a language?

One solution I can come up on the spot is having references big enough to store values of every possible primitive type.

Are there other (better) solutions and are there implemented in popular languages?


答:
I don't completely agree with the statement: "You can't just copy/paste code without understanding how it works."

Forgive my stupidity, but from a programatic viewpoint, isn't including a library of methods/functions which I don't know they work essentially the same as copying/pasting that code into my own?

I.e., if I'm programming using jQuery, I include the jQuery library and then use it. Using Robert Harvey's answer, this is fine since jQuery has abstracted out all of the things I need to use without having to write the code myself or even understand it completely. Do I really need to know exactly how jQuery works behind-the-scenes before I can use it?

Having said that, I agree with the principle behind the statement, but wanted to point out that the concept of "copying/pasting" code (without complete comprehension) is actually more common than one might think and not as onerous as this statement would make it seem.

Title: Is it okay to not completely understand code functionality?

Body:
As I am currently struggling with learning WCF for a project at work, for the past several days I have been looking at online tutorials and examples on the best way to make a WCF client; and today, when I told my boss I was having a hard time finding good tutorials because some of them would not go into details with their examples (for instance showing a piece of code that works but not explaing why exactly, or making an example with just a few lines instead of at a larger scale), he told me that I should not try to understand them completely, because there are times where a code will just do what it does and I should leave it at that (he gave me the example that when doing calculus, for instance, we use formulas that we don't know how they were conceived or how they work, we just know that they do and we use them).

And this bothered me because I have always been told that it's really important to understand your code, and that just copying and pasting without knowing HOW it works is practically a sin; which is why I always take my time in understanding something before moving forward with it. And it's not like I'm trying to understand how a particular class works at an assembly language level, I just want to know why a set of instructions does the trick, and why another one doesn't, or why both do and under what circumstances. But my boss tells me that I will end up wasting time obsessing over these little details, and I should just skip it. So my question is, is he right? Is it okay to understand your code only to a certain extent and keep going, and have I only been obsessing over little things that don't matter?


答:
Exercise the practice of openness in a professional setting - if you feel that their code may be improved and you have a good reason to assert they should be doing it differently, there should be nothing in your way to suggest it (as long as you aren't condescending or such).
 If you work somewhere where openness is frowned upon, I don't know if that's particularly healthy. They may have some excellent insight as to why they're doing something that you didn't notice or the opposite - someone is bound to learn something by just asking questions :)</p>


问:
Reason to treat internal class variables and functions inside a class as "separate" entities
Note:  there is a similar question that addresses my subject:  Better style for member variables?

... but that question does not address "dealing with large legacy code base and comprehension of functions that grew too large".  I am looking for confirmation or rejection of whether my situation warrants it to be a is a good enough reason to adopt a practice of writing internal-to-the-class functions as if they were separate entities, with their appropriate parameters and return values.

My question

Variables internal to a class are considered to be scoped as "globals" within contains of that class.  As such, these variables do not need to be included explicitly as parameters to the class' internal functions.  Further, if internal functions return values that may belong to existing inside-class variables, those also do not need to be returned explicitly.  You can just refer to them via using this object.  But, is doing so a good practice?

My question comes from the context of refactoring a huge legacy codebase.  As such, when I see a function inside a class that goes like $this->IamACute3000LineFunctionDoingInsanelyCuteStuffInASpaghettiCodeLikeWay(), I have little clue as to which in-class "global" variables it needs to do its job, and what exactly it returns.  This makes it hard and time consuming to deal with that code when any work is to be done on the class.  Thus, even though it may not make sense inside the class itself, I do see some merit in writing code like below, treating variables and parameters as if the function was written to be used outside of the class itself:

class HelloClass
{
   $private $name;
   $private $greeting;

   public function __construct($name)
   {
       $this->name = $name;

       //line of interest
       $this->greeting = $this->prepGreeting($this-name);
   }

   //function of interest
   private function prepGreeting($name)
   {
      return "Hello, $name";
   }

   public function getGreeting()
   {
       return $this->greeting;
   }
}

$sayHello = new HelloClass("Dennis");
print $sayHello->getGreeting();
```

<p>Here, <code>prepGreeting</code> is the function in question.  Surely, it looks a bit ridiculous... as it barely takes advantage of built-in class mechanisms, if at all.  It can be rewritten as such instead (with appropriate other constructor changes as well, which are not shown):</p>

```   private function prepGreeting()
   {
      $this->greeting = "Hello, " . $this->name;
   }
```

But then you have to actually read the function's body to understand what it does, what it touches and what it returns.

My question is this:

in my example, where I am dealing with large code where understanding a function takes time, I think there is a good reason to write internal class functions as if they were separate, not belonging to the class, as it will be superior for understanding what goes on inside the function, and what it returns.  This function will be self-contained and as such, it will help a lot with refactoring.  I could pluck that function out, bend the way I need it to bend, move it to another class, if I have to, thus making it easier to work with the class itself.  But, in general, would you recommend such function-writing practice when writing/designing classes?

Or would you recommend instead to use built-in this object, treating internal to the class variables as "class globals", even though doing so may impact readability/understanding/comprehension of the function if its size does grow, as it often does in real life projects?

Finally, am I missing any greater points while focusing on this specific function-writing-style issue?

Add-on

I do see merit in perhaps using some middle-ground, where function parameters are not passed to the function (function uses this object to get to those), but the function still returns values, instead of updating this object directly, and it is up to the caller to update this variable.  i.e. this will change my "line of interest" to this code:  $this->greeting = $this->prepGreeting(); and at least I will know what the function is supposed to return, at a glance.

答:
"When I see a function inside a class, yada yada..."  I think the important part to remember here is that the function is inside the class.  All of the relevant functionality is therefore confined with in the class ("encapsulation").  Your use of the words "global within the class" is not really relevant, in that respect.

All sane object-oriented languages work this way; they expect you to be able to manage the class's internal members satisfactorily, so long as the internal details of the class don't leak out.  If working with the internal members of a class has become  difficult, it means that the class has become too large and too complex, and probably needs to be divided up into smaller classes.

ContentLicense: CC BY-SA 4.0


答:
There are various approaches taken by other languages, that avoid having separate "boxed" and "unboxed" kinds of values.

In Python, all values (from integers to objects) act the same when used as references. It might feel like simple values act differently, but that's because type such as int and str objects are immutable. A similar approach is taken by Ruby and most other popular "scripting" type languages.

In Lisp, a value can be either a number or a reference to a cons cell. Some implementations combine these into a single machine word by reserving one or two of the high bits in the word to indicate the type of the value. For example, a 0 in the high bit might mean an integer value, but a 1 means the address of a cons cell. (There can be other adjustments applied such as shifting the address value left a couple of bits to access the whole address space, possible because the LSB of address bits are always 0 due to alignment constraints. All of this is highly implementation dependent.)

In C++, the generics mechanism (templates) allows you to write generic code that can handle primitive types such as int as well as polymorphic pointers. The underlying mechanism actually compiles the generic code more than once depending on the actual type with which the generic template is instantiated.


问:
Should I use branches for example uses of a github repo?
I'm working on a Github repo called Designemplate at https://github.com/benwatkinsart/Designemplate and was thinking of developing some example uses of the CSS file to show how it's used. Should I use a branch called examples and store them there?</p>

答:
Using branches for this is possible, but extremely awkward to use. I recommend using branches only for different stages of development, e.g. as suggested by the git-flow model.

When can branches get awkward? Always then when two branches represent different resources (not just different versions of the same resource), so that you might want to view both resources at the same time. As you can only have one branch checked out in your working directory, you'll either end up switching back and forth between branches, or cloning the repo into a second directory to have another branch checked out there – starting another repo just for the second resource would have been much easier.

Instead, just create an examples/ directory. It's the simplest, most intuitive solution to your problem.

I also notice that your repo is using the GitHub Pages feature, where your repo is accessible as a website (here https://benwatkinsart.github.io/Designemplate/). It would make sense to make your examples accessible via this website, and simply add a link from each example to the corresponding source on GitHub. The Pages features only displays items on the gh-pages branch, not from any other branches.


问:
The best way to open source my website
I'm creating a website where trust is a big issue, I want to prove by making it open source I actually do what I claim.

Question 1. If I make my source code open, how can I prove the actual website runs on this code?

But I also have a dilemma, it is a commercial project and I don't want others to run off with it and claim it theirs. So I think I need a correct license.

Question 2. What license is best for me? Currently I'm thinking about GPL v3.

答:
The point of publishing your web site code is that people don't have to trust you. If you publish your code as open source, then in theory they would be able to run your code privately on their web server and not rely on you. Of course this usually requires users of a certain minimum technical competence, or you would need to allow others to run your code on behalf of third parties (eg. Wordpress follows this model).

If there are trust issues between you and your users, then you may want to think at a higher level. Provide some way for people to verify that the instructions they give you have actually been carried out. For example, see End-to-end auditable voting systems for an example of this sort of thing.

Title: The best way to open source my website


答:
As others have mentioned, you should ask about the senior developer's choices in a non-confrontational way, but it might also be worth it to look into a few things.

First of all: is there a coding standard that the project follows?  If there is no coding standard defined, then nobody is breaking the coding standard.  The 'standard' may simply be to make new code look similar to the old code.  That's an unfortunate position to be in, but an ad-hoc coding standard is still a coding standard.

If there is a coding standard: who ensures its implementation?  Are all developers responsible, is it handled during review periods, etc.

I'll give you my example: I came onto a project that's just starting out.  We have senior members, but mostly juniors(myself included).  As it turned out, I was the one who was most concerned about a coding standard.  Our company and QA policies dictate that we have a standard, and since I was the one who brought it up it was my job to find one.

That turned out to be super easy.  There's a standard for Java set by Oracle, which makes that the obvious choice.  Next, I found a tool for Java called Checkstyle, which enforces coding standards for you.  Every time you make a change and save a file, Checkstyle runs over the file for any violations of the coding standard you have, and high lights all violations just like a warning. Additionally, it does a few static analysis tasks: N-Path complexity, cyclomatic complexity, etc. After that, I looked into Eclipse's formatter and found I could make that conform to our coding standard as well.  So now, after a minimal amount of set up, we have a tool that:

High lights coding standard violations

A formatter that can be invoked with ctrl + shift + F

Zero maintenance

No time is spent in code reviews for trivial coding standard issues(tab here, space there, comment needed here, etc)

So, ultimately, to really deal with maintaining a coding standard, I would:

Ask what the current standard is, is it defined somewhere, and are all developers aware of it?

Get a plan ready - do some homework and search for tools in your project's language that can help you do what I did.  Seriously: having a coding standard in place that everyone follows is great.  I ended up making it so easy to do that no one had a reason not to follow it.

Once you have a plan, try talking about it to your supervisor.  Tell them your plan, and more importantly: tell them how this could save them time in the future by having fewer defects in the code.


答:
No.  Boxing is required only when dealing with an "object" i.e. where the type is unknown.  Given generics without type erasure, there is little to no reason to do so.

The reason why Java and .Net have boxing is because generics were tacked on later.  The reason why Java does more boxing than .Net is a consequences of Java doing more boxing than was necessary and partly how they decided to implement generics.

Also "primitive types" are themselves a performance/size optimization, as such it is certainly conceivable of a system where that optimization was considered unnecessary.

The only use case I can think of for boxing in .net given generics is the Tag on controls -- i.e. a class exposing a property for users of the class, and not for use IN the class.  And even there, boxing could be avoided by requiring that it be a non-primitive class, a bit of extra work, but not unreasonably so.


答:
Question 1:

You can't. Your server is a black box. Nobody can see what code it is really running. Even when you configure your webserver to make the src-directory accessible to the public, you have no way to prove that it's really the src-directory used by the website and not a mock-directory you set up for the public.

Question 2:

The GPL only requires to relicense code under the same license when someone receives the program in code- or binary form. That means you can run a website on modified GPL code and don't have to disclose any of your modifications at the server-sided components, because you aren't giving them to anyone. You only give people the HTML output of your program, and the output of a GPL program isn't subject to the GPL.

But there is also the Affero General Public License (AGPL) which adds a new clause to the standard GNU GPL: It demands to give the sourcecode to "users interacting with it remotely through a computer network", which means anyone who visits the website. However, remember answer to question 1.

In case you want to publish your sourcecode but you only want this for reference purpose and don't want anyone to use it for anything, Open Source isn't the word you are looking for. What you mean is "shared source", which means that you publish the sourcecode, but do so under "all rights reserved" conditions, which forbids people to use it for their own purpose.

Title: The best way to open source my website

Body:
I'm creating a website where trust is a big issue, I want to prove by making it open source I actually do what I claim.

Question 1. If I make my source code open, how can I prove the actual website runs on this code?

But I also have a dilemma, it is a commercial project and I don't want others to run off with it and claim it theirs. So I think I need a correct license.

Question 2. What license is best for me? Currently I'm thinking about GPL v3.


问:
Where should salt hash values come from?
When adding salt values to a hash value for something like a password that cannot be stored in plain text, what is the best place to get the salt values come from? For context, let us suppose this is for passwords on a webpage login. </p>

答:
Use bcrypt and read this article as to normal hashes alone is not serious protection in this day and age.

Consider using SDR zero knowledge password protocol which has plenty of opensource libraries and is patent free.

SDR requires salt and the best place to get that is the client; time their keystrokes, mouse movements, hash their environment variables, random numbers, file creation times in their temp folder, to make salt at their end in an unpredictable way away from your server. SDR takes the salt, a large prime, the user password and generates a verifier key. You don't store a password it never leaves their machine but you can verify that they have the password which goes with the verifier key and the salt. It is immune from man in the middle and dictionary attacks. Encrypt the keys and salt in the database column just to be sure.


答:
No use directories for different content.

Use branches for content that is changing or being changed over time rather than using it to segregate types types of content.

Another option (if you don't want all those files in your base source control repository)... is to create a separate repository and then include that in the other one.  For example in rails you would make a gem, publish it and then refer to it in the Gemfile as a dependency.  You don't mention rails so your exact process may vary.

Another option is to have a top level directory for the project, to have directories for the templates and also a code directory, within which the .git repo resides.

Title: Should I use branches for example uses of a github repo?

Body: I'm working on a Github repo called Designemplate at https://github.com/benwatkinsart/Designemplate and was thinking of developing some example uses of the CSS file to show how it's used. Should I use a branch called examples and store them there?</p>


答:
TL;DR;

What I would say is that those are not exceptions to you because you should have checked them before calling update. By the time you got to that point of update the only thing that should fail is a network error, db lock, or db not available; behavior out of your control. If you check everything you are in control of then your application flow will be yours to control and not based on exceptions. Exceptions are expensive so you should avoid using them to control application flow.


问:
If this isn't a user story, what is it?
I'm with an org that is trying to transition to Agile. One thing that I've been struggling with is what they call user stories. In my experience, a user story would be this:

Use should be able to accomplish task x using tool y

During the sprint, we'd then design a solution to enable this.

However, this is what we're writing:

User should click on button A to go to page B to read text C where they will then select option D which will then redirect them to page E. Data F will be saved to the database.

To me, this reads as a solution, which is what the sprint is for.

Are the scenarios where the latter is actually a proper user story? Or, if not, is there a proper term for that type of detailed "solution description" within an Agile process?

答:
Have a look at the Wikipedia article for User Story Modeling.

Notice that, while subsequent steps involve things like GUI mockups and Story Boards, the very first step is gathering user stories, and they are quite specific:

Scenario Go-Dutch barbecue

Start: This Sunday Peter, Putri, and Peng meet at the park for a go-Dutch barbecue. They use the Group Account app to do the
  accounting.

Step 1: Peter brings the meat for $12. Peter adds this item to the Group Account app.

Step 2: Putri brings salad for $9. Peter adds this item, too. The app shows that by now the average share is $7 and that Peng still have
  to bring these $7 while Peter gets $5 out and Putri gets $2 out.

Step 3: ...

Your second example probably falls under the subcategory GUI Mockups.  But it's still considered "User Story Modeling."

Title: If this isn't a user story, what is it?


问:
Design of high performance file processing web application
I'm trying to design a web app with ability to scale but can't wrap my heads around few concepts. I want to design it right but im not a experienced programmer, i have more of a system engineering background.

Basic architecture look like this:

Web Server -> File processing server -> NoSQL DB -> Search server

So the main scenario is follows:

User uploads a file via site

File is send for processing to a server(python script)

Results of processing is send to NoSQL DB

Results processed by search server and returned to user

We can scale web frontends via load balancing. Something like nginx+apache.

Database scaling is taking care by Cassandra or MongoDB. Search scaling is taking care by elasticsearch or sphinx clustering.

Now I want to be able to add multiple file processing servers in case file uploaded is too big. So I need to somehow split file into chunks and process it simultaneously on multiple nodes plus if node goes down while working it shouldn't affect anything and data must be saved. So I need something else which will be allocating tasks to my file processing servers, balancing load and control execution of tasks.

How to design custom applications for that kind of things? Should I use message queuing?

答:
You will have to use ajax (or some async callback or a handler) to hit the server only when you have the whole file, that way you won't need to split the file into chunks. Just tell the user that his file are going to be processed and send him a message when its finished.

From there, you can have async worker method (on the server) per uploaded file to send it to the python script for processing.


答:
The second example you gave is certainly not a traditional User Story, which is generally formulated something like As a *role*, I want *goal/desire* so that *benefit*, but is what I would call 'acceptance criteria'.

According to the Wikipedia article linked above:

Every user story must at some point have one or more acceptance tests
attached, allowing the developer to test when the user story is done
and also allowing the customer to validate it. Without a precise
formulation of the requirements, prolonged nonconstructive arguments
may arise when the product is to be delivered.

Your "User should click on button A ..." scenario looks an awful lot like such an acceptance test.

Title: If this isn't a user story, what is it?

Body:
I'm with an org that is trying to transition to Agile. One thing that I've been struggling with is what they call user stories. In my experience, a user story would be this:

Use should be able to accomplish task x using tool y

During the sprint, we'd then design a solution to enable this.

However, this is what we're writing:

User should click on button A to go to page B to read text C where they will then select option D which will then redirect them to page E. Data F will be saved to the database.

To me, this reads as a solution, which is what the sprint is for.

Are the scenarios where the latter is actually a proper user story? Or, if not, is there a proper term for that type of detailed "solution description" within an Agile process?


问:
What do I gain by using the Strategy pattern in this case?
I wrote a program with Java that plays simple music. Currently chords have only one way ('strumming pattern') to be played. I want to expand this and create different 'strumming patterns' that chords can use to play their notes.

The Chord class has a play() method that is responsible for playing the chord. Currently it contains the logic for the only 'strumming pattern' of how the notes are played.

To add new strumming patterns, the simplest approach is to change play() to something like this:

```<code>void play(int strummingStyle){
    if(strummingStyle == REGULAR_STYLE) playRegular();
    if(strummingStyle == SOMETHING_ELSE_STYLE) playSomethingElse();
    // .. etc
}
</code>```

Have a method for each strumming style, and parameterize the method to play a specific style.

However using the Strategy pattern feels like a better approach. What I mean is to encapsulate each strumming pattern in a subclass of StrummingPattern and set the Chord to a specific strumming pattern: chord.setStrummingPattern(StrummingPattern pattern);.

play() would then simply delegate to the strumming pattern like so:

```<code>void play(){
    pattern.play();
}
</code>```

While this clearly feels like the better, more OO approach - I find that I can't explain myself what the actual benefits are. And it's important for me to actually understand why I'm doing something.

Please explain why using the Strategy pattern in a case like this is a better approach than the more naive 'a method represents a behavior' approach. What exactly are the Strategy pattern's benefits in this kind of situation? Why should I use it?

答:
"However using the Strategy pattern feels like a better approach"

Yes. :)

Your instincts are right on this one.

In OO, you want to avoid that kind of "if this, do this; if that do that" logic, because the type system handles that for you very elegantly. (I actually have an aversion to if...then logic in general, because as the logic branches it makes my brain hurt more and more).

(A corollary, if you're checking types with if blah instanceof Blah, then you probably need to think harder about your OO design, because you're cheating on polymorphism and peeking at the underlying type. The class should just know what it needs to do, and the caller should just know how to call it.)

The main advantage of the Strategy pattern is leveraging the dynamic dispatch aspect of the language to do the "if...then" block for you. So you only have to make sure your Strategy classes are correct and that the consumer of them calls the play() method correctly. It scales in complexity better, because you can just drop in new strategy classes over time. Testing is tons and tons easier, because it's all nicely decoupled.

...

If you want to convince yourself, do it both ways. Write an example with 5 alternatives as the block of "if...thens", and another example with 5 alternatives in the strategy pattern.

Then write unit tests to 100% coverage for both cases.

;)


答:
In the first example you need to modify an existing class to add new behaviour, in the second with the strategy pattern you can add new funcionality to your system adding new classes and without modify the current code (or with minimal modifications).

This has a lot of advantages:

Less risk of breaking existing functionality

Smaller classes vs classes that grow and grow

Better for teamwork, think in N programmers each one adding new "strumms" at the same time with the two approaches

Your systems its more extensible, in the future you can make this api public and other people can add new elements (chords, strumms) to your system

In terms of SOLID, the second solution its more Open-Close and as a consequence the resultant classes are more Single responsability.

Use SOLID, GRASP, or other OO principles like cohesion and coupling,think in the cost of adding new functionally, think in the cost of understanding the system for a new programmer as tools to evaluate your designs and learn to decide WHY a design its better or not than other. The patterns often offers good solutions or pointers (often not) you need to rely on more fundamental principles of OO to evaluate and know WHY, you are in the good direction if you "feel" that needs this Why's, its better to not use patterns than to use then blindly.

Title: What do I gain by using the Strategy pattern in this case?

Body:
I wrote a program with Java that plays simple music. Currently chords have only one way ('strumming pattern') to be played. I want to expand this and create different 'strumming patterns' that chords can use to play their notes.

The Chord class has a play() method that is responsible for playing the chord. Currently it contains the logic for the only 'strumming pattern' of how the notes are played.

To add new strumming patterns, the simplest approach is to change play() to something like this:

```<code>void play(int strummingStyle){
    if(strummingStyle == REGULAR_STYLE) playRegular();
    if(strummingStyle == SOMETHING_ELSE_STYLE) playSomethingElse();
    // .. etc
}
</code>```

Have a method for each strumming style, and parameterize the method to play a specific style.

However using the Strategy pattern feels like a better approach. What I mean is to encapsulate each strumming pattern in a subclass of StrummingPattern and set the Chord to a specific strumming pattern: chord.setStrummingPattern(StrummingPattern pattern);.

play() would then simply delegate to the strumming pattern like so:

```<code>void play(){
    pattern.play();
}
</code>```

While this clearly feels like the better, more OO approach - I find that I can't explain myself what the actual benefits are. And it's important for me to actually understand why I'm doing something.

Please explain why using the Strategy pattern in a case like this is a better approach than the more naive 'a method represents a behavior' approach. What exactly are the Strategy pattern's benefits in this kind of situation? Why should I use it?


答:
neither of those are user stories, though the first one is closer than the second

a user story should express what the user wants to do and why, but not how.

```<code>as a [user], i want to [do something], so that [benefit]
</code>```

a user story is a functional requirement, not a design specification

if what the user wants to do is complex, by all means draw screen mockups and navigation diagrams - but don't bother dressing up the design in story clothes; they don't fit, and they're not necessary

note: to really flesh out the requirements, use test scenarios, e.g.

```<code>given [preconditions]
when [triggering event/condition]
then [expected outcome]
</code>```

Title: If this isn't a user story, what is it?

Body:
neither of those are user stories, though the first one is closer than the second

a user story should express what the user wants to do and why, but not how.

as a [user], i want to [do something], so that [benefit]

a user story is a functional requirement, not a design specification

if what the user wants to do is complex, by all means draw screen mockups and navigation diagrams - but don't bother dressing up the design in story clothes; they don't fit, and they're not necessary

note: to really flesh out the requirements, use test scenarios, e.g.

given [preconditions]
when [triggering event/condition]
then [expected outcome]


问:
What is a good integration test strategy?
I'm getting started on a project wherein I want to have pretty thorough test coverage, and I have the luxury of driving the test strategy.  I've settled on a workable plan for unit testing, and I've also settled on using Gherkin to describe features and a port of Cucumber to run the scenarios as end-to-end acceptance tests.

The problem is that I sense that there is a gap in between those two layers.  I can test all my units in isolation, and I can test that my features work, but I can think of other things that I'm going to want to test.

I'm also coming from a different project with (poorly-implemented) automated tests that are a very brittle and are a maintenance nightmare, the goal of these tests being to mostly replace manual regression testing.  Writing more maintainable tests is a must, but at a higher level I'm not sure that our tests are the right ones.

As an example, given a web application, say there's a form to add an event with start and end dates.  As an end-to-end test, we can validate that you can, in fact, add an event.  But if your start date is after your end date, then you get an error message, and I wouldn't think that how a trivial user input error is handled belongs in a feature file.  On the other hand, there seems to be a pretty strong belief that unit testing the UI isn't worth it; instead, one should do automated integration testing.

So what do I do for this code?

Do I unit test the components related to error messages in general, as well as that this form is going to show them, and skip automating that they actually appear?
Do I do the above and then automate that just one error message somewhere shows as intended, and assume the rest will work?
Do I try to automate every different potential failure case for every form?

This hits the middle ground of integration testing, of which I am leery.  Based on my experience, maintaining a large number of integration tests does not seem worth the value.  On the other hand, there is functionality above the unit level and below the feature level that I would ideally like tested, both in the UI and outside of it.  And I'm concerned about what kind of confidence automated regression can bring if it isn't hitting everything.

I am perfectly willing to write integration tests, but in the context of when to write tests, what tests to write, and how many to write, what is a good approach to addressing this problem?

答:
Do BDD. Write acceptance tests to define the important scenarios of the system. You'll have most of the integration tests that you need, plus valuable documentation and proof that your system does what it's supposed to.

Then add integration tests so that you have good integration coverage. (BobDalgleish's comment is a good way of thinking about integration coverage.) I usually find that missing integration coverage helps me find missing acceptance tests.

Then add unit tests to specify details of behavior and technical correctness. You won't have to unit-test some code at all, because it will already be tested by your acceptance/integration tests. You will think of things to test in other code, and you may even want to re-test paths through that code that are already tested in acceptance/integration tests so that the unit tests make sense without reading the integration tests.


问:
Is there a name for this technique in testing?
When I've written tests for some code and want to make sure that it's actually testing what it's supposed to, I'll mess up or remove the code-under-test, and see if the tests fail. If they don't, I've got a problem.

Is there a name for this technique? It's a real bother having to talk in sentences everytime I want to suggest to someone that they do it.

答:
You're looking for mutation testing.

The idea of mutation testing is to check that the code can be modified to cause the testing to fail, as you have pointed out. An example is as such:

```<code>public double getDiscountedRate(int age, int employmentDurationInMonths) {
    return age < 30 || employmentDurationInMonths < 18 ? 0.2 : 0.05;
}
</code>```

So if we have this test:

```<code>@Test
public void canGetCorrectDiscountedRate() {
    assert getDiscountedRate(29, 24) == 0.2;
}
</code>```

The assertion will be true. If the formula is modified as such:

```<code>public double getDiscountedRate(int age, int employmentDurationInMonths) {
    return age < 30 && employmentDurationInMonths < 18 ? 0.2 : 0.05;
}
</code>```

Then we will expect the assertion to be false now. This helps when there may be a careless error in the method, such as (post-operator modification):

```<code>public double getDiscountedRate(int age, int employmentDurationInMonths) {
    return age < 30 && employmentDurationInMonths < 18 ? 0.2 : 0.2; // where is 0.05?
}
</code>```

In this, the fact that the assertion did not fail for the modified code will let the developer know that it was wrongly returning the same discount rate even when the condition is false.

The Wikipedia article on mutation testing has also helpfully pointed out 'fault injection' as a related article.

Body:
You're looking for mutation testing.

The idea of mutation testing is to check that the code can be modified to cause the testing to fail, as you have pointed out. An example is as such:

public double getDiscountedRate(int age, int employmentDurationInMonths) {
    return age < 30 || employmentDurationInMonths < 18 ? 0.2 : 0.05;
}

So if we have this test:

@Test
public void canGetCorrectDiscountedRate() {
    assert getDiscountedRate(29, 24) == 0.2;
}

The assertion will be true. If the formula is modified as such:

public double getDiscountedRate(int age, int employmentDurationInMonths) {
    return age < 30 && employmentDurationInMonths < 18 ? 0.2 : 0.05;
}

Then we will expect the assertion to be false now. This helps when there may be a careless error in the method, such as (post-operator modification):

public double getDiscountedRate(int age, int employmentDurationInMonths) {
    return age < 30 && employmentDurationInMonths < 18 ? 0.2 : 0.2; // where is 0.05?
}

In this, the fact that the assertion did not fail for the modified code will let the developer know that it was wrongly returning the same discount rate even when the condition is false.

The Wikipedia article on mutation testing has also helpfully pointed out 'fault injection' as a related article.


问:
How to insert/update a large amount of data into mysql using php
I have an excel sheet which has a large amount of data. I am using php to insert the data into mysql server.

I have two problems

1) I have to update a row if the id already exists, else insert the data.

2) BIG PROBLEM : I have more than 40,000 rows and the time out on the sql server which is set by the admin is 60 seconds. When i run the update/insert query it will take more than 60 seconds, and because of this there will be a timeout. So the whole process will fail.

Is there a way I can do this ?

Currently I am checking the student id if it exists, then update otherwise insert. This I feel is taking a lot of time and causing the server to time out.

Also I have this field in the mysql stating the last time the data was updated(last_update). I was thinking of using this date, and if it is past a particular date(ie last time i ran the program) then only those rows should be updated.

Will this help in anyway ?

And what is the query i can run so as to check this date in the mysql database, that if it is past a particular date only those rows need to be updated and not everything else.
(Please help me with an example query for the above!!!!!!!!!!!!!!!!!)

答:
Break the large query into smaller queries and loop through each batch. Try smaller batches will take well under 60 seconds to avoid the risk of a timeout due to server overload, which might push the time over 60 seconds.

Checking the student ID sounds more reliable than using a time comparison. Are you sure you have an index on student ID? And is student ID using the most suitable data format. e.g. Use an integer if possible rather than a string.

Lastly, I don't suppose you can request a longer query duration from the administrator... it would greatly reduce code complexity.


问:
What is the best way to track database changes across a large team
What is the best way to track any change made to the SQL Server database before moving to production in case of a large team ?
We have used excel sheets but quite often things get missed which come out with SQL compare only during moving changes to production?</p>

答:
SQL Server Data Tools provides a Visual Studio project template which allows database development. This way, you can have the source of your database within the same solution that contains the code for your application. You can track all the changes made to the database through source control, given that all changes are made through the project. </p>

<p>It also has a database compare tool, in which you can see the structural differences between the database and what's in your project. The tools also make it easy to deploy the changes made in the source code to the database. </p>

Body:
SQL Server Data Tools provides a Visual Studio project template which allows database development. This way, you can have the source of your database within the same solution that contains the code for your application. You can track all the changes made to the database through source control, given that all changes are made through the project.

It also has a database compare tool, in which you can see the structural differences between the database and what's in your project. The tools also make it easy to deploy the changes made in the source code to the database.