问:
Sprints between Thanksgiving, Christmas and New Years
What do hardened Scrum folks say about planning Sprints around "Major Holidays" lots of stakeholders have a tendency to take multiple days off and the tendency is that we'll miss sprint goals and fixed dates for sprint review/retrospective and planning meetings get all gummed up.  (I try to do planning every other Monday and Review/Retro every other Friday).

We planned a 2 week sprint, but I forgot about Thanksgiving and hunting (which is a pretty major factor in my state) and I don't want to make the same mistake around Christmas and New Years, so I wound up just putting in slack time to fix bugs and stuff.

I figure a 4 week lazy-man's Sprint (eg. Dec 15th 2014 to Jan 12 2015) would be a good way to spend the Holidays, but is this Scrum or is this dumb?

答:
Sprints, indeed, depend on the days off. If you have ten day sprints, it's the same as having two week sprints if your team doesn't work on Saturday and Sunday.

This also means that you have to be very clear with everyone what does the duration of the sprint mean. If you tell that your sprints are ten days long, some people will understand it as two weeks, others—as one week and three days. Having a publicly available formal schedule such as:

Sprint 14: November 18th—December 2nd (10 days)

  Sprint 15: December 2nd—December 18th (11 days; december 4th: attending the conference in NYC)

  ...

may help.

The same goes with vacations, days off and other exceptional events (such as an important power outage in your office). If you know that two of the five members of the team are on vacation for the next three weeks, there are chances you won't perform as fast as usual during the next sprint (if you do, consider firing someone).

I would suggest two options:

Option 1

Keep two weeks sprints even during holidays (unless all of your team members are not working for the entire period of a sprint), but adjust the amount of work which should be done during the sprint.

Consider how many team members are available (some may be on vacation), how critical is their presence, how would their absence impact other people, what would go wrong (for instance, Joel is the only one who knows the password of the server, and he went to Himalayas for two weeks and will not be reachable), etc.

Move the sprint date slightly if major participants cannot attend the meeting. Doing it two days later or earlier wouldn't be too much trouble, but moving it a week towards or backwards would be an issue.

Also note that moving the date of the meeting may have a negative impact on some participants who may consider that the meetings are not that important than they are. You certainly don't want one of the participants to call you later telling that you should move the meeting from today to tomorrow, because he can't attend it today, because he has done another appointment for today.

I would probably find this option more intuitive. Keeping sprints regular ensures better visibility of the project, and keeping sprints short is essential. Unless the communication between the team members is excellent, a four-weeks sprint may have a negative impact.

Moreover, team members may not remember well what they did three weeks ago (especially after holidays). Personally, I can't even remember what I did yesterday; I can take notes, but if I know that the meeting will be only in four weeks, I will be inclined much more to skip notes as well.

Option 2

Make the next sprint much longer than usual (such as four weeks vs. the usual two weeks).

This approach is better in a case where you're sure that the progress will be too small otherwise. Having nothing to say during the sprint review and the retrospective may have two negative effects:

The team members themselves may have an impression that they "did nothing" during two weeks. In that case, they may be less motivated for the next sprint.

If the customer or your boss attends the meeting and has an impression that the team wasn't working too much, this could result in even worse consequences.


问:
How to track temporal changes in a database?
Imagine a software for theater owners. You can accept reservations for the different cinema halls. Each hall has a different number of seats.

Say the owner wants to know how many people visited the cinema on each day in the past years. Easy, just query the Reservations table and group by date.

What if we want to know the utilized capacity - how much % of seats are sold? Easy, just join the reservations with the Cinema_Halls table, and divide the number of reservations by the number of available seats.

However, on August 1st, the owner decides to add more seats to one of the cinema halls, and updates the database accordingly. But now, all the utilization percentages before August 1st are invalid, as we do not have access to the historical number of seats.

There are three solutions that come to my mind:

Add a new table, which tracks number of seats over time. Tuple: (HallID, numberOfSeats, validFrom, validUntil)

Don't modify the cinema_hall record, but add a new one with a different number of seats, and mark the old one as invalid.

Use special temporal database features of your DBMS

(1) seems to be cumbersome. If you really want the capability to get all historical data, you would need a separate table for every single value that could change.

(2) is not how the user would want to work, and could introduce side effects.

(3) might not be supported by your database system.

What would be a good solution to solve this?

答:
You don't strictly want to know the total number of seats, but the total number of seats available to be sold. For example, some seats may be in existence physically but unsellable for a given event. I'd be inclined to think about an "available seat" as a tuple of (hallId, seatId, eventId) - which you can pair up with a Reservation when it arrives. Given that, you can then sum up over a set of events, a date range (joining to Events), have variable pricing, multiple screenings per day, etc.

If you don't want to track individual seats, then just store (hallId, eventId, seatsAvailable, seatsSold) or (hallId, date, seatsAvailable, seatsSold) for each event or day. There will potentially be some redundancy in the data compared to (1) but it will make queries a lot cleaner than handling date ranges.

ContentLicense: CC BY-SA 3.0


答:
Door number (2) is attractive if you can do it. The problem with many applications tracking long-lived facilities (theater halls and other building components, aircraft, cargo vessels, ...) is that they assume those assets are invariant. They are not. As relatively inflexible and expensive capital assets, they are not changed very often--but they definitely do change over their entire life cycles, which span years to decades. Seats are added or removed, rooms are subdivided or combined or radically reassigned, and so on.

If you have a Cinema_Halls table that can record identity information (e.g. name of the room, its location in the building), lifecycle information (e.g. start and stop timestamp, or in databases like PostgreSQL that have slightly better temporal handling, an interval defining the service lifetime), their capacity and/or other interesting parameters (e.g. total number of seats, number of handicapped seats, usable area in square feet, maximum occupancy as decreed by the Fire Marshal, ...), then your database accurately records the parameters for the hall as a function of time. It exposed a little more complexity/variability in your data model, but in ways that reflect reality; doing utilization and other joins against that facility table will be straightforward.

However, you may not be able to make such a significant schema change. In which case you must put the data externally. Option (1) is such an approach--in effect, a facilities description table that assumes "Hall 1" is itself invariant, but that some of its operational parameters vary over time. There are pros to this approach. Your other tables, for example, will simply reference hallID = 1 always, and not need to have items 1, 4, 17, 19, and 31 all be different instantiations of the logical "Hall 1" at different points in time. But the queries when you do want hall capacity information will be a little more complex. And if Hall 1 is at some point separated into Hall 1A and Hall 1B, the "halls are invariant" assumption breaks anyway.

If you cannot make Option (1) work as a separate table, alternatives are to encode the lifecycle information somewhere--e.g. stored procedures, or into static data embedded within your analytics functions/methods/objects. That's an ugly, bifurcated, and somewhat fragile approach--but there are many cases where that kind of duct tape and baling wire solution the best you can do, given other practical / organizational constraints. Despite the genuine downsides of the implementation, on the plus side, the code asking for the required values (e.g. "number of seats in hall x at time t") can often do so cleanly (because the number_of_seats function/method/procedure hides how the value is computed).

Your final suggestion, choice (3), is admirable but unworkable, if only because workaday databases provide such weak support to represent and compute temporal relationships, properties, and realities. PostgreSQL has a pretty decent interval data type. It's rich, precise, and works only in PostgreSQL. If you're using PostgreSQL, have at--but it's non-portable. And an interval type, while a start, is hardly an entire "temporal reasoning" capability. With other databases, you're even worse off. Oracle has two interval types, un-unified, of varying precision. Other databases like DB2 and MySQL support some interval-like computations in their SQL operators and functions for date/time objects, but have no first-class interval types.

So, in order of solution richness and elegance: options 2, 1, 3.

Title: How to track temporal changes in a database?

Body:
Imagine a software for theater owners. You can accept reservations for the different cinema halls. Each hall has a different number of seats.

Say the owner wants to know how many people visited the cinema on each day in the past years. Easy, just query the Reservations table and group by date.

What if we want to know the utilized capacity - how much % of seats are sold? Easy, just join the reservations with the Cinema_Halls table, and divide the number of reservations by the number of available seats.

However, on August 1st, the owner decides to add more seats to one of the cinema halls, and updates the database accordingly. But now, all the utilization percentages before August 1st are invalid, as we do not have access to the historical number of seats.

There are three solutions that come to my mind:

Add a new table, which tracks number of seats over time. Tuple: (HallID, numberOfSeats, validFrom, validUntil)

Don't modify the cinema_hall record, but add a new one with a different number of seats, and mark the old one as invalid.

Use special temporal database features of your DBMS

(1) seems to be cumbersome. If you really want the capability to get all historical data, you would need a separate table for every single value that could change.

(2) is not how the user would want to work, and could introduce side effects.

(3) might not be supported by your database system.

What would be a good solution to solve this?


问:
Advice needed on rethrowing an exception
Consider the following c# code:

```<code>public class ExceptionManager
{
    public static void TreatException(Exception ex)
    {
        if (ShowAndContinue(ex))
            // display a user-friendly message on what happened and let the app run.
        else
            throw ex;
    }

    // (more code)
}
</code>```

(Please note that the above is over-simplified so that the focus is on my actual concern)

IMHO I think the way the exception is thrown is wrong because stacktrace information is lost. The preferred way (again, IMHO) to write the throw line would be this:

```<code>throw new UntreatableErrorException("Manager could not treat the exception.", ex);
</code>```

This way the original exception's stacktrace is preserved.

However, a colleague of mine is arguing that doing so would mean losing the ability to catch the original exception lower in the call stack, because catch works with exception type and hence an exception trap might be set to catch the original exception but not the UntreatableErrorException. Therefore it's better to throw back the original exception instance, even if it means losing the stacktrace.

Which one of us is right here on what should be the best practice?

答:
You are both right.

You don't want to lose the stack trace, but you may want to catch the lower level exception.

Don't wrap the exception if it isn't adding information.

I would call your ExceptionManager and TreatException a bit of a code smell - they are trying too hard to centralize exception handling.

To re throw without losing the stack trace:

```<code>public static bool ContinueAfterException(Exception ex)
{
    if (ShowAndContinue(ex))
    {
      // display a user-friendly message on what happened and let the app run.
      return true;
    }

    return false;
}
</code>```

Elsewhere:

```<code>try
{
  // some exception throwing code
}
catch(Exception ex)
{
    if(!ContinueAfterException(ex))
        throw; // no ex
}
</code>```

Body:
You are both right.

You don't want to lose the stack trace, but you may want to catch the lower level exception.

Don't wrap the exception if it isn't adding information.

I would call your ExceptionManager and TreatException a bit of a code smell - they are trying too hard to centralize exception handling.

To re throw without losing the stack trace:

public static bool ContinueAfterException(Exception ex)
{
    if (ShowAndContinue(ex))
    {
      // display a user-friendly message on what happened and let the app run.
      return true;
    }

    return false;
}

Elsewhere:

try
{
  // some exception throwing code
}
catch(Exception ex)
{
    if(!ContinueAfterException(ex))
        throw; // no ex
}


问:
Should I accept empty collections in my methods that iterate over them?
I have a method where all logic is performed inside a foreach loop that iterates over the method's parameter:

```<code>public IEnumerable<TransformedNode> TransformNodes(IEnumerable<Node> nodes)
{
    foreach(var node in nodes)
    {
        // yadda yadda yadda
        yield return transformedNode;
    }
}
</code>```

In this case, sending in an empty collection results in an empty collection, but I'm wondering if that's unwise.

My logic here is that if somebody is calling this method, then they intend to pass data in, and would only pass an empty collection to my method in erroneous circumstances.

Should I catch this behaviour and throw an exception for it, or is it best practice to return the empty collection?

答:
The right solution is much harder to see when you are just looking at your function in isolation.  Consider your function as one part of a larger problem.  One possible solution to that example looks like this (in Scala):

input.split("\\D")
.filterNot (_.isEmpty)
.map (_.toInt)
.filter (x => x >= 1000 && x <= 9999)
```

First, you split the string up by non-digits, filter out the empty strings, convert the strings to integers, then filter to keep only the four-digit numbers.  Your function might be the map (_.toInt) in the pipeline.

This code is fairly straightforward because each stage in the pipeline just handles an empty string or an empty collection.  If you put an empty string in at the start, you get an empty list out at the end.  You don't have to stop and check for null or an exception after every call.

Of course, that's presuming an empty output list doesn't have more than one meaning.  If you need to differentiate between an empty output caused by empty input and one caused by the transform itself, that completely changes things.

Body:
The right solution is much harder to see when you are just looking at your function in isolation.  Consider your function as one part of a larger problem.  One possible solution to that example looks like this (in Scala):

input.split("\\D")
.filterNot (_.isEmpty)
.map (_.toInt)
.filter (x => x >= 1000 && x <= 9999)

First, you split the string up by non-digits, filter out the empty strings, convert the strings to integers, then filter to keep only the four-digit numbers.  Your function might be the map (_.toInt) in the pipeline.

This code is fairly straightforward because each stage in the pipeline just handles an empty string or an empty collection.  If you put an empty string in at the start, you get an empty list out at the end.  You don't have to stop and check for null or an exception after every call.

Of course, that's presuming an empty output list doesn't have more than one meaning.  If you need to differentiate between an empty output caused by empty input and one caused by the transform itself, that completely changes things.


问:
How to communicate software design efficiently between developers?
Recently I've come to understand that a serious problem at my workplace is the lack of communication between developers. It's odd, because we're a totally open sort of organization. Everyone can go to everyone and ask whatever they need and communication is hardly regulated at all. And yet it doesn't happen by itself...

The kind of lack that I feel most keenly myself is between me (the architect of the system, more or less) and the rest of the developers (which usually work on a piece of required functionality, not the framework). Whenever I create some component or a naming convention or whatever... there's no way I can make it known to all the people who might need to know this. At most I tell it in person to the fellow who asked me for it, but that's about it.

As a result, wheels get reinvented, there are hardly any conventions in the code (mostly evolved from copy-pasting), occasional cargo-cult coding, etc. I try to clean it up whenever I get the opportunity, but with workload being as large as it is, there are rarely such chances. :(

I'm not really sure how to solve this. I could try and document all the stuff that has been created (probably would take at least a week - difficult to budget that much time) in our internal wiki, but who ever reads such places regularly for news? And how would you find if something that you need has already been implemented somewhere?

What do other people do to avoid this pitfall? What methods have shown themselves as efficient?

答:
For teams doing OO design and implementation, part of the communication should be a shared understanding of the problem space, and typical tools used to solve those problems.

The notion of design patterns was created very specifically to create a shared vocabulary that can be used as a short-hand when talking about the problem spaces.

I don't mean using design patterns as a way to extend meeting times with tiresome "so and so isn't the xyzzy pattern!" arguments. Rather, instead of having to discuss at length some specific implementation, design patterns allow us to discuss the bigger picture and how the pieces fit together.


问:
Under which circumstances does it make sense to lose track of where an exception was thrown from?
Is there any valid reason why a catch block on a lower layer would throw back an exception caused by a higher, unknown layer using the following syntax:

```<code>throw ex;
</code>```

... rather than:

```<code>throw;
</code>```

... ?

In the first case, not only the catch block doesn't deal with the exception, but it also reset its StackTrace property, making it more difficult to understand what caused it.

Why would anyone want a catch block in a lower layer to behave like this?

答: First off, having a catch block which only rethrows the exception is usually useless. But, the only real world scenario i can think of which makes sense to use throw ex instead of throw is if you're developing some sort of third party library which you by all means dont want anyone in the outter scope who's using your code to see the full stacktrace. Im not saying this is a good thing, but it might happen.


问:
Can a Java interface declaration enforce parameter properties?
As far as I know, declaring an interface is like so:

```<code>public interface Roots_Squares {
    public double square_root( double value );
}
</code>```

Now... how do you enforce value to have non-negative values?  Such a function should avoid negative values right?  If someone creates a class that implements this, and that implementation does not handle negative values, and then I use their class with a negative value... well, things break.

It then becomes my responsibility to check for negatives when I'm pretty sure the implementor should do the checking.

答: The comments on Doval's answer are right: create and use a PositiveDouble. Also, consider using a design by contract tool. A design by contract tool like cofoja might solve your problem. I have not used 1 but I know that there are several design by contract tools in Java.</p>


问:
How to choose between different ways to write some code?
I would like to validate point in a two-dimensional rectangular Cartesian coordinate. I found following regular expression solution on stackoverflow ^(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)$
 . Another solution is using little PHP controls:

```<code>    $xy = explode(",", "-3,3");
    $return = array(0,0);

    if(is_array($xy) && count($xy) == 2) {
        $return = $xy;
        foreach($xy as $digit) {
            if(!is_numeric($digit)) {
                $return = array(0,0);
                break;
            }
        }
    }
</code>```

Although, seconds solution is "larger", I prefer this for readability. What elements should I use to make the right choice between those two solutions?

答:
Here are some points you should take in consideration:

Readability: long regular expressions are difficult to understand. Use comments (and eventually break one long expression into several small ones, if possible) to make it easier to read. At the same time, the piece of PHP code in your question can (and should) be refactored to make it more readable.

Readability by beginner programmers: if your team has beginner programmers, they may be completely lost and horrified when facing a long regular expression. In the same way, beginners may prefer imperative style over functional one.

In a case of doubt, talk with your team. Ask if everyone is fine using regular expressions. Show this one (with comments) and ask if they understand it. If you work with experienced developers, you may also add comments, then introduce a error into the expression itself, and ask them if they notice anything wrong.

Performance: benchmark extensively both solutions. It might be that the one is terribly slow compared to another one. Don't guess—measure.

Note that if both conform to your expectations, you shouldn't take the performance element into consideration. For example, if you expect the code to run in 5 ms., and one piece of code takes 14 µs, while the second one takes 960 µs, don't take the first one just because it is faster.

Maintenance: if you expect the code to be modified, think twice. Would it be easy to modify the regular expression (once it is properly commented)? Is it safe to modify the piece of code without breaking anything?

Having regression testing ensures you can modify code without breaking it, but that's not the point. If the code is difficult to modify, nobody will dare touching it, even with regression tests.

Finally, you must obviously understand both to pick the right one for you/your project/your team. This means that:

You should be able to add relevant comments to the regular expression,

You should be able to see something wrong in the pice of PHP code you copy-pasted and be able to refactor this.


答:
I could try and document all the stuff that has been created…

Gotta start somewhere.

…who ever reads such places regularly for news?

Then use email to notify of changes. Do keep the SNR low.

You'll need to get people behind changes (including management), then make them aware of the changes as they are adopted. You may want their input on some changes. Otherwise, just float them by in an email/update. For more complex topics, take a few minutes to explain and Q+A not long after it's been floated.

And how would you find if something that you need has already been implemented somewhere?

Code reviews would be a good start. If people are still not reusing code, you should get in at earlier stages (i.e. before code is written).

As a result, wheels get reinvented, there are hardly any conventions in the code…

That's the hard part. Nobody wants to take the initiative. My typical approach is to perform the change myself, float, discuss if needed, push, then enforce (tool-permitting).

So if it is coding conventions:

do a dry run of the next important change on your todo list

if that succeeds, float the change to the engineers

if there are questions/concerns, detail the case for the change in email or meeting

push

enforce (tool-permitting)

That's how I usually do it, anyway. Sometimes larger tasks are divided.

Title: How to communicate software design efficiently between developers?

Body:
Recently I've come to understand that a serious problem at my workplace is the lack of communication between developers. It's odd, because we're a totally open sort of organization. Everyone can go to everyone and ask whatever they need and communication is hardly regulated at all. And yet it doesn't happen by itself...

The kind of lack that I feel most keenly myself is between me (the architect of the system, more or less) and the rest of the developers (which usually work on a piece of required functionality, not the framework). Whenever I create some component or a naming convention or whatever... there's no way I can make it known to all the people who might need to know this. At most I tell it in person to the fellow who asked me for it, but that's about it.

As a result, wheels get reinvented, there are hardly any conventions in the code (mostly evolved from copy-pasting), occasional cargo-cult coding, etc. I try to clean it up whenever I get the opportunity, but with workload being as large as it is, there are rarely such chances. :(

I'm not really sure how to solve this. I could try and document all the stuff that has been created (probably would take at least a week - difficult to budget that much time) in our internal wiki, but who ever reads such places regularly for news? And how would you find if something that you need has already been implemented somewhere?

What do other people do to avoid this pitfall? What methods have shown themselves as efficient?


问:
Why shouldn't a method throw multiple types of checked exceptions?
We use SonarQube to analyse our Java code and it has this rule (set to critical):

Public methods should throw at most one checked exception

Using checked exceptions forces method callers to deal with errors, either by propagating them or by handling them. This makes those exceptions fully part of the API of the method.

To keep the complexity for callers reasonable, methods should not throw more than one kind of checked exception."

Another bit in Sonar has this:

Public methods should throw at most one checked exception

Using checked exceptions forces method callers to deal with errors, either by propagating them or by handling them. This makes those exceptions fully part of the API of the method.

To keep the complexity for callers reasonable, methods should not throw more than one kind of checked exception.

The following code:

```<code>public void delete() throws IOException, SQLException {      // Non-Compliant
  /* ... */
}
</code>```

should be refactored into:

```<code>public void delete() throws SomeApplicationLevelException {  // Compliant
    /* ... */
}
</code>```

Overriding methods are not checked by this rule and are allowed to throw several checked exceptions.

I've never come across this rule/recommendation in my readings on exception handling and have tried to find some standards, discussions etc. on the topic.  The only thing I've found is this from CodeRach: How many exceptions should a method throw at most?

Is this a well accepted standard?

答:
I remember fiddling around with this a little bit when playing with Java a while back, but I wasn't real conscious of the distinction between checked and unchecked until I read your question.  I found this article on Google pretty quickly, and it goes into some of the apparent controversy:

http://tutorials.jenkov.com/java-exception-handling/checked-or-unchecked-exceptions.html

That being said, one of the issues this guy was mentioning with checked exceptions is that (and I've personally run into this from the beginning with Java) if you keep adding a bunch of checked exceptions to throws clauses in your method declarations, not only do you have to put in a lot more boilerplate code to support it as you move to higher-level methods, but it also just makes a bigger mess and breaks compatibility when you try to introduce more exception types to lower-level methods.  If you add a checked exception type to a lower-level method, then you have to run back through your code and adjust several other method declarations as well.

One point of mitigation mentioned in the article - and the author did not like this personally - was to create a base class exception, limit your throws clauses to only use it, and then just raise subclasses of it internally.  That way you can create new checked exception types without having to run back through all your code.

The author of this article may not have liked this much, but it makes perfect sense in my personal experience (especially if you can look up what all the subclasses are anyway), and I bet that's why the advice you're being given is to cap everything to one checked exception type each.  What's more is that the advice you mentioned actually allows for multiple checked exception types in non-public methods, which makes perfect sense if this is their motive (or even otherwise).  If it's just a private method or something similar anyway, you're not going to have run through half your codebase when you change one little thing.

You did largely ask if this is an accepted standard, but between your research you mentioned, this reasonably thought-out article, and just speaking from personal programming experience, it certainly doesn't seem to stand out in any way.


问:
Why do people disable JavaScript?
I asked a question yesterday Should I Bother to Develop For JavaScript Disabled?. I think the consencus is: Yes, I should develop for JavaScript Disabled. Now I just want to understand why users disable JS. It seems many developers (I guess people who answered the questions are developers) disable JS. Why is that. Why do users disable JS? For security? Speed? or what?</p>

答: With Javascript activated any website may execute code on my Computer. I don't even know, if the particular website executes code and what it does. Even more worse, someone else may insert code without my knowledge into a normally harmless website (XSS). Recently a the well-known german computer-magazin c't made an article, taht an 16-year-old tried the online-banking-sites of the most common banks in germany. Many of them - including the biggest - were vulnerable for XSS. And you don't even notice, that your online-banking-site executes some Javascript that changes for example the target and the amount for a transaction. With disabled Javascript the XSS-attack in the context of a trusted site is useless, I don't execute the malicious code.</p>

ContentLicense: CC BY-SA 2.5

Title: Why do people disable JavaScript?


问:
Are there any widely accepted sets of standards/practices for secure coding?
The title should be fairly self-explanatory.

We need to update our coding standards, and as part of this process we've been asked to try and follow an industry standard from a recognised/knowledgeable body rather than just rolling our own. It allows us to demonstrate that we're using widely recognised "best practice" and avoid the accusation that what we've adopted it a pointless waste of time.

I found a few examples, but they mostly seem to be quite loose and generic.

https://security.berkeley.edu/content/application-software-security-guidelines

https://www.securecoding.cert.org/confluence/display/seccode/Top+10+Secure+Coding+Practices

We do both web and desktop development, using the Microsoft stack. So something widely applicable across environments but targeted at MS languages would be especially helpful.

答:
Check out the Owasp secure coding guidelines.

and then check out the PCI-DSS standard. While PCI are guidelines for credit card processing, they can be used as a guide for having secure processes and code.

ContentLicense: CC BY-SA 4.0


问:
Determining a class structure
I'm currently in the early stages of designing an e-commerce application.  I'm working out some designs for my classes which have so far been fairly straightforward, but I've run into something of a problem which I suspect is related to the Circle/Square problem.  The following (simplified) class diagram outlines what I've designed so far

There are two classes of sellable products in the system

Physical products representing an object that exists through the real world (Bikes, Lego, CDs, etc)

Downloadable products representing something you can purchase over the web (MP3s, eBooks, etc)

A physical product has attributes such as shipping weight

A downloadable product has attributes such as file type and size

Products can themselves be made up of products (components).  An album is composed of tracks, a bike is composed of frame, wheels, handlebars, gears, etc, each of which is a product in its own right

A third type of product, a product bundle, is for grouping otherwise unrelated products together for selling as a single unit (A bike could be bundled with a pump, helmet, etc, a collection of eBooks could be bundled together, and so on).

The Product Bundle is where the difficulties are springing up.  A bundle of physical products would have things such as the shipping weight being the total shipping weights of all the products that make it up, a stock level equal to the level of the composing product with the least stock, etc.  A bundle of downloadable products would have a total file size of all the files that make up the bundle, a file name list composed of all the files in the bundle and so on.

But what about a bundle that comprises both physical and digital products?  Suppose for example you want to provide a digital download of a movie when someone buys the same movie on DVD, or you want to give an eBook about the Tour De France away with a bicycle, now there's a mixture of properties that put the bundle in neither the physical or digital product grouping.

I've thought of the following solutions but none seem ideal:

Put all the properties applicable to both in the superclass

The Bundle class can easily override methods defined on the superclass to be able to compute the composite values (sum all product weights together, etc)

This seems like a really poor encapsulation

You'll have methods on physical products that are only really applicable to digital ones and vice versa

The superclass starts to become a "god object"

The storage requirements for objects mean that you always need to store attributes that don't apply to the actual type of object (you're always storing a shipping weight of 0 for downloads, a filesize of 0 for physical products, etc)

Implement abstract methods in the Product class, override them in the subclasses to do something where appropriate, throw an exception where not

Doesn't really solve the encapsulation problem

Code that deals with products now has to be prepared to determine actual class of object being processed, deal with exceptions, etc

Possible violation of the liskov substitution principle?

As above but return default values where the method is not appropriate (0 for weight on a digital product, 0 for filesize on physical products, etc)

Code no longer has to deal with exceptions or class

Could lead to unforeseen logical errors when trying to process products in inappropriate ways

Implement physical properties/methods in physical product class, implement file properties/methods in digital product class, both in bundle class with interfaces to tell them all apart (physical implements one, digital implements another, bundle implements both)

Better encapsulation

Adds a fair chunk of boilerplate code (interfaces to be implemented, etc)

The Bundle class will still need to be aware of what type its component classes are

The problem of what the Bundle class should do when methods that aren't appropriate for a given circumstance remains.  Should getShippingWeight return 0 or throw an exception if the bundle's products are all digital?

Some other solution that hasn't occurred to me yet

????

Most of the above approaches would still require the Bundle class to do additional work to determine the types of its constituent parts.

Basically, is there an approach of the ones highlighted above that would be preferable to address these issues, or is there some other approach from these that could be better applied to get a good design that doesn't overload a base class with too much functionality and doesn't leave considerable special cases that need to be dealt with elsewhere?  Any input is appreciated.

答:
What's your use-case?

Domain-Driven Design is (partly) about implementing specific models rather than general ones: a model which solves your particular business problem really well is much more valuable than a model which sort-of-solves lots of problems.

To me it looks like the most general part of your current design (by which I mean the part which is trying to be the most things at once) is the ProductBundle. So let's try to cut its responsibilities down by examining use cases.

If, for example, you're designing a shopping cart system, then you may be better served by a model which accumulates a flat list of items in the cart, and then performs all the calculations (bundles, discounts, and so on) at the checkout, perhaps using some sort of rules engine. ProductBundle may still appear in this design, but only as an implementation detail of the discount engine.

On the other hand, if you are implementing an inventory/warehouse control system which tells you when to order more items, then you might model products as individual SKUs with, say, shipping times, quantities, and so on. ProductBundle may still appear in this design, but in a purely advisory role ("X is in a bundle with Y; you should order them together").

If your system has to fill both use-cases then you need to evaluate the likelihood of friction as the application evolves. (It sounds like you're already experiencing such friction.) You can alleviate this pain by splitting the application up into bounded contexts.

Title: Determining a class structure


问:
Are there other ways to limit recursion depth for a function?
I am trying to prevent a function/method (in Java) from performing recursion more than a depth of 3 self calls. I've learnt about the accumulator trick from odersky's scala coursera course.

```<code>public void myMethod(File arg, int accumulator) {
    //...snipped...
    File newArg= ...;
    if (accumulator + 1 > 3)
        throw new IllegalStateException("exceeeding depth 3");
    myMethod(newArg, accumulator+1);
}
</code>```

Any other ideas ? Perhaps with a ThreadLocal ?

答:
Yes, there is another way of limiting recursion depth, but I would not encourage it.

In general, we can say that you are currently using a data-driven approach.

```<code>public void myMethod(File arg, int accumulator) {
</code>```

where the accumulator counts the recursion call depth.

The other way is to enumerate the calls. Said another way, hard-code the calls:

```<code>private void myMethodSnippedCode(/*args*/) {
    //...snipped...
}

public void myMethod(File arg) {
    myMethodSnippedCode(/*whatever*/);
    // File newArg= ...; // ... code is moved to the myMethod1 call below
    // Exception removed. Why would you throw an exception?
    myMethod1(...); // the ... is where your new File is created
}

private void myMethod1(File arg) {
    myMethodSnippedCode(/*whatever*/);
    myMethod2(...);
}

private void myMethod2(File arg) {
    myMethodSnippedCode(/*whatever*/);
    myMethod3(...);
}

private void myMethod3(File arg) {
    myMethodSnippedCode(/*whatever*/);
    // don't make any more calls
}
</code>```

What a code comprehension and maintenance nightmare. If we have to change the number of levels required, or introduce other changes, someone will inevitably get it wrong.

Stick with nice clean recursion that everyone will understand:

```<code>public void myMethod(File arg, int depth) {
    // [snipped code body]
    if (depth< 3)
        myMethod(..., ++depth); // the ... is where your new File is created
}
</code>```

BTW, the initial call to myMethod requires the caller to pass zero. What will happen if they pass  6? Or -21? The solution to this is to wrap the first call

```<code>public void myMethod(File arg) {
        myMethodWorker(arg, 0);
}

private void myMethodWorker(File arg, int depth) {
    // [snipped code body]
    if (depth < 3)
        myMethodWorker(..., ++depth); // the ... is where your new File is created
}
</code>```

Body:
Yes, there is another way of limiting recursion depth, but I would not encourage it.

In general, we can say that you are currently using a data-driven approach.

public void myMethod(File arg, int accumulator) {

where the accumulator counts the recursion call depth.

The other way is to enumerate the calls. Said another way, hard-code the calls:

private void myMethodSnippedCode(/*args*/) {
    //...snipped...
}

public void myMethod(File arg) {
    myMethodSnippedCode(/*whatever*/);
    // File newArg= ...; // ... code is moved to the myMethod1 call below
    // Exception removed. Why would you throw an exception?
    myMethod1(...); // the ... is where your new File is created
}

private void myMethod1(File arg) {
    myMethodSnippedCode(/*whatever*/);
    myMethod2(...);
}

private void myMethod2(File arg) {
    myMethodSnippedCode(/*whatever*/);
    myMethod3(...);
}

private void myMethod3(File arg) {
    myMethodSnippedCode(/*whatever*/);
    // don't make any more calls
}

What a code comprehension and maintenance nightmare. If we have to change the number of levels required, or introduce other changes, someone will inevitably get it wrong.

Stick with nice clean recursion that everyone will understand:

public void myMethod(File arg, int depth) {
    // [snipped code body]
    if (depth< 3)
        myMethod(..., ++depth); // the ... is where your new File is created
}

BTW, the initial call to myMethod requires the caller to pass zero. What will happen if they pass  6? Or -21? The solution to this is to wrap the first call

public void myMethod(File arg) {
        myMethodWorker(arg, 0);
}

private void myMethodWorker(File arg, int depth) {
    // [snipped code body]
    if (depth < 3)
        myMethodWorker(..., ++depth); // the ... is where your new File is created
}


答:
there are various ways:

rewrite the recursion into an iterative version and you don't have to worry about recursion depth only the stack depth if the iterative version requires one.

Use an outside variable of some kind (static variable, field member,...) to track the recursion depth. This has the downside that it takes up some bytes just for this method and may not be thread-safe/reentrant depending on what type you choose.

However the accumulator method is usually preferable when the iterative version would end up unreadable.

Title: Are there other ways to limit recursion depth for a function?

Body:
I am trying to prevent a function/method (in Java) from performing recursion more than a depth of 3 self calls. I've learnt about the accumulator trick from odersky's scala coursera course.

```<code>public void myMethod(File arg, int accumulator) {
    //...snipped...
    File newArg= ...;
    if (accumulator + 1 > 3)
        throw new IllegalStateException("exceeeding depth 3");
    myMethod(newArg, accumulator+1);
}
</code>```

Any other ideas ? Perhaps with a ThreadLocal ?


问:
How to prevent race conditions in a web application?
Consider an e-commerce site, where Alice and Bob are both editing the product listings. Alice is improving descriptions, while Bob is updating prices. They start editing the Acme Wonder Widget at the same time. Bob finishes first and saves the product with the new price. Alice takes a bit longer to update the description, and when she finishes, she saves the product with her new description. Unfortunately, she also overwrites the price with the old price, which was not intended.

In my experience, these issues are extremely common in web apps. Some software (e.g. wiki software) does have protection against this - usually the second save fails with "the page was updated while you were editing". But most web sites do not have this protection.

It's worth noting that the controller methods are thread-safe in themselves. Usually they use database transactions, which make them safe in the sense that if Alice and Bob try to save at the precise same moment, it won't cause corruption. The race condition arises from Alice or Bob having stale data in their browser.

How can we prevent such race conditions? In particular, I'd like to know:

What techniques can be used? e.g. tracking the time of last change. What are the pros and cons of each.

What is a helpful user experience?

What frameworks have this protection built in?

答:
Use Optimistic Concurrency Control.

Add a versionNumber or versionTimestamp column to the table in question (integer is safest).

User 1 reads record:

```<code>{id:1, status:unimportant, version:5}
</code>```

User 2 reads record:

```<code>{id:1, status:unimportant, version:5}
</code>```

User 1 saves record, this increments the version:

```<code>save {id:1, status:important, version:5}
new value {id:1, status:important, version:6}
</code>```

User 2 tries to save the record they read:

```<code>save {id:1, status:unimportant, version:5}
ERROR
</code>```

Hibernate/JPA can do this automatically with the @Version annotation. If you use Spring Data Rest, it will automatically set the HTTP ETag with this version number

You need to maintain the state of the read record somewhere, generally in session (this is safer than in a hidden form variable).

Body:
Use Optimistic Concurrency Control.

Add a versionNumber or versionTimestamp column to the table in question (integer is safest).

User 1 reads record:

{id:1, status:unimportant, version:5}

User 2 reads record:

{id:1, status:unimportant, version:5}

User 1 saves record, this increments the version:

save {id:1, status:important, version:5}
new value {id:1, status:important, version:6}

User 2 tries to save the record they read:

save {id:1, status:unimportant, version:5}
ERROR

Hibernate/JPA can do this automatically with the @Version annotation. If you use Spring Data Rest, it will automatically set the HTTP ETag with this version number

You need to maintain the state of the read record somewhere, generally in session (this is safer than in a hidden form variable).


答:
Software or system security hugely depends on the type of system being designed, the data it stores and the regulatory/contractual environment it is used in. Most organizations often cannot articulate the level of security required in the systems they produce, either.

Personally, I think about security on three levels. First is the highest level: the business level where management decides the risks to the business, usually referred to as Enterprise Risk Management (ERM) using frameworks like COSO, or IT governance, using frameworks like CoBIT or TOGAF. Organizations do not have to use a recognized framework but it can help ensure issues are not forgotten and help prioritize otherwise easy to dismiss non-functional requirements like security.

This also includes compliance, such as industry-specific law like HIPAA's Security Rule for health information, contractual obligations like PCI-DSS or buyer specifications like FIPS 140-2 or Common Criteria). Each is verified in different ways.

Second is the development organization level: what practices the organization should undertake when developing a system. Several standards or frameworks exist, such as:

The Building Security In Model (BSIMM)

Safecode

Microsoft's Security Development Lifecycle

These recommend different practices to use at different stages of software development. For example, many frameworks recommend threat modelling to detect design flaws early (where they are cheapest to fix), adhering to secure coding guidelines and using static analysis tools to find flaws as code as written then penetration testing afterwards, using tools that emulate common attack methods.

The third is guidance for each of the specific practices. Focusing on Microsoft coding practices, as mentioned by the OP, the challenge with the Microsoft online documentation is, while there is a lot of it, much of it is out of date. Instead, focus on OWASP for the web side. OWASP approaches each vulnerability from a vendor neutral perspective then links to vendor-specific mitigations.

While it focuses heavily on C++, consider Secure Coding (link is to the Amazon page) if for the desktop side and the follow up book on secure coding for Vista. Microsoft's MSDN Security Center collates information on Microsoft tools and libraries.

If you want vendor-neutral training or certification on secure coding, consider the SANS courses or (ISC)2 CSSLP. Remember, security is not just about the code - ensure your operations and IT staff have also considered security in their infrastructure design, your QA know how to test security features and your architects consider security (indeed, IASA considers security as one of the four main groupings of quality attributes).

Title: Are there any widely accepted sets of standards/practices for secure coding?

Body:
The title should be fairly self-explanatory.

We need to update our coding standards, and as part of this process we've been asked to try and follow an industry standard from a recognised/knowledgeable body rather than just rolling our own. It allows us to demonstrate that we're using widely recognised "best practice" and avoid the accusation that what we've adopted it a pointless waste of time.

I found a few examples, but they mostly seem to be quite loose and generic.

https://security.berkeley.edu/content/application-software-security-guidelines

https://www.securecoding.cert.org/confluence/display/seccode/Top+10+Secure+Coding+Practices

We do both web and desktop development, using the Microsoft stack. So something widely applicable across environments but targeted at MS languages would be especially helpful.


问:
Is this still a Greedy Algorithm
As a preface I will state this is for a homework assignment.  I have already discussed this with the professor and will not be using this design.  This purpose of this question is whether or not the defined algorithm is greedy.  Also if this is in the wrong section I apologize and please let me know where it should be asked.

I would like to know if the following algorithm would be considered as a greedy algorithm.  There are two stages for the algorithm but I am interested in the algorithm as a whole.

First stage:  Run a series of pre-defined greedy algorithms.  Each algorithm would come up with a solution for the overall problem.  For example, given the scheduling problem, if I had the following alogorithms:

Pick the longest request of all choices.

Pick the shortest request of all choices.

Pick the latest ending request of all choices.

Second stage: I would now have three "solutions" to choose from.  I now pick the "best" solution from some criteria, say maximum number of requests scheduled.

Is this two stage algorithm considered to be a greedy algorithm since all of the parts themselves are greedy?

答:
Let's first define a greedy algorithm - I'll take it from Wikipedia because it is a reasonable one.

A greedy algorithm is an algorithm that follows the problem
  solving heuristic of making the locally optimal choice at each stage
  with the hope of finding a global optimum.

For your considered solution, it isn't a greedy algorithm because there really isn't a question of multiple stages and making choices in the hopes of finding a global optimum at all. I'd be more likely to call it an amalgamated method or, more idiomatically, a Goldilocks method - try all the options and choose the one you like the most. This more closely resembles a brute-force method, or a best-of-three method (such as with some optimizations of quicksort in the problem of picking a good median), than it resembles a traditional greedy algorithm.

The main problem, beyond the technical definitions, is the reason for considering the term "greedy" itself: how does an attempt to solve a problem deal with the fact that sometimes what seems like the best idea at the time can in fact not bring about the ideal outcome? If it generally ignores this problem and just does what makes the most sense one step at a time, the solution is generally considered a greedy one; if it attempts to consider the impact of local optima in some way, it isn't (even if it produces terrible results!); if it considers all possible solutions, it's brute-force...etc.

Title: Is this still a Greedy Algorithm


问:
Some tips on creating programs in C?
So I'm currently in my first year in university studying electrical engineering. I'm taking a intro to C course, and I'll say it now, I'm not sure if I'm going to be able to pass the exam. Even with the help of my father I find programming extremely hard. If you give me a code to trace and figure out what's being printed, if it will have any errors, I'm pretty good at doing that. However, when it comes to writing a program from scratch, this is my real struggle. Even if I'm given a set of instructions on how to do it, I still won't be able to do it. For example, I'm doing a past exam that asks me to prompt the user to enter  integers until the user enters 0. Spent 3 hours thinking about it to no ado. At this point the program will take all the user inputted values and take an average.

So this is how I thought it out:

I need to use a for loop or a while loop to prompt the user to enter an integer.

I need to find some way to store the variables the user enters.

If the user enters 0, I'll use an if statement to calculate the average, print it out, and break.

So I'm stuck on finding some way to store all the variables and this has stumped me for hours.

答:
You don't need to store all the variables, only their running total and how many of them there are to calculate the mean.

FTR, to store all the variables, you would need a dynamically allocated data structure, which requires malloc/free and nobody should have that shit inflicted on them.

Title: Some tips on creating programs in C?


答:
Your interface should document how it handles bogus input, and can declare Exceptions it will throw.  In this case, a simple

@throws IllegalArgumentException would do the trick.

Title: Can a Java interface declaration enforce parameter properties?

Body:
As far as I know, declaring an interface is like so:

```<code>public interface Roots_Squares {
    public double square_root( double value );
}
</code>```

Now... how do you enforce value to have non-negative values?  Such a function should avoid negative values right?  If someone creates a class that implements this, and that implementation does not handle negative values, and then I use their class with a negative value... well, things break.

It then becomes my responsibility to check for negatives when I'm pretty sure the implementor should do the checking.


答:
An important way of learning programming (and many other things) is by reading the work of others, especially masters.

Equally important to programming is to do what you have been asked to do and nothing else.

So, if the questions asks

prompt the user to enter integers until the user enters 0.

then that's all you should do. The first cut of the logic might look something like

```<code>output the prompt
get the number
if number not zero then loop
</code>```

So what tools or pieces do we have to build this from?

Maybe you could use printf to output the prompt, scanf to get the input, and while to form the loop. Does that make sense?

But those pieces don't match the initial logic (unless you know about a do ... while loop). So we would start with the loop

```<code>while (n != 0) {
    printf("Please input an integer\n"); // output the prompt
    scanf("%d", &n); // get the number
}
</code>```

Of course, you'll see that we haven't defined n, so we better add it

```<code>int n = -1; // initialize n so that the loop will work the first time
while (n != 0) {
    printf("Please input an integer\n"); // output the prompt
    scanf("%d", &n); // get the number
}
</code>```

The question didn't ask for a function, or a working program, or the correct #includes, so I haven't written them.

The key to learning to programm is (apart from reading code) is to write code. Lots of it. Make mistakes. Fix them. Learn from them. And do more. Do it until you can think in code. Everyone of average intelligence can do it.

And another thing. You wouldn't believe how dumb the computer is. You have to tell it everything. And it only does what you tell it, not what you intended.

And about exams - make sure you understand what is expected. For example, if the lecturer has said to always add the correct #includes, then do it. Exam papers always have context and interpretation from the semester of study.

Title: Some tips on creating programs in C?

Body:
So I'm currently in my first year in university studying electrical engineering. I'm taking a intro to C course, and I'll say it now, I'm not sure if I'm going to be able to pass the exam. Even with the help of my father I find programming extremely hard. If you give me a code to trace and figure out what's being printed, if it will have any errors, I'm pretty good at doing that. However, when it comes to writing a program from scratch, this is my real struggle. Even if I'm given a set of instructions on how to do it, I still won't be able to do it. For example, I'm doing a past exam that asks me to prompt the user to enter  integers until the user enters 0. Spent 3 hours thinking about it to no ado. At this point the program will take all the user inputted values and take an average.

So this is how I thought it out:

I need to use a for loop or a while loop to prompt the user to enter an integer.

I need to find some way to store the variables the user enters.

If the user enters 0, I'll use an if statement to calculate the average, print it out, and break.

So I'm stuck on finding some way to store all the variables and this has stumped me for hours.

Body:
An important way of learning programming (and many other things) is by reading the work of others, especially masters.

Equally important to programming is to do what you have been asked to do and nothing else.

So, if the questions asks

prompt the user to enter integers until the user enters 0.

then that's all you should do. The first cut of the logic might look something like

output the prompt
get the number
if number not zero then loop

So what tools or pieces do we have to build this from?

Maybe you could use printf to output the prompt, scanf to get the input, and while to form the loop. Does that make sense?

But those pieces don't match the initial logic (unless you know about a do ... while loop). So we would start with the loop

while (n != 0) {
    printf("Please input an integer\n"); // output the prompt
    scanf("%d", &n); // get the number
}

Of course, you'll see that we haven't defined n, so we better add it

int n = -1; // initialize n so that the loop will work the first time
while (n != 0) {
    printf("Please input an integer\n"); // output the prompt
    scanf("%d", &n); // get the number
}

The question didn't ask for a function, or a working program, or the correct #includes, so I haven't written them.

The key to learning to programm is (apart from reading code) is to write code. Lots of it. Make mistakes. Fix them. Learn from them. And do more. Do it until you can think in code. Everyone of average intelligence can do it.

And another thing. You wouldn't believe how dumb the computer is. You have to tell it everything. And it only does what you tell it, not what you intended.

And about exams - make sure you understand what is expected. For example, if the lecturer has said to always add the correct #includes, then do it. Exam papers always have context and interpretation from the semester of study.


问:
I'm graduating with a Computer Science degree but I don't feel like I know how to program
I'm graduating with a Computer Science degree but I see websites like Stack Overflow and search engines like Google and don't know where I'd even begin to write something like that. During one summer I did have the opportunity to work as a iPhone developer, but I felt like I was mostly gluing together libraries that other people had written with little understanding of the mechanics happening beneath the hood.

I'm trying to improve my knowledge by studying algorithms, but it is a long and painful process. I find algorithms difficult and at the rate I am learning a decade will have passed before I will master the material in the book. Given my current situation, I've spent a month looking for work but my skills (C, Python, Objective-C) are relatively shallow and are not so desirable in the local market, where C#, Java, and web development are much higher in demand. That is not to say that C and Python opportunities do not exist but they tend to demand 3+ years of experience I do not have. My GPA is OK (3.0) but it's not high enough to apply to the large companies like IBM or return for graduate studies.

Basically I'm graduating with a Computer Science degree but I don't feel like I've learned how to program. I thought that joining a company and programming full-time would give me a chance to develop my skills and learn from those more experienced than myself, but I'm struggling to find work and am starting to get really frustrated.

I am going to cast my net wider and look beyond the city I've grown up in, but what have other people in similar situation tried to do? I've worked hard but don't have the confidence to go out on my own and write my own app. (That is, become an indie developer in the iPhone app market.) If nothing turns up I will need to consider upgrading and learning more popular skills or try something marginally related like IT, but given all the effort I've put in that feels like copping out.

答: Very few people graduate any discipline being an expert at something they have merely studied. Computer science isn't in any way special in that regard. Nothing beats empirical experience and you only get that from developing fully-fledged software for real clients, with all the demands, time-constraints, changes and teamwork this involves.


问:
Infix vs Prefix Notation - Which do you prefer?
I have been learning Clojure and looking at Scheme and CL which introduced me to the world of prefix notation. At first I didn't like it but it is still starting to grow on me. To be honest though, there are still long calculations that are difficult for me to understand but I think that is an issue of me needing more exposure/practice and I'll get it.

But that leads me to the question: Which type of notation do you prefer and why?

答: I find infix notation easier to read, simply because I've been working with it ever since kindergarten.</p>


答:
Lets consider the situation where you have the provided code of:

```<code>public void delete() throws IOException, SQLException {      // Non-Compliant
  /* ... */
}
</code>```

The danger here is that the code that you write to call delete() will look like:

```<code>try {
  foo.delete()
} catch (Exception e) {
  /* ... */
}
</code>```

This is bad too.  And it will be caught with another rule that flags catching the base Exception class.

The key is to not write code that makes you want to write bad code elsewhere.

The rule that you are encountering is a rather common one.  Checkstyle has it in its design rules:

ThrowsCount

Restricts throws statements to a specified count (1 by default).

Rationale: Exceptions form part of a method's interface. Declaring a method to throw too many differently rooted exceptions makes exception handling onerous and leads to poor programming practices such as writing code like catch(Exception ex). This check forces developers to put exceptions into a hierarchy such that in the simplest case, only one type of exception need be checked for by a caller but any subclasses can be caught specifically if necessary.

This precisely describes the problem and what the issue is and why you shouldn't do it.  It is a well accepted standard that many static analysis tools will identify and flag.

And while you may do it according to language design, and there may be times when it is the right thing to do, it is something that you should see and immediately go "um, why am I doing this?"  It may be acceptable for internal code where everyone is disciplined enough to never catch (Exception e) {}, but more often than not I've seen people cut corners especially in internal situations.

Don't make people using your class want to write bad code.

I should point out that the importance of this is lessened with Java SE 7 and later because a single catch statement can catch multiple exceptions (Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking from Oracle).

With Java 6 and before, you would have code that looked like:

```<code>public void delete() throws IOException, SQLException {
  /* ... */
}
</code>```

and

```<code>try {
  foo.delete()
} catch (IOException ex) {
     logger.log(ex);
     throw ex;
} catch (SQLException ex) {
     logger.log(ex);
     throw ex;
}
</code>```

or

```<code>try {
    foo.delete()
} catch (Exception ex) {
    logger.log(ex);
    throw ex;
}
</code>```

Neither of these options with Java 6 are ideal.  The first approach violates DRY.  Multiple blocks doing the same thing, again and again - once for each exception.  You want to log the exception and rethrow it?  Ok.  The same lines of code for each exception.

The second option is worse for several reasons.  First, it means that you are catching all the exceptions.  Null pointer gets caught there (and it shouldn't).  Furthermore, you are rethrowing an Exception which means that the method signature would be deleteSomething() throws Exception which just makes a mess further up the stack as people using your code are now forced to catch(Exception e).

With Java 7, this isn't as important because you can instead do:

```<code>catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}
</code>```

Furthermore, the type checking if one does catch the types of the exceptions being thrown:

```<code>public void rethrowException(String exceptionName)
throws IOException, SQLException {
    try {
        foo.delete();
    } catch (Exception e) {
        throw e;
    }
}
</code>```

The type checker will recognize that e may only be of types IOException or SQLException.  I'm still not overly enthusiastic about the use of this style, but it isn't causing as bad code as it was under Java 6 (where it would force you to have the method signature be the superclass that the exceptions extend).

Despite all these changes, many static analysis tools (Sonar, PMD, Checkstyle) are still enforcing Java 6 style guides.  It's not a bad thing.  I tend to agree with a warning these to still be enforced, but you might change the priority on them to major or minor according to how your team prioritizes them.

If exceptions should be checked or unchecked... that is a matter of great debate that one can easily find countless blog posts taking up each side of the argument.  However, if you are working with checked exceptions, you probably should avoid throwing multiple types, at least under Java 6.

Title: Why shouldn't a method throw multiple types of checked exceptions?

Body:
We use SonarQube to analyse our Java code and it has this rule (set to critical):

Public methods should throw at most one checked exception

Using checked exceptions forces method callers to deal with errors, either by propagating them or by handling them. This makes those exceptions fully part of the API of the method.

To keep the complexity for callers reasonable, methods should not throw more than one kind of checked exception."

Another bit in Sonar has this:

Public methods should throw at most one checked exception

Using checked exceptions forces method callers to deal with errors, either by propagating them or by handling them. This makes those exceptions fully part of the API of the method.

To keep the complexity for callers reasonable, methods should not throw more than one kind of checked exception.

The following code:

```<code>public void delete() throws IOException, SQLException {      // Non-Compliant
  /* ... */
}
</code>```

should be refactored into:

```<code>public void delete() throws SomeApplicationLevelException {  // Compliant
    /* ... */
}
</code>```

Overriding methods are not checked by this rule and are allowed to throw several checked exceptions.

I've never come across this rule/recommendation in my readings on exception handling and have tried to find some standards, discussions etc. on the topic.  The only thing I've found is this from CodeRach: How many exceptions should a method throw at most?

Is this a well accepted standard?

Body:
Lets consider the situation where you have the provided code of:

public void delete() throws IOException, SQLException {      // Non-Compliant
  /* ... */
}

The danger here is that the code that you write to call delete() will look like:

try {
  foo.delete()
} catch (Exception e) {
  /* ... */
}

This is bad too.  And it will be caught with another rule that flags catching the base Exception class.

The key is to not write code that makes you want to write bad code elsewhere.

The rule that you are encountering is a rather common one.  Checkstyle has it in its design rules:

ThrowsCount

Restricts throws statements to a specified count (1 by default).

Rationale: Exceptions form part of a method's interface. Declaring a method to throw too many differently rooted exceptions makes exception handling onerous and leads to poor programming practices such as writing code like catch(Exception ex). This check forces developers to put exceptions into a hierarchy such that in the simplest case, only one type of exception need be checked for by a caller but any subclasses can be caught specifically if necessary.

This precisely describes the problem and what the issue is and why you shouldn't do it.  It is a well accepted standard that many static analysis tools will identify and flag.

And while you may do it according to language design, and there may be times when it is the right thing to do, it is something that you should see and immediately go "um, why am I doing this?"  It may be acceptable for internal code where everyone is disciplined enough to never catch (Exception e) {}, but more often than not I've seen people cut corners especially in internal situations.

Don't make people using your class want to write bad code.

I should point out that the importance of this is lessened with Java SE 7 and later because a single catch statement can catch multiple exceptions (Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking from Oracle).

With Java 6 and before, you would have code that looked like:

public void delete() throws IOException, SQLException {
  /* ... */
}

and

try {
  foo.delete()
} catch (IOException ex) {
     logger.log(ex);
     throw ex;
} catch (SQLException ex) {
     logger.log(ex);
     throw ex;
}

or

try {
    foo.delete()
} catch (Exception ex) {
    logger.log(ex);
    throw ex;
}

Neither of these options with Java 6 are ideal.  The first approach violates DRY.  Multiple blocks doing the same thing, again and again - once for each exception.  You want to log the exception and rethrow it?  Ok.  The same lines of code for each exception.

The second option is worse for several reasons.  First, it means that you are catching all the exceptions.  Null pointer gets caught there (and it shouldn't).  Furthermore, you are rethrowing an Exception which means that the method signature would be deleteSomething() throws Exception which just makes a mess further up the stack as people using your code are now forced to catch(Exception e).

With Java 7, this isn't as important because you can instead do:

catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

Furthermore, the type checking if one does catch the types of the exceptions being thrown:

public void rethrowException(String exceptionName)
throws IOException, SQLException {
    try {
        foo.delete();
    } catch (Exception e) {
        throw e;
    }
}

The type checker will recognize that e may only be of types IOException or SQLException.  I'm still not overly enthusiastic about the use of this style, but it isn't causing as bad code as it was under Java 6 (where it would force you to have the method signature be the superclass that the exceptions extend).

Despite all these changes, many static analysis tools (Sonar, PMD, Checkstyle) are still enforcing Java 6 style guides.  It's not a bad thing.  I tend to agree with a warning these to still be enforced, but you might change the priority on them to major or minor according to how your team prioritizes them.

If exceptions should be checked or unchecked... that is a matter of great debate that one can easily find countless blog posts taking up each side of the argument.  However, if you are working with checked exceptions, you probably should avoid throwing multiple types, at least under Java 6.


问:
Why Microsoft’s Web API is named as ASP.Net Web API
ASP.Net is Active Server Pages using .Net Framework

Wikipedia says

It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server Pages (ASP) technology.

While answering this question following thought came to me – why Microsoft named it’s Web API as “ASP.Net Web API”. There are no Pages involved in Web API. Then why do some people call it as “Active Server Pages .Net Web Api” ?

I believe there are some fundamental features of ASP.Net shared with Web API. So what are they?

Another observation - why is the tag in programmers naming it as "asp.net-mvc-web-api"?

Reference:

ScottGu's Blog- ASP.NET Web API

答:
As you probably know, Web API used to be a part of WCF and NOT part of the ASP.NET family. Microsoft tried to develop the technology under the WCF Web API moniker for several years, but eventually decided that they were probably trying to fit a square peg in a round hole.

I think that makes sense. After all, WCF always does seems to be more "Service" oriented (I don't like to use that term, but I can't think of a better term), while Web API seems to lean more to the RESTful end of things. So adding it to the ASP.NET family makes a lot of sense to me, as the ASP.NET family relates to everything Microsoft is doing that involves HTTP/Web.

Try not to take the ASP.NET name too seriously, as the original ASP name was conceived in 2000. Think of it more as the .NET stack for building full-fledged web applications, whether that involves web pages or not.


问:
Why is there no WSDL type support for Web Api?
So I am just getting started with .Net WebApi and one thing that I am noticing straight away is that there is no Contract defining how the API looks and should be consumed (Request/Responses from each Action), this is usually in the form of a WSDL for WCF/Soap.

It seems to me like this is something that would be very valuable and make life a lot easier for consumers of your API.

Is there a reason there isn't one? Is there a programming paradigm or principle that I am unaware of? Is there a way I could create one?

答:
While a lot of the answers here are great, I think the answer is MUCH simpler: you're looking at the wrong technology for the job.

If you're looking to build a SOAP-service, you really should stick to WCF. It's still a very powerful framework, Microsoft is still actively developing it, no announcements were made for us to think it's going anywhere in the future, and it was made with this in mind. Web API does in no way supersede WCF (although it's probably trendier than WCF).

Web API used to be part of WCF, but it was moved over to the ASP.NET family exactly BECAUSE it didn't really fit alongside the other WCF technologies. Web API is much more concerned with using HTTP as an application protocol than a transfer protocol. In Web API, the HTTP verbs are king, in WCF HTTP merely serves to enable the SOAP protocol.

Don't blame Web API for not giving the ability to do certain things that it was not made for.


问:
What rights do I have if a closed source non-distributed in-home application was stolen?
I was always wondering about this, because I have been recently reading about many leaks and stolen programs on certain news sites:

If a program (running on a server for example, serving http clients), which is closed source and not released to the public, that uses a LGPL or GPL library gets stolen, can the owner of the program effectively* sue the thief?

effectively - the company won't be turned down by a judge?

答:
I am not a lawyer - this is not legal advise.

You have copyright over the application (or parts of it) that you wrote, so you have a legal claim your rights have been infringed regardless of the status of the open source licenses and your obligation to open-source the code you own the copy right to.

The issue over your obligation to open-source your copyrighted work is a separate legal issue. The theft of the copyrighted material owned by you is still illegal even if you have not fulfilled your obligations to the copyright holder of the libraries.

So the next question "effectively".......How much are yo prepared to spend on lawyers.... Do you know who stole it, do you have proof.....


答:
The answer has been given to you on a plate, unfortunately its not going to help you learn and you are not a better programmer unless you think about how we got the answer so easily.  (Or do you just want to pass an exam?)

"So I'm stuck on finding some way to store all the variables and this
  has stumped me for hours."

Did you think to ask "Is there another way" - how do you think the answerers here came up with the answer? Did we all know it already, how did we solve it so quickly. We quickly realised that the way you were thinking was never going to work.

My though process is "That list potentially has unlimited inputs, storing the numbers is not possible. How else can it be done? what is an average? - total divided by number of samples. Keep a running total and count of the number of samples. Calculate average at end.

I though that through about as fast as you will have read it. How  - experience and doing it lots of times, nothing to do with us being cleverer than you.....

Title: Some tips on creating programs in C?


问:
Simple Injector in Onion Layer Architecture
I'm trying to find a good resource, advice, etc in a project I've taken on for myself at work.

Background

When I started here we had a application that was part MVC part Webform (separate projects on solution) that was tightly coupled to it's DAL with business code all over the place.

I refactored the entire solution into the onion layer architecture almost two years ago using ninject. killed of it's SOAP services in favor of WebAPI and moved the vast majority of the webforms into MVC overtime. (still some left in webforms, but their days are numbered)

Overall this has been a major success in regards to maintainability, stability, and getting our business logic where it belongs. Lately though performance has been a growing issue. We've establish multiple causes, but we were surprised at how badly ninject was impacting our performance, after some research we found ninject was infact one of the worst DI frameworks from a performance stand point. With this in mind we're moving to simple injector as it impressed us.

The problem

We don't just rewrite our work, we gradually move it where able. We all know we can't realistic blend ninject with simple and not expect utter chaos. With that in mind we cleaned up our code to make sure it all would work with both ninject and simple and we're to that final step of actually wiring the whole thing up...

Except every guide, tutorial, and example I've found has the actual UI project (MVC) reference both the interface and the project I'll inject my classes from...

Example:

```<code>container.Register<ILoggingService, LoggingService>();
</code>```

With Onion Architecture we strived to make sure our front end had no direct references to the supporting code. This was handled by having a project separate from my MVC project to handle injection thereby allowing me to never have a reference between my UI and my backend code. (Thus preventing you from accidentally bypassing your interface and DI)

The above would require me to directly reference the backend code and in my opinion fundamentally defeat what we've strived to do. Perhaps my heads not all together from being tired + mentally on holiday already, but I'm having a heck of a time trying to figure out how to accomplish what we had under ninject in simple injector (I'm sure it's stupid easy, but I've been beating my head on this for hours so any help would go a long way)

答: Usually, there is some kind of "Application" or "Launcher" project, which references every assembly the application needs to run. Only responsibility of this project is to wire up the dependencies and start up the application. It has no UI and no behavior. But I'm not sure how this would handle in MVC application.</p>


问:
Using action array vs Switch Case
I have an occasion of code in which I will draw a different set of buttons in a screen (depending on the number of the buttons).
One thought (and my current implementation) is to use an action array and call a different action

```<code>        Action[] array = new Action[9];
        array[0] = one;
        array[1] = two;
        array[2] = three;
        array[3] = four;
        array[4] = five;
        array[5] = six;
        array[6] = seven;
        array[7] = eight;
        array[8] = nine;

        array[buttons.Count - 1]();
</code>```

So depending on the number of buttons I call the specific drawing method. Another implementation might be using switch case and would look like something this

```<code>switch(buttons.count){
case 1: one(); break;
case 2: two(); break;
.
.
.
.
case 9: nine();break;
}
</code>```

Are there any pros and cons of using versus the other?
Are there any efficiency differences?

答:
Of course there are pro and con effects; if there weren't, the community would long ago have figured them out, and everybody would agree to do always the one and never the other.

A switch statement is fine if the things you switch over have only one behaviour. A button does something when clicked, so that seems appropriate. But as soon as the variable you're switching over has more than one behaviour, you would need a second switch statement listing exactly the same cases. That's a violation of DRY, and it will get worse with every additional thing that's added to the class. And let's be honest: when was the last time you saw an established class get less complex?

An array of objects that all dispatch the same messages avoids this problem. It may or may not be less efficient than a switch compiled into a jump table. If it is, the difference may or may not be worth compromising other principles. If it is, it may or may not be a good idea if you do compromise them now, considering that the system will evolve further and today's small compromise might become a huge maintenance headache for years to come.

This is why only you know whether to choose one option over the other: because the particulars of your application probably outweigh the general pressures that we can enumerate for you.

(It's a bit like prejudice: when all you know about a web application is that it was written by volunteers in PHP, it's fine to assume that it's probably on the less secure side vs. one that is used by a major bank. After all, many such apps are in fact insecure. But if you have concrete examples of either web app, looking at the particulars of both instances is virtually always smarter than relying on general maxims, i.e. prejudice.)

Title: Using action array vs Switch Case


答:
IMHO the first one is in most cases preferable. First, in C# you can rewrite the initialization  much shorter as

```<code>    Action[] array = new[]{one, two, three, four, five, six, seven,eight,nine};
</code>```

But the real advantage comes when you have to change your actions later, for example, by introducing an additional argument. You then have to change only this line

```<code>    array[buttons.Count - 1](myArgument);
</code>```

The switch variant instead needs changes in 9 places instead:

```<code>switch(buttons.count){
case 1: one(myArgument); break;
case 2: two(myArgument); break;
...
</code>```

That is because the switch variant does not follow the "Don't Repeat Yourself" (DRY) principle. Imagine what happens when you have not just 9 actions, but 50, or you have to introduce more arguments, or to process a return code from the action / function.

And don't worry too much about performance - in most real-world cases the performance difference is negligible. When you suspect it is not, you will have to try and measure if a replacement by a switch statement does really bring the necessary performance gain.

Title: Using action array vs Switch Case

Body:
I have an occasion of code in which I will draw a different set of buttons in a screen (depending on the number of the buttons).
One thought (and my current implementation) is to use an action array and call a different action

```<code>        Action[] array = new Action[9];
        array[0] = one;
        array[1] = two;
        array[2] = three;
        array[3] = four;
        array[4] = five;
        array[5] = six;
        array[6] = seven;
        array[7] = eight;
        array[8] = nine;

        array[buttons.Count - 1]();
</code>```

So depending on the number of buttons I call the specific drawing method. Another implementation might be using switch case and would look like something this

```<code>switch(buttons.count){
case 1: one(); break;
case 2: two(); break;
.
.
.
.
case 9: nine();break;
}
</code>```

Are there any pros and cons of using versus the other?
Are there any efficiency differences?

Body:
IMHO the first one is in most cases preferable. First, in C# you can rewrite the initialization  much shorter as

    Action[] array = new[]{one, two, three, four, five, six, seven,eight,nine};

But the real advantage comes when you have to change your actions later, for example, by introducing an additional argument. You then have to change only this line

    array[buttons.Count - 1](myArgument);

The switch variant instead needs changes in 9 places instead:

switch(buttons.count){
case 1: one(myArgument); break;
case 2: two(myArgument); break;
...

That is because the switch variant does not follow the "Don't Repeat Yourself" (DRY) principle. Imagine what happens when you have not just 9 actions, but 50, or you have to introduce more arguments, or to process a return code from the action / function.

And don't worry too much about performance - in most real-world cases the performance difference is negligible. When you suspect it is not, you will have to try and measure if a replacement by a switch statement does really bring the necessary performance gain.


问:
What can I say in Github issues?
I'm new to the open source community. When I look at projects on Github I don't see any "forum". There's only an "issues" page. Is that only meant for submitting bugs? Or can I say other things? for example:

Can I suggest features? e.g. "I have an idea. It would be great if this project had this and that."

Can I ask questions like "How does this work?" or "What's the syntax for this?"

Is it nice to address problems that I'm having? e.g. "I tried this but it didn't work. Maybe I'm doing something wrong. Can someone help me?"

Can I ask what the owners think about a pull request I want to send? e.g "I'm going to implement this. Would you accept it?"

答:
Yes to all but check to see if there is a better place for 2 and 3.

StackOverflow should be your first port of call, first to check if your question has been asked and second to construct a question.

1 and 4 are most certainly the sort of things you can create an issue for. The maintainers are likely to tag them as 'Feature request' or 'Improvement' etc.

Title: What can I say in Github issues?


答:
Well, there are many arguments one way or the other.

But the most important thing to realize: it doesn't matter (in this case).

Performance wise, the drawing (and subsequent rendering of it) will take order of magnitudes longer than the invocation of the right drawing functions.

Complexity wise, the drawing code will most likely also crushingly outweigh the invocation issue. The fact that you need nine different drawing functions makes this pretty clear.

If you are actually concerned with this, the right thing to do is to blackbox the decision in a separate class, where a button count goes in and a drawing function comes out. Thus no other code depends on how this is accomplished and you can change that any time you have a reason to.

Title: Using action array vs Switch Case


问:
To include a resource ID in the payload or to derive from URI
Designing an API, we've come up against the question of whether a PUT payload should contain the ID of the resource being updated.

This is what we currently have:

PUT /users/123 Payload: {name: "Adrian"}

Our route code extracts the ID from the URI and continues on with the update.

The first users of our API are questioning why we don't allow ID in the payload:

PUT /users/123 Payload: {id: 123, name: "Adrian"}

The reason we didn't allow it is because the ID is duplicated, in the payload and URI.

Thinking about this some more, we are coupling the resource to the URI.

If the URI doesn't have the ID, the payload will need to be amended:

PUT /no/id/here Payload: {name: "Adrian"} < What user???

Are there any reasons not to?

答:
You are supposed to couple the Uniform Resource Identifier to the resource.

When REST is implemented with HTTP, you use GET to retrieve the current value of the resource and PUT to set a new value. The GET does not have a payload, so the resource has to be identified by the URI. And the PUT is logically done to the same URI and the payload should look exactly as what you want the next GET to return.

You can use POST to different URI, but it would only make less sense as it would be unnecessarily asymmetrical to the GET. POST to common URI could only make sense for creating new resources (POST /users/new, payload: {name: "Adrian"}, response {id: 345, name: "Adrian"}), but that's not idempotent and therefore should be avoided if you are striving for REST¹. Instead you should reserve ID with one call and then use PUT to set the new ID; that is fault-tolerant, because if the first request fails, the ID reservation can time out eventually and the PUT is idempotent. Or use client-generated UUID.

¹ The definition of REST does not say anything about idempotence, so I can't really claim it is not REST if you have non-idempotent operations. That does not change the fact that sticking to idempotent requests makes things more reliable without complicating them and is therefore recommended.


问:
Django Project Logic Solution
I'm starting to develop my first webapp, and I'm using django.

Before anything I'm working on the software logic, how it should work, the links and objects it needs.

The problem is:

I need the app to create a new database for each new client(superuser) of mine. And this db should record some models containing info about some "read only" users, created by the admin.

The thing is, one "read only" user can, and possibly will be, in other databases from other superusers. Is it even possible to get access to the info of this "read only" user from one database to the other?

Or should I just use one database that handles multiple clients?

The superusers should NOT be related and they don't need to know about each other. The only thing that's important is that the "read only" users should get access to their data stored both superusers X and Y. This is every time they login the system.

Thanks!

答: You need to put it all into one database. SuperUsers should only link to ReadOnly users data, so that the ReadOnly user data is not duplicated.</p>

Title: Django Project Logic Solution


问:
Using a global struct with pthreads in C
I'm trying to simulate clients going into a bank and being served by tellers over a period of time.  I am using a thread to determine if a client came into the bank via an arrival rate and am using multiple threads to represent tellers with an s service rate.  I am using a struct to hold the period of time, arrival rate, service rate, number of tellers, and the customer waiting queue.  I am attempting to share that struct between all threads but get "dereferencing pointer" errors and "request for member x in something not a structure" error.

```<code>//Used to store information input by user and the customer queue
struct shiftInfo {
    int tellers;
    int serviceTime;
    int simTime;
    int sampleInterval;
    int threadID;
    float arrivalRate;
    int Q[]; //Customer Queue
};
</code>```

The information is passed from into the struct from the command line via

```<code>    struct shiftInfo *Q = malloc(sizeof(struct shiftInfo) + (maxCust*sizeof(int)));
    struct shiftInfo info;
    info.simTime = atoi(argv[1]);
    info.arrivalRate = atof(argv[2]);
    info.tellers = atoi(argv[3]);
    info.serviceTime = atoi(argv[4]);
    info.sampleInterval = atoi(argv[5]);
    //Initiates Q to 0
    for (int i = 0; i < maxCust; i++)
        info.Q[i] = 0;
</code>```

The teller, timer, and customer threads are created and terminated by a main thread

```<code>  //Manager thread is main thread
  pthread_t manager;
  iret = pthread_create(&manager, NULL, mainThread, (void *)&info);
  if (iret){
    printf("ERROR: return code %d\n", iret);
    exit(-1);
    }
</code>```

To keep this short I'm going to only ask about the timer thread and hopefully apply the answer to the other threads.  The timer thread is created in the main thread by:

```<code>  int status;
  struct shiftInfo *I = info;
  pthread_t time;
      status = pthread_create(&time, NULL, timer, (void *)info);
      if (status){
        printf("ERROR CODE: %d\n", status);
        exit(-1);
    }
</code>```

And the timer thread function is:

```<code>void *timer(void *info){
    int timeRemaining = info -> simTime;
    while(timeRemaining){
        sleep(1);
        timeRemaining--;
        }
}
</code>```

For "int timeRemaining = info -> simTime;" I get the warning "dereferencing void pointer" and the error  request for member âsimTimeâ in something not a structure or union.
Any advice would be appreciate.

Also, I create the customer thread identically to the way I create the timer thread but receive a warning (warning: passing argument 3 of âpthread_createâ makes pointer from integer without a cast [enabled by default]) that I do not receive when creating any other thread, what causes that?

```<code>pthread_t customer;
    status = pthread_create(&customer, NULL, customer, (void *)info);
        if (status){
            printf("ERROR CODE: %d\n", status);
            exit(-1);
        }
</code>```

答:
```<code>struct shiftInfo *Q = malloc(sizeof(struct shiftInfo) + (maxCust*sizeof(int)));
</code>```

This allocates a struct shiftInfo object with space reserved for maxCust integers. Looks ok ...

```<code>struct shiftInfo info;
info.simTime = atoi(argv[1]);
info.arrivalRate = atof(argv[2]);
info.tellers = atoi(argv[3]);
info.serviceTime = atoi(argv[4]);
info.sampleInterval = atoi(argv[5]);
</code>```

... but then this ^ creates another struct shiftInfo object, with no extra space reserved for customers, and with local scope.

```<code>//Initiates Q to 0
for (int i = 0; i < maxCust; i++)
    info.Q[i] = 0;
</code>```

And finally, this ^ sets up the customer array that doesn't exist in the local object. The dynamically-allocated object called Q, which does have space for this customer array, never seems to be used.

Body:
struct shiftInfo *Q = malloc(sizeof(struct shiftInfo) + (maxCust*sizeof(int)));

This allocates a struct shiftInfo object with space reserved for maxCust integers. Looks ok ...

struct shiftInfo info;
info.simTime = atoi(argv[1]);
info.arrivalRate = atof(argv[2]);
info.tellers = atoi(argv[3]);
info.serviceTime = atoi(argv[4]);
info.sampleInterval = atoi(argv[5]);

... but then this ^ creates another struct shiftInfo object, with no extra space reserved for customers, and with local scope.

//Initiates Q to 0
for (int i = 0; i < maxCust; i++)
    info.Q[i] = 0;

And finally, this ^ sets up the customer array that doesn't exist in the local object. The dynamically-allocated object called Q, which does have space for this customer array, never seems to be used.