答:
I'm not sure I'd say that I couldn't solve a problem, but there have been cases where I did give up on trying to solve a problem.  After pouring many hours into trying to fix a bug or implement some feature that I don't have an idea of how to do it, I may tell someone on my team, team leader or manager, "I'm stuck on this.  What do you want me to do?" so that they know where I am.  They could say, "Keep at it, we think you'll get it," or "Move on to something else that isn't that important," or a few other things and then I'll know what I should be doing.

I've had bugs that I didn't resolve and some features that didn't get done, sure.  While I can try to get something done, not everything is within my power to solve in a reasonable time.  A key point in this is to have communication so that your superiors know where you are.

That said, I did have a couple of times where I ran into some rather special circumstances:

While working at a large Canadian bank in Toronto, I would be asked to do all kinds of stuff that I didn't know how to do when I was given the task.  For example, I was asked to test out this method for securing laptops where the "Esc" and "Enter" keys were swapped on boot-up and with the right key sequence the laptop would be usable again that just seemed bizarre to try to figure out, "Would this work?  How do I know this would or wouldn't be OK with the users?"  There were other tasks that I either just didn't have the hardware or other resources to get it done.  At the same time it was rather educational as this gave me many things to note on any future employment situation to prevent trouble.  Things like ensuring when I'm paid, how is my time tracked, and other communication issues were illustrated with great detail to me here that I haven't really forgotten.

While working at an Application Service Provider in Calgary, I was given this project of trying to create a copy of another website within our internal application that we sold as a service.  A key point here is that I wasn't given a time line or suggestions on what part to do first, just general research and a month later I was asked for a demo just as I was having a bad reaction to some pain medication.  That reaction lasted a week that I took off of work suddenly and then the following week, I went to a Microsoft event that was kind of the last straw as I was fired the next day.  Something to note here is how I had a rather poor relationship with my boss as anytime he'd come near my area my immediate thought was, "Now what's wrong?" which tended to not be a rather healthy thing to have as a reaction to someone many times over.


问:
Thoughts of Cloud Development/Google App Engine
I use mainly PHP for web development, but recently, I started thinking about using Google App Engine. It doesn't use PHP which I am already familiar with, so there will be a steeper learning curve. Probably using Python/Django. But I think it maybe worthwhile. Some advantages I see:

Focus on App/Development. No need to setup/maintain server ... no more server configs

Scales automatically

Pay for what you use. Free for low usage

Reliable, it's Google after all

Some concerns though:

Does database with no joins pose a problem for those who used App Engine before?

Do I have to upload to Google just to test? Will it be slow compared to testing locally?

What are your thoughts and opinions? Why would you use or not use App Engine?

答:
I have thought about using it many times as it is a free, scalable solution up to a point. The problem I have is that, similar to you, I don't use/know the languages that are supported. I use C#/ASP.Net and so it is a problem for me.

Over the past few days I've thought of learning a JVM based language (Clojure has caught my fancy) and then going from there and using GAE but I have seen many posts on other forums that mention that depending on what you are looking for, a cheap VPS host can be better than GAE.

I will try to find those links but I believe they are at home, so I will add them when I find them.

ContentLicense: CC BY-SA 2.5


问:
Should I be worried if I solve a lot of my problems the same way?
I really enjoy programming games and puzzle creators/games. I find myself engineering a lot of these problems the same way and ultimately using similar technique to program them that I'm really comfortable with.

To give you brief insight, I like to create graphs where nodes are represented with objects. These object hold data such as coordinates, positions and of course references to other neighboring objects. I'll place them all in a data structure and make decisions on this information in a "game loop".

While this is a brief example, its not exact in all situations. It's just one way I feel really comfortable with. Is this bad?

答:
If you solve problem it's good.
And it's not matter what way till it not make more problems.</p>

ContentLicense: CC BY-SA 3.0


答:
Be careful around thinking that it's reliable just because it's from Google. Computer systems do go down and GAE is no exception. One particular case is described here. The reason I post this article and not any of the other ones on the same subject is that it's describing recent problems, not something from a year or two ago.

Automatic scaling and pay for what you use models can also be problematic if your app gets popular quickly. Admittedly, for many that's not really an issue, but it is something to be aware of. You can't really tell people to not come to your site because you don't have the money to pay the bill that month.

Personally, I'd probably stay away from GAE (and cloud services in general) at this point. I haven't found server configuration to be particularly cumbersome in the past (and on a shared hosting account it's not really my problem anyway) and I like staying in control of my data. If I ever hit the point where I need the scaling capabilities of the cloud providers, then I'll look into it again. Till then... cheap common hosting is better.

Title: Thoughts of Cloud Development/Google App Engine

Body:
I use mainly PHP for web development, but recently, I started thinking about using Google App Engine. It doesn't use PHP which I am already familiar with, so there will be a steeper learning curve. Probably using Python/Django. But I think it maybe worthwhile. Some advantages I see:

Focus on App/Development. No need to setup/maintain server ... no more server configs

Scales automatically

Pay for what you use. Free for low usage

Reliable, it's Google after all

Some concerns though:

Does database with no joins pose a problem for those who used App Engine before?

Do I have to upload to Google just to test? Will it be slow compared to testing locally?

What are your thoughts and opinions? Why would you use or not use App Engine?


问:
Type casting variables in PHP, what is the practical reason for doing this?
PHP, as most of us know, has weak typing.  For those who don't, PHP.net says:

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used.

Love it or hate it, PHP re-casts variables on-the-fly.  So, the following code is valid:

```<code>$var = "10";
$value = 10 + $var;
var_dump($value); // int(20)
</code>```

PHP also allows you to explicitly cast a variable, like so:

```<code>$var = "10";
$value = 10 + $var;
$value = (string)$value;
var_dump($value); // string(2) "20"
</code>```

That's all cool...  but, for the life of me, I cannot conceive of a practical reason for doing this.

I don't have a problem with strong typing in languages that support it, like Java.  That's fine, and I completely understand it.  Also, I'm aware of - and fully understand the usefulness of - type hinting in function parameters.

The problem I have with type casting is explained by the above quote.  If PHP can swap types at-will, it can do so even after you force cast a type; and it can do so on-the-fly when you need a certain type in an operation.  That makes the following valid:

```<code>$var = "10";
$value = (int)$var;
$value = $value . ' TaDa!';
var_dump($value); // string(8) "10 TaDa!"
</code>```

So what's the point?

Take this theoretical example of a world where user-defined type casting makes sense in PHP:

You force cast variable $foo as int → (int)$foo.

You attempt to store a string value in the variable $foo.

PHP throws an exception!! ← That would make sense.  Suddenly the reason for user defined type casting exists!

The fact that PHP will switch things around as needed makes the point of user defined type casting vague.  For example, the following two code samples are equivalent:

```<code>// example 1
$foo = 0;
$foo = (string)$foo;
$foo = '# of Reasons for the programmer to type cast $foo as a string: ' . $foo;

// example 2
$foo = 0;
$foo = (int)$foo;
$foo = '# of Reasons for the programmer to type cast $foo as a string: ' . $foo;
</code>```

A year after originally asking this question, guess who found himself using typecasting in a practical environment?  Yours Truly.

The requirement was to display money values on a website for a restaurant menu.  The design of the site required that trailing zeros be trimmed, so that the display looked something like the following:

Menu Item 1 .............. $ 4
Menu Item 2 .............. $ 7.5
Menu Item 3 .............. $ 3
```

<p>The best way I found to do that wast to cast the variable as a float:</p>

```$price = '7.50'; // a string from the database layer.
echo 'Menu Item 2 .............. $ ' . (float)$price;
```

PHP trims the float's trailing zeros, and then recasts the float as a string for concatenation.

答:
It can also be used as a quick and dirty method to ensure untrusted data isn't going to break something eg if using a remote service which has crap validation and must only accept numbers.

```<code>$amount = (float) $_POST['amount'];

if( $amount > 0 ){
    $remoteService->doacalculationwithanumber( $amount );
}
</code>```

Obviously this is flawed and also handled implicitly by the comparison operator in the if statement, but is helpful in ensuring you know exactly what your code is doing.

Body:
It can also be used as a quick and dirty method to ensure untrusted data isn't going to break something eg if using a remote service which has crap validation and must only accept numbers.

$amount = (float) $_POST['amount'];

if( $amount > 0 ){
    $remoteService->doacalculationwithanumber( $amount );
}

Obviously this is flawed and also handled implicitly by the comparison operator in the if statement, but is helpful in ensuring you know exactly what your code is doing.


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

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

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

So my questions are:

Do you have a miscellaneous utility library?

Which part are you most proud of and why?

Give an example of code if you like :-)

答:
I had some date manipulations that I performed using Java, then I started using JodaTime as I had heard good things about it and its to be included in Java 7 (not sure if this is still the case, but even if its not it is still well worth using it imho).

It turned a 50+ line class into one line with about three chained method calls.

For the curious it involved getting the date for each day of n weeks past : eg the sales figure for a monday 10 weeks ago etc etc).

And here is part of it

```<code>public static DateTime getDayPreviousWeek(DateTime dt, DayOfWeek dayOfWeek, int n_weeks) {
       return dt.minusWeeks(n_weeks).dayOfWeek().setCopy(dayOfWeek.getDayAsString());
}
</code>```

Body:
I had some date manipulations that I performed using Java, then I started using JodaTime as I had heard good things about it and its to be included in Java 7 (not sure if this is still the case, but even if its not it is still well worth using it imho).

It turned a 50+ line class into one line with about three chained method calls.

For the curious it involved getting the date for each day of n weeks past : eg the sales figure for a monday 10 weeks ago etc etc).

And here is part of it

public static DateTime getDayPreviousWeek(DateTime dt, DayOfWeek dayOfWeek, int n_weeks) {
       return dt.minusWeeks(n_weeks).dayOfWeek().setCopy(dayOfWeek.getDayAsString());
}


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

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

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

答:
First of all, your fear is very healthy, and normal. Here are my musings after about 15 years in the software industry.

Here are some questions to ask yourself:

Do you understand the problem?

Do you know that the problem is unsolvable (within your time/budget constraints)?

Do you just not know how to solve the problem?

Is your client/boss asking for the impossible.

Is it worth it? (ROI)

Is it a REAL problem?

1) First of all, make sure you understand the problem. There are no stupid questions.
Do you understand what your client/boss is asking you versus what they need?

2) This will happen. "Build me a bridge by tomorrow". Make sure that you know for a fact that a problem is unsolvable within your constraints. Your client/boss might be flexible on the time/budget and these can be modified to give you more time/budget.

3) If the problem is understandable and the constraints are within reason, and there is technology that can solve the problem, but you just don't know enough...that's what StackOverflow and the Internet is for. Make sure you do your research first. Try to ask explicit questions that have quantifiable answers. Ask your peers. Have a design session.

4) This is a variant of answer number 2. It seems like your client/boss is asking the impossible. Do some research. Never say that the problem is unsolvable, unless you know exactly why and you can clarify.

5) ROI stands for Return On Investment. This refers to an investment in time. Your Time!. Is the problem important enough to solve to warrant the amount of time it will take you to research and solve the problem. Discuss this with your client/boss

6) Is it a real problem. Clients, often times, understand what they want, but don't necessarily understand what they need. Try to understand what your Client/Boss actually needs and discuss this with them.

Hope these guidelines help you.


答:
To answer your questions:

1) The BigTable database is different from a relational database. You can still have references between objects. Its not just a relational database "without joins" - that would be broken - its a completely different kind of database system. It will have a learning curve and it is optimized for some use cases at the expense of others but I doubt you will find a use case it cannot solve for.

2) The SDK includes a local execution platform that is identical in interface and behavior. So no, you do not have to publish your app to test it locally.


问:
GPLed Library (EXT JS) Licensing Issue
Good Day Everyone,

I am realy out of option for interpreting the GPL for EXTJS for my work/idea/personal project. I can see that this is an active forum I realy hope, I have a closure on this.

First let me explain my project, Iam creating this website which is like a webportal which is intented for End-User, now this webapps uses an EXTJS library which is GPL'ed as with my understanding on this GPL Any application uses GPL license libray should be released to as Open Source a a GPL compatible Linsence, this is when I or my application is a derivework or I have modified the Library and released it. or destribute it.

But EXTJS has this dual license which is typically giving me the rights to do what I want. without giving out my code.

If my application is intented for end user only, not a derive form of work, not a library, not a development tool, I will not distribute it because it is on the web. with this also the Libraries i will use will remain untouch as it is. and I will have list of library I use and thier respective license to credit them

Given this can I not close-source my application and not violate the GPL?
is it ok for me to use GPL library so long as the above is meet?

The question in short is can i used GPL'ed Library, do not released my code as OPensource compatible License
and still NOT violate the GPL'ed terms?

Thanks in Advance

Nick Ace

答:
The intent of the ExtJs license is pretty clear: if you want to distribute your software without releasing your own source code, you have to buy a commercial license.

Based on the "Quid Pro Quo" principle,
  if you wish to derive a commercial
  advantage by not releasing your
  application under an open source
  license, you must purchase an
  appropriate number of commercial
  licenses from Sencha. By purchasing
  commercial licenses, you are no longer
  obligated to publish your source code.

http://www.sencha.com/products/license.php

Note that this is about distribution. If your application is an in-house application, and you are not distributing the application to the outside world, then you don't need to buy a commercial license.  Notice the words "releasing your application" in the quote above.

With respect to using the ExtJs library for an application in which the pages will be seen by the outside world, I would contact Sencha and ask them if they consider this a form of distribution.

Title: GPLed Library (EXT JS) Licensing Issue


答:
I wrote a small utils package when I was doing Java development in my Comp. Sci class in high school. I'm most proud of my random number generator.

```<code>/**
* Returns a random integer.
*
* @returns    int    Random integer
*/
public static int getRandom()
{
    return 4; // Chosen by a fair dice roll.
              // Guaranteed to be random.
}
</code>```

Props to my inspiration.

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

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

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

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

So my questions are:

Do you have a miscellaneous utility library?

Which part are you most proud of and why?

Give an example of code if you like :-)

Body:
I wrote a small utils package when I was doing Java development in my Comp. Sci class in high school. I'm most proud of my random number generator.

/**
* Returns a random integer.
*
* @returns    int    Random integer
*/
public static int getRandom()
{
    return 4; // Chosen by a fair dice roll.
              // Guaranteed to be random.
}

Props to my inspiration.


问:
Are short identifiers bad?
Are short identifiers bad? How does identifier length correlate with code comprehension? What other factors (besides code comprehension) might be of consideration when it comes to naming identifiers?

Just to try to keep the quality of the answers up, please note that there is some research on the subject already!

Edit

Curious that everyone either doesn't think length is relevant or tend to prefer larger identifiers, when both links I provided indicate large identifiers are harmful!

Broken Link

The link below pointed to a research on the subject, but it's now broken, I don't seem to have a copy of the paper with me, and I don't recall what it was. I'm leaving it here in case someone else figure it out.

http://evergreen.loyola.edu/chm/www/Papers/SCP2009.pdf

答: In, and of themselves, short identifiers are not bad.  The purpose of choosing good names (short or long) is in service to code clarity.  Choosing identifiers in the service of code clarity is more important than meeting some minimum length requirement.  In general what this means is writing slightly longer meaningful names.

Title: Are short identifiers bad?


问:
What is a practical way to debug Rails?
I get the impression that in practice, debuggers are rarely used for Rails applications. (Likewise for other Ruby apps, as well as Python.)

We can compare this to the usual practice for  Java or VisualStudio programmers--they use an interactive debugger in a graphical IDE.

How do people debug Rails applications in practice? I am aware of the variety of debuggers, so no need to mention those, but do serious Rails programmers work without them? If so, why do you choose to do it this way?

It seems to me that console printing has its limits when debugging complex logic.

答: I wrote about 30 pages on debugging techniques, separated out by various levels—from OS-level debugging tools, to logging tools, to log based alerts, to C tools, to browser debugging techniques. I published this as a series of articles called A Comprehensive Guide To Debugging Rails.</p>

Title: What is a practical way to debug Rails?


问:
Why Beta versions have so many bugs?
When I worked in Microsoft on MSE antivirus, we had several stages of pre-release: Alpha, Beta, RC. The biggest difference between these stages were bug fixes. Each time we fixed more bugs, and usually updated some minor features.

Apple works in the same way. Look here:
http://www.techrepublic.com/article/pro-tip-how-to-create-a-bootable-usb-installer-for-os-x-yosemite/

They released a beta of Yosemite OS, but the beta is full of bugs.

Why do these big companies work like this? Isn't it better to release a beta version that was tested very thoroughly but one that just doesn't provide all the features that the final version will provide?

答:
If you wait until all possible bugs are found, you'll wait forever. Voltaire wrote it first:

Le mieux est l'ennemi du bien.

(translated: “The best is the enemy of the good.”)

It means that seeking to create perfection means you'll never actually produce anything good at all; you'll continually be not finished because you're not quite perfect. You must stop and release. Since you know you're not actually attempting to produce perfection (merely good enough will do; balance the cost of not fixing a bug against the cost of not releasing because of the additional delay) why fret that things aren't perfect?

What tends to happen is that people produce alpha versions of software while they're working on the major features; these may well be internal only, or only released to a very select group of external people, and will probably be rather broken in other ways. Then, once the major things are in place and roughly working together, a beta is created and sent to a larger group of people. This is where QA really gets their teeth in, ferreting out all sorts of minor bugs, and where the people who are very keen on getting the new features — enough to tolerate the fact that the software is known to be buggy — can get early access. There may even be a few beta cycles, as bugs are ironed out (including eventually all the show-stoppers, hopefully).

Once the cost of fixing bugs is exceeding the cost of leaving them unfixed, it's time for the full release. If you don't like bugs, that's what you should wait for. (The really conservative will even wait for the first few official patches to come out, so that even really obscure stuff gets squelched.) But some people simply are much keener on getting at those features: they're the ones that betas are aimed at (and alphas are usually for people who are pretty close to the development process only, as they're usually missing key functionality).

Agile processes try to shorten things by keeping the amount of time that things are broken really limited and putting the customer close to the development, but it's not suited to all software. Anything aimed at having a really wide release (e.g., commercial products) simply cannot have all the customers there; that forces the sort of release strategy outlined above.

Title: Why Beta versions have so many bugs?


问:
calling methods if previous call success
I my c# program I have to perform 5 steps(tasks) sequentially. basically these five should execute one after the other only the previous task performed is success. Currently I have done it in following style. But this is not very good code  style to follow.

```<code>var isSuccess=false;
isSuccess=a.method1();

if(isSuccess)
    isSuccess=a.method2();

if(isSuccess)
    isSuccess=a.method3();

if(isSuccess)
    isSuccess=a.method4();

if(isSuccess)
    isSuccess=a.method5();
</code>```

How can I re factor this code. What is the best way I can follow?

答:
I would actually let it stay as it is, since this way it's easily readable and understandeable by anyone. But if you use the same pattern in a lot of places and all the method have the same signature here's an (overengineered and probably twisted) idea:

```<code>public class SequentialExecutor
{
    private Func<bool>[] functions;

    public SequentialExecutor(params Func<bool>[] functions)
    {
        this.functions = functions;
    }

    public bool Execute()
    {
        foreach (var func in functions)
        {
            bool isSuccess = func();
            if (!isSuccess)
            {
                return false;
            }
        }

        return true;
    }
}
</code>```

You can use it like this:

```<code>var executor = new SequentialExecutor(a.method1, a.method2, a.method3, a.method1, a.method4);
bool isSuccess = executor.Execute();
</code>```

P.S. NOT TESTED

Body:
I would actually let it stay as it is, since this way it's easily readable and understandeable by anyone. But if you use the same pattern in a lot of places and all the method have the same signature here's an (overengineered and probably twisted) idea:

public class SequentialExecutor
{
    private Func<bool>[] functions;

    public SequentialExecutor(params Func<bool>[] functions)
    {
        this.functions = functions;
    }

    public bool Execute()
    {
        foreach (var func in functions)
        {
            bool isSuccess = func();
            if (!isSuccess)
            {
                return false;
            }
        }

        return true;
    }
}

You can use it like this:

var executor = new SequentialExecutor(a.method1, a.method2, a.method3, a.method1, a.method4);
bool isSuccess = executor.Execute();

P.S. NOT TESTED


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

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

答:
I have to disagree with Konrad Rudolph. There is "One bit" of computer science you should know to make you a better "real world programmer." If you take nothing else away from the answers you're getting here, at least consider this- Satisfying the requirements is NOT the same as satisfying the client! The end users will ALWAYS try to use your program in a way you never thought of or coded for. ALWAYS, ALWAYS, ALWAYS.

Therefore, in order to be a better programmer, you must first LISTEN. Listen to the client. Listen to their needs. Listen to their wants. And especially, listen to their level of "techs-pertise." I can't tell you how many times I've seen a project built that was exactly what was requested, but not at all what the client actually neeeded. All because the programmer gathering the req's wasn't really listening.

Something else you can take away is, unless you've got a background in UI design, get someone eles to design the UI. I can ALWAYS spot an app where the UI was designed by the programmer and not an expert. What is logical and makes sense to you will not make sense to the client. And, if your clients aren't tech saavy, (and who's are?) then your "functionaly correct, but esthetically ugly" solution will be met with the warmth of skunk at a dinner party.

OwnerDisplayName: Chris G.


问:
What alternative is better to diagram this scenario?
I was creating and discussing a class diagram with a partner of mine. To simplify things, I've modify the real domain we're working on and made up the following diagram:

Basically, a company works on constructions that are quite different one from each other but are still constructions. Note I've added one field for each class but there should be many more.

Now, I thought this was the way to go but my partner told me that if in the future new construction classes appear we would have to modify the Company class, which is correct. So the new proposed class diagram would be this:

Now I've been wondering:

Should the fact that in no place of the application will there be mixed lists of planes and bridges affect the design in any way?

When we have to list only planes for a company, how are we supposed to distinguish them from the other elements in the list without checking for their class names?

Related to the previous question, is it correct to assume that this type of diagram should be high-level and this is something it shouldn't matter at this stage but rather be thought and decided at implementation time?

Any comment will be appreciated.

答:
First and foremost, the models are highly dependent of the business domain so, since you have changed it, it might be that my answer fits the question but not your real domain.

Depends of what the relationship means. An "inventory of company" or "construction projects currently active" would be examples where the relationship with AbstractProject would be understandable.

I would do, so. Of course, your language might make it difficult and you might find it easier to add a "type" attribute to AbstractProject. (Not good because it breaks the open/closed principle).

As, outside 1 & 2, I think that Plane and Bridge have so few things it common that probably you should skip the abstract class altogether. Of course, that would complicate the model, since know you either have two relationships with company (bad for the open/closed principle, if you end producing also Car), or you have to add another middle class (ConstructionProject), which is what I would do.

No, it is not high level, "free to change". It is the data that you pass to the code-monkeys so they do their job, and the data that you pass to other teams that must develop SW to use your system, so you have to stick with it.

That does not forbid you from modifying it if you see that it does not really adapt to your needs, but those modifications "in the code" must be approved, reflected in the UML, and communicated. Depending of your project management phylosophy, they would be interpreted as "mistakes" or "refinements" of your original model.


答:
If the Company does not need to know the difference between a Bridge and a Plane, the second diagram is indeed better; it encodes the fact that the Company is fundamentally ignorant of the difference.

On the other hand, if the Company needs to intimately understand the difference between a Bridge and a Plane (and any other future subclasses of AbstractConstruction) then the first diagram is the right one; it's a better model of the nature of the domain. (It might be that this is an indication that the model is wrong in other ways, such as encoding information in the wrong class, but that's out of the scope of this particular decision, and sometimes it is better to use a less perfect OO solution to get better buy-in from project partners.)

Which fits the real domain better? Well, I find it hard to think of any real company that just makes Bridges and Planes, so this is all a stand-in for something else (or a silly toy example) and it is by examining the details of that that you'll understand more completely what you should choose. However, whatever you pick, it should be the thing that best models the real situation.

I'd also rename AbstractConstruction to ConstructionProject, but that's just me. I hate putting meta-information into class names; a class is abstract if it's metadata says it is, not if its got that label. And plain old Construction is wrong too; it's the project that you're dealing with…

Title: What alternative is better to diagram this scenario?

Body:
I was creating and discussing a class diagram with a partner of mine. To simplify things, I've modify the real domain we're working on and made up the following diagram:

Basically, a company works on constructions that are quite different one from each other but are still constructions. Note I've added one field for each class but there should be many more.

Now, I thought this was the way to go but my partner told me that if in the future new construction classes appear we would have to modify the Company class, which is correct. So the new proposed class diagram would be this:

Now I've been wondering:

Should the fact that in no place of the application will there be mixed lists of planes and bridges affect the design in any way?

When we have to list only planes for a company, how are we supposed to distinguish them from the other elements in the list without checking for their class names?

Related to the previous question, is it correct to assume that this type of diagram should be high-level and this is something it shouldn't matter at this stage but rather be thought and decided at implementation time?

Any comment will be appreciated.


答:
This is the sort of situation where throwing an exception on failure may be neater. If that's your API, you can then do:</p>

```<code>try {
    a.method1();
    a.method2();
    a.method3();
    a.method4();
    a.method5();
} catch (UnsatisifedException e) {
    // Some sort of recovery logic here...
}
</code>```

Title: calling methods if previous call success

Body:
I my c# program I have to perform 5 steps(tasks) sequentially. basically these five should execute one after the other only the previous task performed is success. Currently I have done it in following style. But this is not very good code  style to follow.

```<code>var isSuccess=false;
isSuccess=a.method1();

if(isSuccess)
    isSuccess=a.method2();

if(isSuccess)
    isSuccess=a.method3();

if(isSuccess)
    isSuccess=a.method4();

if(isSuccess)
    isSuccess=a.method5();
</code>```

How can I re factor this code. What is the best way I can follow?

Body:
This is the sort of situation where throwing an exception on failure may be neater. If that's your API, you can then do:

try {
    a.method1();
    a.method2();
    a.method3();
    a.method4();
    a.method5();
} catch (UnsatisifedException e) {
    // Some sort of recovery logic here...
}


问:
Syntax of passing lambda
Right now, I'm working on refactoring a program that calls its parts
by polling to a more event-driven structure.

I've created sched and task classes with the sced to become a base
class of the current main loop.   The tasks will be created for each
meter so they can be called off of that instead of polling.

Each of the events main calls are a type of meter that gather info
and display it.  When the program is coming up, all enabled meters
get 'constructed' by a main-sub.  In that sub, I want to
store off the "this" pointer associated with the meter, as well
as the common name for the "action routine.

```<code>void MeterMaker::Meter_n_Task (Meter * newmeter,) {
  push(newmeter);      // handle non-timed draw events
  Task t  = new Task(now() + 0.5L);
  t.period={0,1U};
  t.work_meter = newmeter;
  t.work  = [&newmeter](){newmeter.checkevent();};<<--attempt at lambda
  t.flags = T_Repeat;
  t.enable_task();
  _xos->sched_insert(t);
}
</code>```

A sample call to it:

```<code>Meter_n_Task(new CPUMeter(_xos, "CPU "));
</code>```

've made the scheduler a base class of the main routine (that handles
the loop), and I've tried serveral variations to get the task class
to be a base of the meter class, but keep running into roadblocks.
It's alot like "whack-a-mole" -- pound in something to fix something one
place, and then a new probl pops out elsewhere.

Part of the problem, is that the sched.h file that is trying
to hold the Task Q, includes the Task header file.  The task
file Wants to refer to the most "base", Meter class.

The meter class pulls in the main class of the parent as it passes
a copy of the parent to the children so they can access the draw
routines in the parent.

Two references in the task file are for the 'this' pointer of
the meter and the meter's update sub (to be called via this).

```<code>void *this_data= NULL;
void (*this_func)() = NULL;
</code>```

Note -- I didn't really want to store these in the class, as
I wanted to use a lamdba in that meter&task routine above to
store a routine+context to be used to call the meter's action routine.

Couldn't figure out the syntax.

But am running into other syntax problems trying to store the
pointers...such as

```<code>  g++: COMPILE lsched.cc
In file included from meter.h:13:0,
                 from ltask.h:17,
                 from lsched.h:13,
                 from lsched.cc:13:
xosview.h:30:47: error: expected class-name before ‘{’ token
 class XOSView : public XWin, public Scheduler {
</code>```

Like above where it asks for a class, where the classname "Scheduler" is.
!?!?  Huh?  That IS a class name.

I keep going in circles with things that don't make sense...
Ideally I'd get the lamba to work right in the Meter_n_Task routine
at the top.  I wanted to only store 1 pointer in the 'Task'
class that was a pointer to my lambda that would have already
captured the "this" value ... but couldn't get that syntax to work
at all when I tried to start it into a var in the 'Task' class.

This project, FWIW, is my teething project on the new C++... (of course
it's simple!.. ;-))... I've made quite a bit of progress in other
areas in the code, but this lambda syntax has me stumped...its at
times like thse that I appreciate the ease of this type of operation in
perl.  Sigh.

Not sure the best way to ask for help here, as this isn't a simple
question.  But thought I'd try!... ;-)

Too bad I can't attach files to this Q.

答:
Your main problem appears to be that your design makes your classes know too much about each other, which will give you headaches with cyclic dependencies and inextricable ownership issues – especially since you're apparently using raw pointers a lot.

Your Task abstraction shouldn't know anything about Meter, or if it does, it should know about an abstract base class for your meters, and rely exclusively on that. And Meter should be completely oblivious of the Task system. This will enable you to have a task and scheduler abstraction that are either completely generic, or only depend on a well-defined interface.

You state in comments that going with an abstract base class and virtual methods would be too heavy, so a "generic" task abstraction should be the way to go. Tools to build that in C++ would either be templates, or in this case using a std::function to hide the actual type (and "nature") of the task to be run.

Here's a minimal task setup, you'll need to add your task state (enabled/disabled, next start time, etc.) in there, and adapt your scheduler to use this: (see How can I store a lambda expression as a field of a class in C++11?)

```<code>#include <functional>

struct Task
{
    Task(std::function<bool()> f): func(f) {}
    bool execute()
    {
        return func();
    }
private:
    std::function<bool()> func;
};
</code>```

You can use this utility to schedule ordinary functions, or lambdas – std::function takes care of hiding the actual type of the callable it handles for you.

Example usage:

```<code>#include <iostream>
#include <vector>

#include "task.h"

bool foo()
{
    std::cout << "Fooing" << std::endl;
    return true;
}

struct Meter
{
    Meter(std::string n): name(n) {}
    bool process_events()
    {
        std::cout << "Processing " << name << std::endl;
        return true;
    }
private:
    std::string name;
};

int main()
{
    Meter m { "CPU" };
    std::vector<Task> tasks;
    tasks.emplace_back(foo);
    tasks.emplace_back([&m](){return m.process_events();});

    for (auto& task: tasks)
        task.execute();
}
</code>```

Now this looks wrong:

```<code>class XOSView : public XWin, public Scheduler { ... };
</code>```

A window isn't a scheduler, a scheduler isn't a window, and a game isn't either of those either. That sort of construct is will give you more headaches going further than you already have. Use composition. Your game should have a UI, and have a scheduler, and a bunch of other stuff. It shouldn't be a UI and a scheduler at the same time.

```<code>_xos->sched_insert(t);
</code>```

Transform that to use a member scheduler object:

```<code>_xos->sched().insert(t);
</code>```

Then figure out whether your meters need to know about the game controller or the UI. If they need both (what I understand from your comment), pass a reference to both during construction until the time you can make a better interface between those.

Multiple inheritance is very easy to get wrong, even more so than plain inheritance (which is difficult enough already). Avoid it unless you know better.

Random advice:

Make sure you understand the difference between a class declaration and definition, and what you can do with an incomplete type (on that has been declared but not defined). See for example Does not name a type error in C++, and for more info When can I use a forward declaration?.

Don't try and bypass a type error with a void*. Understand your problem and fix it. Types are central to C++, and void* is as close as to a "non-type" as possible. The compiler can't help you with it, can't warn you about type errors when you use that.

Be more careful with your syntax. If t is a pointer t.foo() is wrong. This isn't Java. Classes and struct definitions must end with a ; (struct foo {};). Forgetting that semicolon will lead you to very bizarre compiler errors.

Don't use new, this isn't Java. Use std::shared_ptr and/or std::unique_ptr with their std::make_shared/std::make_unique helpers. This will same you a lot of memory management issues, and exception-safety gotchas.

More reading on lambdas: What is a lambda expression in C++11?, Lambda Expressions

Title: Syntax of passing lambda

Body:
Your main problem appears to be that your design makes your classes know too much about each other, which will give you headaches with cyclic dependencies and inextricable ownership issues – especially since you're apparently using raw pointers a lot.

Your Task abstraction shouldn't know anything about Meter, or if it does, it should know about an abstract base class for your meters, and rely exclusively on that. And Meter should be completely oblivious of the Task system. This will enable you to have a task and scheduler abstraction that are either completely generic, or only depend on a well-defined interface.

You state in comments that going with an abstract base class and virtual methods would be too heavy, so a "generic" task abstraction should be the way to go. Tools to build that in C++ would either be templates, or in this case using a std::function to hide the actual type (and "nature") of the task to be run.

Here's a minimal task setup, you'll need to add your task state (enabled/disabled, next start time, etc.) in there, and adapt your scheduler to use this: (see How can I store a lambda expression as a field of a class in C++11?)

#include <functional>

struct Task
{
    Task(std::function<bool()> f): func(f) {}
    bool execute()
    {
        return func();
    }
private:
    std::function<bool()> func;
};

You can use this utility to schedule ordinary functions, or lambdas – std::function takes care of hiding the actual type of the callable it handles for you.

Example usage:

#include <iostream>
#include <vector>

#include "task.h"

bool foo()
{
    std::cout << "Fooing" << std::endl;
    return true;
}

struct Meter
{
    Meter(std::string n): name(n) {}
    bool process_events()
    {
        std::cout << "Processing " << name << std::endl;
        return true;
    }
private:
    std::string name;
};

int main()
{
    Meter m { "CPU" };
    std::vector<Task> tasks;
    tasks.emplace_back(foo);
    tasks.emplace_back([&m](){return m.process_events();});

    for (auto& task: tasks)
        task.execute();
}

Now this looks wrong:

class XOSView : public XWin, public Scheduler { ... };

A window isn't a scheduler, a scheduler isn't a window, and a game isn't either of those either. That sort of construct is will give you more headaches going further than you already have. Use composition. Your game should have a UI, and have a scheduler, and a bunch of other stuff. It shouldn't be a UI and a scheduler at the same time.

_xos->sched_insert(t);

Transform that to use a member scheduler object:

_xos->sched().insert(t);

Then figure out whether your meters need to know about the game controller or the UI. If they need both (what I understand from your comment), pass a reference to both during construction until the time you can make a better interface between those.

Multiple inheritance is very easy to get wrong, even more so than plain inheritance (which is difficult enough already). Avoid it unless you know better.

Random advice:

Make sure you understand the difference between a class declaration and definition, and what you can do with an incomplete type (on that has been declared but not defined). See for example Does not name a type error in C++, and for more info When can I use a forward declaration?.

Don't try and bypass a type error with a void*. Understand your problem and fix it. Types are central to C++, and void* is as close as to a "non-type" as possible. The compiler can't help you with it, can't warn you about type errors when you use that.

Be more careful with your syntax. If t is a pointer t.foo() is wrong. This isn't Java. Classes and struct definitions must end with a ; (struct foo {};). Forgetting that semicolon will lead you to very bizarre compiler errors.

Don't use new, this isn't Java. Use std::shared_ptr and/or std::unique_ptr with their std::make_shared/std::make_unique helpers. This will same you a lot of memory management issues, and exception-safety gotchas.

More reading on lambdas: What is a lambda expression in C++11?, Lambda Expressions


答:
This is what I would do:

If you want to take into account that there is no mixed list, you can have a company having a Map of lists. (mapping type to list)

Having a map of lists as above, you also will be able to get the type without having to use the class name (still need some thing for identification of objects though). I am not saying doing this is better. I am only saying you will get what you stated above by doing this. In fact you can even rename the AbstractConstruction to ProjectInfo and use composition pattern to have it inside each Plane or Bridge object. Which design is good depends on the situation, and your situation is essentially what you would want in the application (so list more of what you want, or what you would anticipate that you want). I don't see a lot of what you want to actually come up with a good design and defend that design based on what you want.

I personally use diagram to make sure that I think in paper before I code some thing reasonably complex. For design and implementation point, if you use it as an internal diagram (for yourself and team), then it doesn't matter if you change it or not. But the moment you start handing out that diagram to other people and team, you should assume that they will make decisions based on the diagram when they work on their module. Any changes you make after that will have cascading effects.


答:
C#/.NET process conditions left to right and would stop at the first false if they were "ANDed" together, e.g.

```<code>bool success = A() && B() && C();
</code>```

should stop at B() if it returned false. Thus the following code will only output "In A" and "In B", but not "In C", because as soon as B() returns false, it stops.

```<code>using System;

public class App
{
  public static void Main()
  {
    bool success = A() && B() && C();
  }

  static bool A()
  {
    Console.WriteLine("In A");
    return true;
  }

  static bool B()
  {
    Console.WriteLine("In B");
    return false;
  }

  static bool C()
  {
    Console.WriteLine("In C");
    return true;
  }
}
</code>```

Output:

```<code>In A
In B
</code>```

Body:
C#/.NET process conditions left to right and would stop at the first false if they were "ANDed" together, e.g.

bool success = A() && B() && C();

should stop at B() if it returned false. Thus the following code will only output "In A" and "In B", but not "In C", because as soon as B() returns false, it stops.

using System;

public class App
{
  public static void Main()
  {
    bool success = A() && B() && C();
  }

  static bool A()
  {
    Console.WriteLine("In A");
    return true;
  }

  static bool B()
  {
    Console.WriteLine("In B");
    return false;
  }

  static bool C()
  {
    Console.WriteLine("In C");
    return true;
  }
}

Output:

In A
In B


问:
Why do VMs need to be "stack machines" or "register machines" etc.?
(This is an extremely newbie-ish question).

I've been studying a little about Virtual Machines.

Turns out a lot of them are designed very similarly to physical or theoretical computers.

I read that the JVM for example, is a 'stack machine'. What that means (and correct me if I'm wrong) is that it stores all of it's 'temporary memory' on a stack, and makes operations on this stack for all of it's opcodes.

For example, the source code 2 + 3 will be translated to bytecode similar to:

```<code>push 2
push 3
add
</code>```

My question is this:

JVMs are probably written using C/C++ and such. If so, why doesn't the JVM execute the following C code: 2 + 3..? I mean, why does it need a stack, or in other VMs 'registers' - like in a physical computer?

The underlying physical CPU takes care of all of this. Why don't VM writers simply execute the interpreted bytecode with 'usual' instructions in the language the VM is programmed with?

Why do VMs need to emulate hardware, when the actual hardware already does this for us?

Again, very newbie-ish questions. Thanks for your help

答:
A machine, virtual or not, needs a model of computation which describes how computation is carried out on it. By definition, as soon as it computes, it implements some model of computation. The question then is: What model should we choose for our VM? Physical machines are constrained by what can be effectively and efficiently done in hardware. But, as you note, virtual machines have no such constraints, they are defined in software using arbitrarily high level languages.

There are, in fact, virtual machines that are high-level as you describe. They are called programming languages. The C standard for example dedicates the bulk of its pages to defining a model for the so-called "C abstract machine" which describes how C programs behave, and by extension (as-if rule) how a conforming C compiler (or interpreter) should behave.

Of course, we usually don't call that a virtual machine. A VM is usually takes to mean something lower-level, closer to hardware, not intended to be directly programmed, designed to be executed efficiently. This selection bias means that something that accepts high-level composable code (like what you describe) wouldn't be considered a VM because is executes high-level code.

But to get the to the point, here are some reasons to make a VM (as in, something targeted by a bytecode compiler) register-based or the like. Stack and register machines are extremely simple. There's a sequence of instructions, some state, and semantics for each instruction (a function State -> State). No complex tree reductions, no operator precedence. Parsing, analysing and executing it is very simple, because it's a minimal language (syntactic sugar is compiled away) and designed to be machine-read rather than human-read.

In contrast, parsing even the simplest C-like languages is quite hard, and executing it requires non-local analyses like checking and propagating types, resolving overloads, maintaining a symbol table, resolving string identifiers, turning linear text into a precedence-driven AST, and so on. It builds on concepts that come natural to humans but have to be painstakingly reverse engineered by machines.

JVM bytecode, for example, is emitted by javac. It virtually never needs to be read or written by humans, so it's natural to gear it towards consumption by machines. If you optimized it for humans, the JVM would just on every startup read the code, parse it, analyze is, and then convert it into an intermediate representation resembling such a simplified machine model anyway. Might as well cut out the middle man.


问:
Finding most Important Node(s) in a Directed Graph
I have a large (≈ 20 million nodes) directed Graph with in-edges & out-edges. I want to figure out which parts of of the graph deserve the most attention. Often most of the graph is boring, or at least it is already well understood. The way I am defining "attention" is by the concept of "connectedness" i.e. How can i find the most connected node(s) in the graph?

In what follows, One can assume that nodes by themselves have no score, the edges have no weight & they are either connected or not.

This website suggest some pretty complicated procedures like n-dimensional space, Eigen Vectors, graph centrality concepts, pageRank etc. Is this problem that complex?

Can I not do a simple Breadth-First Traversal of the entire graph where at each node I figure out a way to find the number of in-edges. The node with most in-edges is the most important node in the graph. Am I missing something here?

答:
Algorithms typically try to optimize one thing or the other. Even NP problems are solvable, except that they require all possible combinations to be tried, which makes them computationally expensive. In the problem you are trying to solve, the question is what is it that you are trying to optimize: time, memory, or something else?

Given that it is 2 million nodes, it is unclear whether they are all read in memory at once, or if they reside on disk and thus memory management and minimization of I/O might be a factor.

Assuming that your entire graph is in memory, the question is who creates the graph? Can you keep a count of the edges for nodes in the graph during creation (or when reading from disk) and keep them in an ordered list?

The other thing is that sometimes a graph can have two or more completely disconnected parts in practical life (I have had to deal with one such graph). In such cases, I have found it more useful to iterate through all the nodes (no matter breadth first or depth first), and then count all the edges on every node -- in most cases, modern languages will keep all the edges in some sort of a collection and you will already have a property or method to get the length or count on that collection, thus saving iteration over all the edges).

The complexity for both these solutions can be O(n log n) where n is the no. of nodes.

Although time and memory is often of concern, but sometimes simplicity is more important than those attributes, so I keep that in my equation too. In many situations, such as this, I would consider complexity of implementation as yet another factor in my pro/con list before deciding what to implement.


答:
This answer focuses on the JVM, but in fact it applies to any VM.

Why do VMs need to emulate hardware, when the actual hardware already does this for us?

They don't, but it makes the VM much simpler and portable: A VM that emulates hardware can use the same computational model than any hardware CPU.

The JVM in particular was built with portability in mind, in fact it was built so it could even be implemented in hardware (it may be hard to believe today, but the origin of Java was in the embedded world - specifically, controllers for interactive television).

If you have a goal like this, it is desirable that the VM operates as close to a physical machine as possible, because translating to actual machine code becomes easier and thus faster. Once you have the opcodes of the VM, in theory, all you have to do is translate to opcodes of the CPU the program actually runs on. In practice it is not exactly that simple.

I mean, why does it need a stack, or in other VMs 'registers' - like in a physical computer?

Using a stack based virtual machine model has the advantage that it can be easily transferred to both register and stack machines, while the opposite is not necessarily true. A register-based VM would need to  make assumptions about the number of registers, the size of the registers etc. With a stack machine, no such assumptions are necessary.

The underlying physical CPU takes care of all of this. Why don't VM writers simply execute the interpreted bytecode with 'usual' instructions in the language the VM is programmed with?

Well, that's what such VMs do, they interpret bytecode. Even the JVM actually does that, at least before JIT (just-in-time) kicks in: it interprets the byte codes and executes the statements in the language the JVM was written in (typically C or C++, but there is even one written in JavaScript, Doppio). Note, however, that even such statements were translated to machine code by a compiler and actually look very similar to what the Java compiler produces - namely, they use registers and the stack to perform their work. Note the use of "interpreted" v.s. "compiled" languages becomes somewhat blurry at this point.

Title: Why do VMs need to be "stack machines" or "register machines" etc.?

Body:
(This is an extremely newbie-ish question).

I've been studying a little about Virtual Machines.

Turns out a lot of them are designed very similarly to physical or theoretical computers.

I read that the JVM for example, is a 'stack machine'. What that means (and correct me if I'm wrong) is that it stores all of it's 'temporary memory' on a stack, and makes operations on this stack for all of it's opcodes.

For example, the source code 2 + 3 will be translated to bytecode similar to:

```<code>push 2
push 3
add
</code>```

My question is this:

JVMs are probably written using C/C++ and such. If so, why doesn't the JVM execute the following C code: 2 + 3..? I mean, why does it need a stack, or in other VMs 'registers' - like in a physical computer?

The underlying physical CPU takes care of all of this. Why don't VM writers simply execute the interpreted bytecode with 'usual' instructions in the language the VM is programmed with?

Why do VMs need to emulate hardware, when the actual hardware already does this for us?

Again, very newbie-ish questions. Thanks for your help


问:
Dealing with state problems in functional programming
I've learned how to program primarily from an OOP standpoint (like most of us, I'm sure), but I've spent a lot of time trying to learn how to solve problems the functional way. I have a good grasp on how to solve calculational problems with FP, but when it comes to more complicated problems I always find myself reverting to needing mutable objects. For example, if I'm writing a particle simulator, I will want particle "objects" with a mutable position to update. How are inherently "stateful" problems typically solved using functional programming techniques?</p>

答:
Functional programs handle state very well, but require a different way of looking at it.  For your position example, one thing to consider is having your position be a function of time instead of a fixed value.  This works well for particles following a fixed mathematical path, but you require a different strategy for handling a change in the path, such as after a collision.

The basic strategy here is you create functions that take in a state and return the new state.  So a particle simulator would be a function that takes a Set of particles as input and returns a new Set of particles after a time step.  Then you just repeatedly call that function with its input set to its previous result.


问:
Your thoughts on Best Practices for Scientific Computing?
A recent paper by Wilson et al (2014) pointed out 24 Best Practices for scientific programming. It's worth to have a look. I would like to hear opinions about these points from experienced programmers in scientific data analysis. The authors' advices sound good, but do you think these advices are helpful and practical? As they admit, introducing all of them may take significant time and effort. For example, putting assertions and deploying unit tests surely need extra coding. Nevertheless, do you think scientists (such as biologists) who had no training in coding should generally follow these? If some of them are too much, to what point should we go and stop depending on what?

Wilson G, Aruliah DA, Brown CT, Chue Hong NP, Davis M, Guy RT, Haddock SHD, Huff KD, Mitchell IM, Plumbley MD, Waugh B, White EP, Wilson P (2014) Best Practices for Scientific Computing. PLoS Biol 12:e1001745.

http://www.plosbiology.org/article/info%3Adoi%2F10.1371%2Fjournal.pbio.1001745

Box 1. Summary of Best Practices

Write programs for people, not computers.

(a) A program should not require its readers to hold more than a handful of facts in memory at once.

(b) Make names consistent, distinctive, and meaningful.

(c) Make code style and formatting consistent.

Let the computer do the work.

(a) Make the computer repeat tasks.

(b) Save recent commands in a file for re-use.

(c) Use a build tool to automate workflows.

Make incremental changes.

(a) Work in small steps with frequent feedback and course correction.

(b) Use a version control system.

(c) Put everything that has been created manually in version control.

Don’t repeat yourself (or others).

(a) Every piece of data must have a single authoritative representation in the system.

(b) Modularize code rather than copying and pasting.

(c) Re-use code instead of rewriting it.

Plan for mistakes.

(a) Add assertions to programs to check their operation.

(b) Use an off-the-shelf unit testing library.

(c) Turn bugs into test cases.

(d) Use a symbolic debugger.

Optimize software only after it works correctly.

(a) Use a profiler to identify bottlenecks.

(b) Write code in the highest-level language possible.

Document design and purpose, not mechanics.

(a) Document interfaces and reasons, not implementations.

(b) Refactor code in preference to explaining how it works.

(c) Embed the documentation for a piece of software in that software.

Collaborate.

(a) Use pre-merge code reviews.

(b) Use pair programming when bringing someone new up to speed and when tackling
particularly tricky problems.

(c) Use an issue tracking tool.

I'm relatively new to serious programming for scientific data analysis. When I tried to write code for pilot analyses of some of my data last year, I encountered tremendous amount of bugs both in my code and data. Bugs and errors had been around me all the time, but this time it was somewhat overwhelming. I managed to crunch the numbers at last, but I thought I couldn't put up with this mess any longer. Some actions must be taken.

Without a sophisticated guide like the article above, I started to adopt "defensive style" of programming since then. A book titled "The Art of Readable Code" helped me a lot. I deployed meticulous input validations and/or assertions for every function, renamed a lot of variables and functions for better readability, and extracted many bits as reusable functions. Recently, I introduced Git and SourceTree for version control.

At the moment, because my co-workers are much more reluctant about these issues, the collaboration practices (8a,b,c) have not been introduced. Actually, as the authors admitted, because all of these practices take some amount of time and effort to introduce, it may be generally hard to persuade your reluctant collaborators to comply them.

I think I'm asking your opinions because I still suffer from many bugs despite all my effort on many of these practices. Bug fix may be, or should be, faster than before, but I couldn't really measure the improvement. Moreover, much of my time has been invested on defence, meaning that I haven't actually done much data analysis (offence) these days. Where is the point I should stop at in terms of productivity?

I've already deployed: 1a,b,c, 2a, 3a,b,c, 4b,c, 5a,d, 6a,b, 7a,7b

I'm about to have a go at: 5b,c

Not yet: 2b,c, 4a, 7c, 8a,b,c

(I could not really see the advantage of using GNU make (2c) for my purpose. Could anyone tell me how it helps my work with MATLAB?)

答:
Most if not all of the things the article you mentioned are known by developers.
Many of them are taught at school, many will be realized when one goes do real work. I am kind of surprised when you said your collaborators won't comply.

And if you worry about making bugs too much, then constrain yourself to just a few domains. You will become so fluent to the point almost everything you need you write, you have already encountered before. Much less chance you create bug this way.

What do you mean by bugs being overwhelming? I might be in the same situation as you are and I don't even know. In the past, I have been working for several years, I have seen people making bugs to the point that I was so confident that 'everybody does'. The key is testing your code often and comprehensively.

Since you mentioned 'defensive programming', if I understand it right, it will be hard for bug-making person like you so professed, to be good. Defensive programming is making code so bug-free it can even deal with the cases outside or bordering the specification. It's bug-free of bug-free.


答:
When writing large and moderately large applications, I have often found it useful to differentiate between the sections of the application that are stateful and those that are stateless.

The classes/data structures in the stateful section store the data of the application and the functions in this section work with implicit knowledge of the data of the application.

The classes/data structures/functions in the stateless section are there to support the purely algorithmic aspects of the application. They don't have implicit knowledge of the data of the application. They work in a purely functional nature. The stateful parts of the application may experience change of state as a side effect of running functions in the stateless section of the application.

The hardest part is figuring out which classes/functions to put in the stateless section and which classes/functions to put in the stateful section, and having the discipline to put them in separate files/libraries.

Title: Dealing with state problems in functional programming

Body: I've learned how to program primarily from an OOP standpoint (like most of us, I'm sure), but I've spent a lot of time trying to learn how to solve problems the functional way. I have a good grasp on how to solve calculational problems with FP, but when it comes to more complicated problems I always find myself reverting to needing mutable objects. For example, if I'm writing a particle simulator, I will want particle "objects" with a mutable position to update. How are inherently "stateful" problems typically solved using functional programming techniques?</p>


问:
Is it necessary to start variable from zero (var i = 0 ) of ' for loop '?
Is it necessary to start variable from zero (var  i = 0) of any looping ?  When should  I use var i = 1; and when var i =0;?

答: You can start a loop at whatever you want. The reason you see loops starting at zero often, is because they are looping through an array. Since the first item in an array is at index '0', it makes sense to start looping from 0 to access every item in an array.</p>


答:
You should use i = 0 in situations where iterating starting at zero would be natural, as previously stated this could include array indexing or similar. Personally I would say I use this style at least 90% of the time, as when modelling problems in the computer we mold them to use built in data structures, which usually start at 0. Our minds become use to working in this style.

Starting at i = 1 is more natural for modeling many problems while designing algorithms. For example, if you are given a problem such as person 1 is x years old, person 2 is y years old, and so on, indexing using the given numbers may make it easier to give an answer if asked something such as who is the youngest person in the list. Experience and experimentation will teach you if this is worthwhile, in my experience, this can be helpful in things such as programming competitions (like the ICPC), where algorithms must be developed quickly with not much time for debugging, and the algorithms can be very complex, so the clarity is important.

In other words it may be beneficial to waste this first index if it adds clarity, however experienced programmers quickly learn to understand both styles.

However, if you start at zero, remember to be aware that the arrays still start at zero, and you will need an n + 1 size array to represent n elements if you use indexing starting at 1.

Also be aware of your conditional in the for loop.

for (int i = 0; i < 10; i++) - Will loop 10 times

for (int i = 1; i <= 10; i++) - Will loop 10 times

It is basic, but a common source of errors that may be hard to track down, especially for beginning programmers.

Title: Is it necessary to start variable from zero (var i = 0 ) of ' for loop '?

Body: Is it necessary to start variable from zero (var  i = 0) of any looping ?  When should  I use var i = 1; and when var i =0;?


问:
Java best practice Interface - subclasses and constants
In the case where a couple of classes implements an interface, and those classes have a couple of constants in common (but no functions), were should I put this constant ?

I've had this problem a couple of times.

I have this interface : DataFromSensors that I use to hide the implementations of several sub classes like DataFromHeartRateMonitor DataFromGps etc...

For some reason, those classes uses the same constants. And there's nowere else in the code were it is used.

My question is, were should I put those constants ?

Not in the interface, because it has nothing to do with my API

Not in a static Constants class, because I'm trying to avoid those

Not in a common abstract class, that would stand between the interface and the subclasses, because I have no functions in common, only a couple of constants (TIMEOUT_DURATION, UUID, those kind of things)

I've read best practice for constants and interface to define constants but they don't really answer my question.

Thanks !

答:
The other thing you can do is specify it in a config resource that you include with a jar. Constants are kinda funny: You think they never need to change until they do and then you have to recompile to code to change your TIMEOUT_VALUE.

If you put it in the jar with the rest of the resources then it is, for all intents and purposes, constant. However, it's not code and, in the off chance you have a problem, you can modify it in the field.

Just an idea. Putting statics in the interface is only a problem if it's the ONLY thing that interface does. Somethings in programming just are ugly and you have to make some tradeoffs.


问:
Session serialization in JavaEE environment
Please consider the following scenario:

We are working on a JavaEE project for which the scalability starts to become an issue. Up until now, we were able to scale up but this is no longer an option. Therefore we need to consider scaling out and preparing the App for a clustered environment.

Our main concern right now is serializing the user sessions.
Sadly, we did not consider from the beginning the issue and we are encountering the following excetion:

```<code>java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: org.apache.catalina.session.StandardSessionFacade
</code>```

I did some research and this exception is thrown because there are objects stored on the session which does not implement the Serializable interface. Considering that all over the app there are quite a few custom objects which are stored on the session without implementing this interface, it would require a lot of tedious work and dedication to fix all these classes declaration.

We will fix all this declarations but the main concern is that, in the future, there may be a developer which will add a non Serializable object on the session and break the session serialization & replication over multiple nodes.

As a quick overview of the project, we are developing using a home grown framework based on Struts 1 with the Servlet 3.0 API. This means that at this point, we are using the standard session.getAttribute() and session.setAttribute() to work with the session and the session handling is scattered all over the code base.

Besides updating the classes of the objects stored on session and making sure that they implement the Serializable interface, what other measures of precaution should we take in order to ensure a reliable Session replication capability on the Application layer?
I know it is a little bit late to consider this but what would be the best practice in this case? Furthermore, are there any other issues we should consider regarding this transition?

Thank you in advance!

答:
If you are considering only a scaled out, clustered environment, with replicated Sessions, then you don't have a workaround. All of your objects must be Serializable.

But if your application and Java EE architecture allows you to do a scaled out "clustered" environment without replicated Sessions, then you are fine. The only thing you will lose here is the ability to keep a user logged in and redirected to another server when the one he was interacting with was shutdown for some reason. This user may be redirected to another server, but he/she will have to sign in again and if your application is not smart enough, he/she will have to start whatever they were doing, all over again.

If you really cannot make sure your objects are Serializable, consider a load balance for "unclustered" Java EE web containers (EJBs may continue to be clustered and may give you greater scalability) with sticky-session and non-replicated HttpSession.


问:
What are the differences between a while loop and a for loop?
What are the differences between a while loop and a for loop? It seems to me that they are the same.</p>

答:
The while loop is usually used when you need to repeat something until a given condition is true:

```<code>inputInvalid = true;
while(inputInvalid)
{
    //ask user for input
    invalidInput = checkValidInput();
}
</code>```

On the other hand, the for loop is usually used when you need to iterate a given number of times:

```<code>for(var i = 0; i < 100; i++)
{
    ...//do something for a 100 times.
}
</code>```

You can use them interchangeably if you like:

```<code>inputInvalid = true;
for(;;)
{
    if(!inputInvalid)
    {
        break;
    }
    //ask user for input
    invalidInput = checkValidInput();
}
</code>```

Or

```<code>inputInvalid = true;
for(;inputInvalid;)
{
    //ask user for input
    invalidInput = checkValidInput();
}
</code>```

And:

```<code>var i = 0;
while(i < 100)
{
    //do your logic here
    i++;
}
</code>```

Body:
The while loop is usually used when you need to repeat something until a given condition is true:

inputInvalid = true;
while(inputInvalid)
{
    //ask user for input
    invalidInput = checkValidInput();
}

On the other hand, the for loop is usually used when you need to iterate a given number of times:

for(var i = 0; i < 100; i++)
{
    ...//do something for a 100 times.
}

You can use them interchangeably if you like:

inputInvalid = true;
for(;;)
{
    if(!inputInvalid)
    {
        break;
    }
    //ask user for input
    invalidInput = checkValidInput();
}

Or

inputInvalid = true;
for(;inputInvalid;)
{
    //ask user for input
    invalidInput = checkValidInput();
}

And:

var i = 0;
while(i < 100)
{
    //do your logic here
    i++;
}


答:
Why not in a static Constant class?
I have seen popular framework like SWT putting lot of constants in a constant class if the usage is widespread.
And even in the case where the usage is not widespread, how is it a bad idea.
A constant is not much of an implementation detail.

Please correct me if I am wrong.

Title: Java best practice Interface - subclasses and constants

Body:
In the case where a couple of classes implements an interface, and those classes have a couple of constants in common (but no functions), were should I put this constant ?

I've had this problem a couple of times.

I have this interface : DataFromSensors that I use to hide the implementations of several sub classes like DataFromHeartRateMonitor DataFromGps etc...

For some reason, those classes uses the same constants. And there's nowere else in the code were it is used.

My question is, were should I put those constants ?

Not in the interface, because it has nothing to do with my API

Not in a static Constants class, because I'm trying to avoid those

Not in a common abstract class, that would stand between the interface and the subclasses, because I have no functions in common, only a couple of constants (TIMEOUT_DURATION, UUID, those kind of things)

I've read best practice for constants and interface to define constants but they don't really answer my question.

Thanks !


问:
How to prevent deep indentations?
What steps and measures can I take to prevent deep indentations in my code?</p>

答:
Break nested components (especially repeated ones) out into separate functions (this is easier if your language supports closures) or replace a series of nested loops with a recursion.

Also, indent two spaces instead of four.

Title: How to prevent deep indentations?


问:
What revision control has the best merging engine?
When it comes to merging, each control version has it's engine to do it. Conflicts are unavoidable but the question is - which revision control has best AI to avoid conflict.

Is it possible to measure such thing?

More specifically, we are thinking to move to GIT cause it has nice hype and rumour that handles conflict better...

Any comment is appreciated...

答:
The perfect merge engine would understand the semantics of the file being merged: so it parses and understands the source code. I'm yet to see such merge engine/version control...

Most merge tools merge files as text. So I would never rely on them blindly, it's always good idea to review the changes before committing it to your branch.

We are using Perforce, which doesn't merge automatically. Whenever the source file changes relative to the common base, it will say the target file needs resolve even if there is no conflict. So I open the merge tool just to quickly step thought the hunks to check if they fit (and get a rough picture what other peers are doing), most often they will fit and accept the result.

I also subscribed to the change notifications of the mainline so I merge the changes to my branch as early as possible so I can avoid problems later.


问:
Commenting/In-Code Documentation Styles
This might be a stupid question, but it's been in the back of my head for a while and I can't find a decent answer anywhere else.

I have a teacher who says we should explicitly list each parameter with a description, even if there's only one.  This leads to a lot of repetition:

```<code>double MyFunction(const int MyParam);
// Function: MyFunction
// Summary: Does stuff with MyParam.
// Input: int MyParam - The number to do stuff with.
// Output: MyParam with stuff done to it.
</code>```

When writing in-code documentation, how detailed are you?

答:
If it's in the service of Doc generation then verbose comments (although irritating) are probably a good thing.  Although you have to make it a team goal to stay on top of comments and keep them up to date.

If it's just the commenting style I would have issue with it.  Excessive comments can hurt code just as much as help.  I can't count the number of time I've come across comments in the code that were out of date and as a result misleading.  I usually ignore comments now and focus on reading the code and the tests of the code to understand what it does and what is the intent.

I would rather have clear concise un-commented code.  Give me some tests with descriptive assertions or methods and I'm happy and informed.

Title: Commenting/In-Code Documentation Styles


问:
Use a template to get alternate behaviour?
Is this a bad practice?

```<code>const int sId(int const id);

// true/false it doesn't matter
template<bool i>
const int sId(int const id) {
    return this->id = id;
}
</code>```

```<code>const int MCard::sId(int const id){
    MCard card = *this;

    this->id = id;

    this->onChange.fire(EventArgs<MCard&, MCard&>(*this, card));

    return this->id;
}
</code>```

```<code>myCard.sId(9);

myCard.sId<true>(8);
</code>```

As you can see, my goal is to be able to have an alternative behaviour for sId.

I know I could use a second parameter to the function and use a if, but this feels more fun (imo) and might prevent branch prediction (I'm no expert in that field).

So, is it a valid practice, and/or is there a better approach?

答:
Actually, it seems you are just overcomplicating things, which might obfuscate your code. This

```<code>sId
</code>```

and this

```<code>sId<true>
</code>```

are just two different functions. And the standard way of implementing two different functions (with the same signature) is simply to use two different function names, without the template hoodoo voodoo, like sIdWithoutEvent and sId (assumed the latter one is  calling the event).

Body:
Actually, it seems you are just overcomplicating things, which might obfuscate your code. This

sId

and this

sId<true>

are just two different functions. And the standard way of implementing two different functions (with the same signature) is simply to use two different function names, without the template hoodoo voodoo, like sIdWithoutEvent and sId (assumed the latter one is  calling the event).


答:
Why do VMs need to be “stack machines” or “register machines” etc.?

They do not. If you need a virtual machine, it may be anything.

The existing virtual machines have appeared as solutions to the situations like: A really brilliant idea has come to my head, I have invented a new programming language! But I have to generate code. (What a boring task!) But I do not want to generate i8086 code because it's ugly, and I do not want to generate 68k code because everyone else is using Intel. There's also VAX, but I don't have any VAX, neither a computer nor a VAX book. Therefore I will generate code for some processor that does not physically exist and implement that processor in software. The spec of that VM will make a chapter in my thesis. In theory, it will be possible to compile it to native code of any processor, but that will not be me.

On the other hand, the notation like "2+3" probably will not be used by VMs in foreseeable future because it implies doing a lot of transformation before something may be executed.


问:
What metadada to save and whether to include it inside the binary file?
I'm wondering if there are any general guidelines or best practices regarding when to split data into a metadata format, as oppose to directly embedding it within the data. (Specific example below).

My understanding of metadata is that it describes data (without the need to actually look at the data), allowing for data to be quickly search/filtered for easy access.

Let's take for example a simple 3D model format. The actual data file is itself a binary file containing vertices and colors. Things like creation date, modified data and author name would be things that describe the binary data, so I would say these belong as metadata (outside of the binary file).

But the following questions arise:

What if the application had no need to search or filter by these fields?

Would it be acceptable to embed these fields directly into the binary data itself?

Could they be duplicated in both the binary data and the meta data, or would this be considered bad practice?

What about more ambiguous fields such as the model name, which could be considered part of the data itself, but also as data describing the binary data?

How do you decide which data to embed in the actual binary file, as opposed to separating into a more flexible metadata format?

Thanks!

答:
You have the distinction between data and metadata spot on.

Two aspects come to mind for this.  One is programming and the other is manageability.  On the programming side I agree that "one file, one data" has its appeal.  You can write a nice, clean handler for the bindary data without cluttering it with messy meta-shenanigans.  For manageability, anyone who uses the binary is going to want to know its provenance, quality, timeliness etc.  Separating these is a problem wating to happen.  One day you copy the binary and not the meta and two weeks later you can't remember what is which or where it came from.

On balance I opt for an all-in-one-file approach when I have the choice.  The file handler can be a wrapper around the binary-parsing and meta-parsing bits.  If an application never calls for the meta then the relevant part of code never gets called.  The size of metadata is rarely going to be a concern compared to the binary portion, either.


问:
Fiscal quarter vs calendar quarter
I'm building a Date/Time class with a "configurable quarter" system as follows.

User specifies which month the quarter starts at (config)

Set of functions to deal with quarters (next quarter, prev quarter, etc)

All quarter functions respect the config

Now this class is primarily to be used for fiscal quarter calculations. So assuming I have this class with a configurable "quarter" system, would I need another parallel set of functions for calendar quarters too? What are the applications for calendar quarters anyways?

By calendar quarters I mean where Q1 is Jan-Mar, and Q4 is Oct-Dec.

By fiscal quarters I mean whatever standard your Country uses (in India Q1 starts in April)

答:
I don't know about the business rules, but your app could default to calendar quarters or if someone wants Calendar Quarters then they start with January. With one exception, I've always worked at companies on a calendar quarter for internal operations and customer billing/reporting, but the accounting may not match. Not sure why it matters in your app if someone starts with Jan or Feb., you have to do the math.

How are you going to handle making a change to the configuration after the system is up and running for a customer and they have historical data? Doesn't happen often, but they could make a company/corporation structural change.

Title: Fiscal quarter vs calendar quarter


答:
Indexing at 1 will often feel more natural and intuitive as you think of the first element as element "1" so you will want to create an array that is one-based.

Over time you will find that most data structures, methods and programming routines that you work with treat arrays as being zero-based.

I found, over time that making zero based arrays work for my "1 equals 1" 1 based mental model meant that I was frequently doing thing like index+1 or index-1 or otherwise messing around with it to make it work with a zero based array.


问:
Can decoupling hurt maintainability in certain situations?
Can the fact that the business logic is mapped to interfaces instead of implementations actually hinder the maintenance of the application in certain situations?

A naive example with the Java's Hibernate framework would be, that for example (provided I don't have the whole code-base in my head, the project structure is a mess and classes are named with arbitrary names) if I wish to see what's going on in a certain DAO, to see if it actually is doing what it's supposed to do, then instead of traversing backwards up the tree from the point where the data service is invoked (where the tree will end in an interface with no implementation details whatsoever apart from the signature) I have to for example go and look for a configuration XML file to see which class is mapped to said interface as the implementation before being able to access the actual implementation details.

Are there any situations where having loose coupling can actually hurt maintainability?

答:
Developing code to an interface is, as far as I know recommended since it allows you to make changes without having to rewrite and/or refactor your code.

That being said, I do believe that having loose coupling can to a certain degree hurt maintainability. The main problem that I see is that people can loose track of what where they doing in the previous methods, which can cause headaches when debugging problems, an overly simplified example would be:

```<code>public class Login
{
     public void verifyLogin(...)
     {
         if(VerifyUtlis.isUserValid(...))
         {
             //redirect to home
         }
         //redirect to somewhere else
     }
}

public class FTPHandler
{
     public void verifyLogin(...)
     {
         if(VerifyUtlis.isUserValid(...))
         {
             //redirect to home
         }
         //redirect to somewhere else
     }
}

public class VerifyUtils
{
     public boolean isUserValid(...)
     {
         ...
     }
}
</code>```

When debugging code in VerufyUtils a developer (maybe someone who has just joined) might find it hard to keep track from where he/she got from (admittedly, the above is over simplified, but I hope you understand how things get when you have 100 classes calling each other).

If the developer can have a hard time in tracking what method is used where, any changes he/she makes can potentially make the application unstable. So if you are going for a loosely couple approach, make sure that the code you have and any changes you made are documented. No need to have thousands of words, but usually explaining why things are the way they are (as opposed to writing comments to explain what the code is doing) helps in keeping loosely coupled systems in scope.

Body:
Developing code to an interface is, as far as I know recommended since it allows you to make changes without having to rewrite and/or refactor your code.

That being said, I do believe that having loose coupling can to a certain degree hurt maintainability. The main problem that I see is that people can loose track of what where they doing in the previous methods, which can cause headaches when debugging problems, an overly simplified example would be:

public class Login
{
     public void verifyLogin(...)
     {
         if(VerifyUtlis.isUserValid(...))
         {
             //redirect to home
         }
         //redirect to somewhere else
     }
}

public class FTPHandler
{
     public void verifyLogin(...)
     {
         if(VerifyUtlis.isUserValid(...))
         {
             //redirect to home
         }
         //redirect to somewhere else
     }
}

public class VerifyUtils
{
     public boolean isUserValid(...)
     {
         ...
     }
}

When debugging code in VerufyUtils a developer (maybe someone who has just joined) might find it hard to keep track from where he/she got from (admittedly, the above is over simplified, but I hope you understand how things get when you have 100 classes calling each other).

If the developer can have a hard time in tracking what method is used where, any changes he/she makes can potentially make the application unstable. So if you are going for a loosely couple approach, make sure that the code you have and any changes you made are documented. No need to have thousands of words, but usually explaining why things are the way they are (as opposed to writing comments to explain what the code is doing) helps in keeping loosely coupled systems in scope.


问:
Dynamic Query Generation : suggestion for better approaches
I am currently designing a functionality in my Web Application where the verified user of the application can execute queries which he wishes to from the predefined set of queries with where clause varying as per user's choice.

For example,Table ABC contains the following Template query called SecretReport

"Select def as FOO, ghi as BAR from MNO where  "

SecretReport can have parameters XYZ, ILP. Again XYZ can have values as 1,2 and ILP can have 3,4

so if the user chooses ILP=3, he will get the result of the following query on his screen
 "Select def as FOO, ghi as BAR from MNO where ILP=3"

Again the user is allowed permutations of XYZ / ILP

My initial thought is that User will be shown a list of Report names and each report will have parameters and corresponding values. But this approach although technically simple does not appear intuitive.

I would like to extend this functionality to a more generic level. Such that the user can choose a table and query based on his requirements. Of course we do not want the end user to take complete control of DB. But only tables and fields that are relevant to him. At present we are defining what is relevant in the code. But I want the Admin to take over this functionality such that he can decide what is relevant and expose the same to the user. On user's side it should be intuitive what is available to him and what queries he can form.

Please share your thoughts what is the most user friendly way to provide this feature to the end user.

答:
My initial thought is that User will be shown a list of Report names and each report will have parameters and corresponding values. But this approach although technically simple does not appear intuitive.

I disagree.

If your reports aren't couched in terms the Users understand (i.e. intuitive), then who did you write them for?

You create a set of reports (with "titles" that mean things to the Users).

Then you add parameters to those reports, again with User-meaningful "descriptions".  It's rare - but not unheard of - for Users to "talk in codes" so favour descriptions over hard-coded values (e.g. what do "1" and "3" mean?)

Buried inside your application, all those "titles" and "descriptions" get converted into database terminology - tables, [joins?], fields, conditions, etc., so that you can build some SQL and actually run it on the Users' behalf, but the Users don't get to see any of that.  Ever.  Not even if the generated SQL is syntactically incorrect (log the "real" error to a file, show the Users something trite but apologetic).

Please note: I keep saying "Users" - plural.

You will have different User communities, with different levels of access to different sets of data.  Make sure that your application can handle this and that your "Administrators" understand it as well.
"Data Protection" legislation varies widely but the basic premise of "don't let anyone see something they're not allowed to" holds true pretty much everywhere and can cost you a lot of money if you get it wrong.

ContentLicense: CC BY-SA 4.0


答: In your shoes, I would just create an app for a "fiscal" quarter. A calendar quarter is just a special case of a fiscal quarter, meaning that all calendar quarters can be defined as fiscal quarters. But the reverse is not true.</p>

Title: Fiscal quarter vs calendar quarter

Body:
I'm building a Date/Time class with a "configurable quarter" system as follows.

User specifies which month the quarter starts at (config)

Set of functions to deal with quarters (next quarter, prev quarter, etc)

All quarter functions respect the config

Now this class is primarily to be used for fiscal quarter calculations. So assuming I have this class with a configurable "quarter" system, would I need another parallel set of functions for calendar quarters too? What are the applications for calendar quarters anyways?

By calendar quarters I mean where Q1 is Jan-Mar, and Q4 is Oct-Dec.

By fiscal quarters I mean whatever standard your Country uses (in India Q1 starts in April)