答:
Your particular example strongly suggests HAS-A relationship, thus, composition, because FooFetcher is not a Session.

BTW, Python does have multiple inheritance, and sometimes functionality can be added using mix-ins.

For example, you may have Sessioning and add it as a mix-in:

```<code> class FooFetcher(BaseFetcher, Sessioning):
     ...
</code>```

Returning to your second example, I think, session should be explicit:

```<code>class FooFetcher(object):
    def __init__(self, session):
        self.session = session
</code>```

This way it's easier to test and maintain the code.

Title: Python -- when should a class have-a rather than be-a?

Body:
This is related to "Extends is evil" vs. OCP? but separate because the idea of "implement the interface" doesn't exist in Python.

I'm writing a class to pull some data off a webpage. It's going to need to hold on to a cookie for authentication, so I'm going to use a requests.Session object in some form. I'm never sure how to approach this -- what's the appropriate choice here?

```<code>class FooFetcher(requests.Session):
    def __init__(self):
        super.__init__()
</code>```

or

```<code>class FooFetcher(object):
    def __init__(self):
        self.session = requests.Session()
</code>```

?

The former seems to end up with FooFetcher having way more public methods than it needs to. The latter looks like it might be unnecessarily convoluted, since pretty much every method of FooFetcher is going to involve a call to a method of that Session object, plus maybe some parsing of JSON that it finds.

Body:
Your particular example strongly suggests HAS-A relationship, thus, composition, because FooFetcher is not a Session.

BTW, Python does have multiple inheritance, and sometimes functionality can be added using mix-ins.

For example, you may have Sessioning and add it as a mix-in:

 class FooFetcher(BaseFetcher, Sessioning):
     ...

Returning to your second example, I think, session should be explicit:

class FooFetcher(object):
    def __init__(self, session):
        self.session = session

This way it's easier to test and maintain the code.


问:
How to properly structure a collection of immutable constants
I'm in the design stages of a program that based upon input received, would select a particular category, and action within that category. The category, the action within in, and the value(s) related to that action are all immutable values, along with the relationship between category and action.

Normally I'd just assign it all into a multidimensional array or collection, but that strikes me as both messy and unnecessarily complex to search and sort. Constants don't allow me the luxury of defining relationships between them (aka you can't have constant A bound to subConstant B for example), and being a desktop app, having a user setting up a database server isn't appealing. Was thinking of having everything in xml files, but core rules of the application isn't appealing due to being able to easily edit, and hence change the primary functionality of the program that I wouldn't wish to be editable.

Anyone ever ran into something like this, and if so, what was the setup that you used for your solution?

EDIT: Let me see if I can explain this better with an example. Say I have the following structure

```<code>category A
  -- action AB
      -- result 1
      -- result 2
      -- result 3
      -- result 4
      -- result 5
      -- result 6
</code>```

where if I selected category A, and action AB, a one dice roll would select the result to be returned. The category, action, and result will never change both in name and in relationship (action AB will always be bound to category A, results within action AB will be bound to action AB, and the result contents will never change)

EDIT: No network usage would be expected for this application, as it was asked in one of the responses.

答:
Create classes or interfaces for categories, actions, and results.  Start with a list for categories.  (You'll need random access, so this should perhaps be a dictionary/map, though if you can ID them with integers an ArrayList might do.)  Each Category will have a similar list of Action instances, and each Action will have a list of Result instances.  (Actually, if these are interfaces rather than instances, each instance can have completely different code from every other, as best suits its purpose, and the lists can be different, or even nonexistent.  You might choose results with an IF statement in one Action and an array in another.)

Now you create a new Result by creating a new instance of a subclass of the desired class, which implements the necessary interface.  (For simple cases you can skip a step or two.)  You create an Action similarly, then add Results to it.  And a Category the same, and add Actions to it.

The key point here is the flexiblity.  You can do just about anything and everything.  Arrays in one place, switch statements in another, if-elses somewhere else.  Also string-based dictionaries, etc., etc.  While each Category looks and works, to outsiders, identical to every other, internally they can be completely different.

(Of course, for the simplest cases a simple nested if-else construct might do the whole job just as well.)

ContentLicense: CC BY-SA 3.0


问:
Is it okay to check in changes to import statement on opensource projects on a commit?
There are some guidelines out there (eg scala guidelines) and I'm wondering if it's okay to do some tidying up when committing other changes or if the commits should be more focused and to the point?

Eg - remove unused, reorder per style guide.

It might make it harder to read the pull request - but it will improve the project quality at least a little.
What's your general rule of thumb? I'm not sure if I'm breaking unspoken taboos.

答:
The rule of thumb is it's okay if you already are submitting another change in that file, perhaps even encouraged.  The reviewer will tell you if their personal preferences are different.

If you want to do cleanup only on files, that usually should go into its own pull request, and like other changes, you probably want to ask before undertaking it.


问:
Why don't RDBMSes return joined tables in a nested format?
For example, say I want to fetch a User and all of his phone numbers and email addresses. The phone numbers and emails are stored in separate tables, One user to many phones/emails. I can do this quite easily:

```<code>SELECT * FROM users user
    LEFT JOIN emails email ON email.user_id=user.id
    LEFT JOIN phones phone ON phone.user_id=user.id
</code>```

The problem* with this is that it's returning the user's name, DOB, favorite color, and all the other information stored in the user table over-and-over again for each record (users×emails×phones records), presumably eating up bandwidth and slowing down the results.

Wouldn't it be nicer if it returned a  single row for each user, and within that record there was a list of emails and a list of phones? It would make the data much easier to work with too.

I know you can get results like this using LINQ or perhaps other frameworks, but it seems to be a weakness in the underlying design of relational databases.

We could get around this by using NoSQL, but shouldn't there be some middle ground?

Am I missing something? Why doesn't this exist?

* Yes, it's designed this way. I get it. I'm wondering why there isn't an alternative that is easier to work with. SQL could keep doing what it's doing but then they could add a keyword or two to do a little bit of post-processing that returns the data in a nested format instead of a cartesian product.

I know this can be done in a scripting language of your choice, but it requires that the SQL server either sends redundant data (example below) or that you to issue multiple queries like SELECT email FROM emails WHERE user_id IN (/* result of first query */).

Instead of having MySQL return something akin to this:

```<code>[
    {
        "name": "John Smith",
        "dob": "1945-05-13",
        "fav_color": "red",
        "email": "johnsmith45@gmail.com",
    },
    {
        "name": "John Smith",
        "dob": "1945-05-13",
        "fav_color": "red",
        "email": "john@smithsunite.com",
    },
    {
        "name": "Jane Doe",
        "dob": "1953-02-19",
        "fav_color": "green",
        "email": "originaljane@deerclan.com",
    }
]
</code>```

And then having to group on some unique identifier (which means I need to fetch that too!) client-side to reformat the result set how you want it, just return this:

```<code>[
    {
        "name": "John Smith",
        "dob": "1945-05-13",
        "fav_color": "red",
        "emails": ["johnsmith45@gmail.com", "john@smithsunite.com"]
    },
    {
        "name": "Jane Doe",
        "dob": "1953-02-19",
        "fav_color": "green",
        "emails": ["originaljane@deerclan.com"],
    }
]
</code>```

Alternatively, I can issue 3 queries: 1 for the users, 1 for the emails, and 1 for the phone numbers, but then the email and phone number result sets need to contain the user_id so that I can match them back up with the users I previously fetched. Again, redundant data and needless post-processing.

答:
Very simply, don't join your data if you want distinct results for a user query and a phone number query, otherwise as others have pointed out the "Set" or data will contain extra fields for every row.

Issue 2 distinct queries instead of one with a join.

In the stored procedure or inline parameterized sql craft 2 queries and return the results of both back.  Most database and languages support multiple result sets.

For example, SQL Server and C# accomplish functionality this by using IDataReader.NextResult().

ContentLicense: CC BY-SA 4.0


问:
Where can I find an authoritative comparison of computer languages?
I've reached a point in my career where I want to consider myself less "an {x} engineer" where {x} is a specific programming language, and I want to be more of a language-agnostic software engineer.

The obvious next step is to start learning as many languages as possible to build experience, but there's only so many hours in the day and I'd rather go about this in a more efficient way. Also, my end goal is not to be practically proficient in 20 languages, but rather to understand more deeply the variation among programming languages and what tradeoffs and design choices they made and why.

I tend to learn better when I can see an overview of the topical landscape first, before diving into the details. Is there a good, long-form (i.e., not a blog post) work on comparative language analysis that does a good job exploring the variations in programming language features? Or maybe, alternately, a good coverage text on programming language design?

答:
Well since your goal is to understand language design, I think two nice books for this are

Structure and Interpretation of Computer Programs

This is more of an "intro to computer science" in general. It teaches Scheme, and uses it as a vehicle to explore a decent swath of computer science. If nothing else, this will teach you how to program functionally since Scheme is essentially untyped lambda calculus + a few primitives.

Concepts Techniques and Models of Computer Programming

Goes through several different paradigms in a delightful language called Oz. An excellent way to learn about functional, concurrent, logic, constraint, (real) object oriented, and several other paradigms. This is important if you want to really understand the difference between languages.

These are books, not essays. But you're asking to cover a lot of ground. I'd especially recommend (skimming) CTMCP since it will talk a lot about language design, it's a very good read as well.

If you just want a general overview of what the major paradigms are, I'd actually recommend good old wikipedian comparisons. This is just a surface overview however.


答:
I do not know such a book and doubt that such a book can exist, because each and every language comparision will be inherently biased. Everyone has a programming language that dominates the perception of other programming languages. A relevant essay on this topic is “Beating The Average” by Paul Graham, a veteran Lisp hacker.

When setting out to get an overview of different languages, it is best to first get an overview of different paradigms, their history, and their interaction.

Structured Programming

Procedural Programming

Object-Oriented Programming

Functional Programming

Logic Programming

Dataflow Programming

Parallel Programming

…

Some languages can be categorized along axes of

static vs. dynamic typing

verbose vs. inferred typing

strong vs. weak typing

parameterized types?

compiled vs. interpreted

Metaprogramming?

Some Languages also share a common ancestry. E.g. the wide branch of C-style languages is dominant in todays languages.

We now have a large multidimensional matrix of different properties, and can pick interesting languages.

C does structured and procedural programming, has static weak verbose typing and is compiled. It is significant of the lingua franca of the programming world.

Haskell is a functional compiled programming language with an extremely expressive static, inferred and strong type system. In many respects it represents the cutting edge of language design.

The Lisp family contains many functional and imperative programming languages, usually with strong, dynamic typing. Interesting features are homoiconic source code, and the resulting metaprogramming capabilities.

C# is an imperative, object-oriented C-style compiled programming language with a rich static and dynamic type system including generics, type inference, and metaprogramming capabilities. It is one of the more modern and flexible languages as far as mainstream languages go.

Perl is an imperative, functional, and object oriented interpreted C-style programming language with strong, dynamic typing. It is significant here because it is strongly influenced by Lisp, Shell, and C traditions, and has unusual features in its language design.

…

Etc. I myself pick a new language once in a while, and play around with it for a month. While I cannot effectively program with it, I am usually able to confidently read sources afterwards.

An interesting idea is to read criticisms of programming languages, and to see what they do wrong. For example php was criticized as a “Fractal of bad Design” in a blog-post. Many other languages share these weaknesses, but it is interesting to see how others ship around those cliffs.

Title: Where can I find an authoritative comparison of computer languages?

Body:
I've reached a point in my career where I want to consider myself less "an {x} engineer" where {x} is a specific programming language, and I want to be more of a language-agnostic software engineer.

The obvious next step is to start learning as many languages as possible to build experience, but there's only so many hours in the day and I'd rather go about this in a more efficient way. Also, my end goal is not to be practically proficient in 20 languages, but rather to understand more deeply the variation among programming languages and what tradeoffs and design choices they made and why.

I tend to learn better when I can see an overview of the topical landscape first, before diving into the details. Is there a good, long-form (i.e., not a blog post) work on comparative language analysis that does a good job exploring the variations in programming language features? Or maybe, alternately, a good coverage text on programming language design?


问:
How to design a log() method that can easily be accessed from the outside of the Console class?
Recently my team has programmed a custom developer console in a video game which can easily be hidden or displayed, because it's more comfortable and less of a hassle.

The Console class contains a log(string) function which should be easily accessible from anywhere outside of it, without having to reference it everywhere.

How could we design a method that can be easily accessed from the outside of the class? For example printing a message to the console in C++ is as simple as:

```<code>cout << "Message";
</code>```

Well we want something similar at best, maybe Console::log(), but we are clueless how to achieve a proper way of doing it.

Cheers.

答:
The proper way to do this is to use a logging framework.  The Apache (or ones modeled on) 'log4xyz' (where xyz is the language choice - log4j for java, log4net for .net, log4cpp for C++) is one of the more common styles.

Since this is specifically about C++, I'll be referencing log4cpp (though I'm most familiar with log4j).

log4cpp has a number of log levels - emerg, fatal, alert, crit, error, warn, notice, info, and debug (docs).

You set up the appenders (an appender is a way to log something - out to a database is one appender, to a file is another, to a file rotating every 24h is another one, to a file rotating every 1 Megabyte of data is another one, etc...) and the categories (a category is a group of things that log the same way).  This can be done either in raw code, or in a property file.

The raw code would look something like this:

```<code>int main(int argc, char** argv) {
    log4cpp::Appender *appender1 = new log4cpp::OstreamAppender("console", &std::cout);
    appender1->setLayout(new log4cpp::BasicLayout());

    log4cpp::Appender *appender2 = new log4cpp::FileAppender("default", "program.log");
    appender2->setLayout(new log4cpp::BasicLayout());

    log4cpp::Category& root = log4cpp::Category::getRoot();
    root.setPriority(log4cpp::Priority::WARN);
    root.addAppender(appender1);
    root.addAppender(appender2);

    ...
}
</code>```

A property file example can be seen on the webpage for the project.

In this code, you've got two appenders that are attached to the root category - one hooked up to an output stream, the other to a file.  The root category is set to log things at the warn level or higher.

To invoke the loggers you would do things such as:

```<code>root.warn("%d + %d == %s ?", 1, 1, "two");
root << log4cpp::Priority::ERROR << "Streamed root error";
root << log4cpp::Priority::INFO << "Streamed root info";
</code>```

And here you have three messages sent to the root logger, one with warn, one with error priority, one with info.  As the info is lower than the warn error, it wouldn't get logged.  Note the two different styles of logging.

Under this model, you would create an appender that logs to your Console object and hook it up to some category.  Adjusting the log level on that category would then allow you to determine what shows up on the console.

Code for getting an arbitrary category looks something like:

```<code>log4cpp::Category& root = log4cpp::Category::getRoot();

log4cpp::Category& sub1 =
    log4cpp::Category::getInstance(std::string("sub1"));
</code>```

This could be invoked from anywhere.  This allows you to abstract away the actual connection of the code to the console (or other logger).  You could do things such as set up a remote logger (it logs to something listening on the network) so that you could have an entire screen of logging going on on a different computer (and to a file) as you test the game - without having to open up a local console to capture that information.

Body:
The proper way to do this is to use a logging framework.  The Apache (or ones modeled on) 'log4xyz' (where xyz is the language choice - log4j for java, log4net for .net, log4cpp for C++) is one of the more common styles.

Since this is specifically about C++, I'll be referencing log4cpp (though I'm most familiar with log4j).

log4cpp has a number of log levels - emerg, fatal, alert, crit, error, warn, notice, info, and debug (docs).

You set up the appenders (an appender is a way to log something - out to a database is one appender, to a file is another, to a file rotating every 24h is another one, to a file rotating every 1 Megabyte of data is another one, etc...) and the categories (a category is a group of things that log the same way).  This can be done either in raw code, or in a property file.

The raw code would look something like this:

int main(int argc, char** argv) {
    log4cpp::Appender *appender1 = new log4cpp::OstreamAppender("console", &std::cout);
    appender1->setLayout(new log4cpp::BasicLayout());

    log4cpp::Appender *appender2 = new log4cpp::FileAppender("default", "program.log");
    appender2->setLayout(new log4cpp::BasicLayout());

    log4cpp::Category& root = log4cpp::Category::getRoot();
    root.setPriority(log4cpp::Priority::WARN);
    root.addAppender(appender1);
    root.addAppender(appender2);

    ...
}

A property file example can be seen on the webpage for the project.

In this code, you've got two appenders that are attached to the root category - one hooked up to an output stream, the other to a file.  The root category is set to log things at the warn level or higher.

To invoke the loggers you would do things such as:

root.warn("%d + %d == %s ?", 1, 1, "two");
root << log4cpp::Priority::ERROR << "Streamed root error";
root << log4cpp::Priority::INFO << "Streamed root info";

And here you have three messages sent to the root logger, one with warn, one with error priority, one with info.  As the info is lower than the warn error, it wouldn't get logged.  Note the two different styles of logging.

Under this model, you would create an appender that logs to your Console object and hook it up to some category.  Adjusting the log level on that category would then allow you to determine what shows up on the console.

Code for getting an arbitrary category looks something like:

log4cpp::Category& root = log4cpp::Category::getRoot();

log4cpp::Category& sub1 =
    log4cpp::Category::getInstance(std::string("sub1"));

This could be invoked from anywhere.  This allows you to abstract away the actual connection of the code to the console (or other logger).  You could do things such as set up a remote logger (it logs to something listening on the network) so that you could have an entire screen of logging going on on a different computer (and to a file) as you test the game - without having to open up a local console to capture that information.


答:
You are missing something.  If you want to denormalize your data, you have to do it yourself.</p>

```<code>;with toList as (
    select  *, Stuff(( select ',' + (phone.phoneType + ':' + phone.PhoneNumber)
                    from phones phone
                    where phone.user_id = user.user_id
                    for xml path('')
                  ), 1,1,'') as phoneNumbers
from users user
)
select *
from toList
</code>```

Title: Why don't RDBMSes return joined tables in a nested format?

Body:
For example, say I want to fetch a User and all of his phone numbers and email addresses. The phone numbers and emails are stored in separate tables, One user to many phones/emails. I can do this quite easily:

```<code>SELECT * FROM users user
    LEFT JOIN emails email ON email.user_id=user.id
    LEFT JOIN phones phone ON phone.user_id=user.id
</code>```

The problem* with this is that it's returning the user's name, DOB, favorite color, and all the other information stored in the user table over-and-over again for each record (users×emails×phones records), presumably eating up bandwidth and slowing down the results.

Wouldn't it be nicer if it returned a  single row for each user, and within that record there was a list of emails and a list of phones? It would make the data much easier to work with too.

I know you can get results like this using LINQ or perhaps other frameworks, but it seems to be a weakness in the underlying design of relational databases.

We could get around this by using NoSQL, but shouldn't there be some middle ground?

Am I missing something? Why doesn't this exist?

* Yes, it's designed this way. I get it. I'm wondering why there isn't an alternative that is easier to work with. SQL could keep doing what it's doing but then they could add a keyword or two to do a little bit of post-processing that returns the data in a nested format instead of a cartesian product.

I know this can be done in a scripting language of your choice, but it requires that the SQL server either sends redundant data (example below) or that you to issue multiple queries like SELECT email FROM emails WHERE user_id IN (/* result of first query */).

Instead of having MySQL return something akin to this:

```<code>[
    {
        "name": "John Smith",
        "dob": "1945-05-13",
        "fav_color": "red",
        "email": "johnsmith45@gmail.com",
    },
    {
        "name": "John Smith",
        "dob": "1945-05-13",
        "fav_color": "red",
        "email": "john@smithsunite.com",
    },
    {
        "name": "Jane Doe",
        "dob": "1953-02-19",
        "fav_color": "green",
        "email": "originaljane@deerclan.com",
    }
]
</code>```

And then having to group on some unique identifier (which means I need to fetch that too!) client-side to reformat the result set how you want it, just return this:

```<code>[
    {
        "name": "John Smith",
        "dob": "1945-05-13",
        "fav_color": "red",
        "emails": ["johnsmith45@gmail.com", "john@smithsunite.com"]
    },
    {
        "name": "Jane Doe",
        "dob": "1953-02-19",
        "fav_color": "green",
        "emails": ["originaljane@deerclan.com"],
    }
]
</code>```

Alternatively, I can issue 3 queries: 1 for the users, 1 for the emails, and 1 for the phone numbers, but then the email and phone number result sets need to contain the user_id so that I can match them back up with the users I previously fetched. Again, redundant data and needless post-processing.

Body:
You are missing something.  If you want to denormalize your data, you have to do it yourself.

;with toList as (
    select  *, Stuff(( select ',' + (phone.phoneType + ':' + phone.PhoneNumber)
                    from phones phone
                    where phone.user_id = user.user_id
                    for xml path('')
                  ), 1,1,'') as phoneNumbers
from users user
)
select *
from toList


问:
How to write "good" unit tests?
Triggered by this thread, I (again) am thinking about finally using unit tests in my projects. A few posters there say something like "Tests are cool, if they are good tests". My question now: What are "good" tests?

In my applications, the main part often is some kind of numerical analysis, depending on large amounts of observed data, and resulting in a fit function that can be used to model this data. I found it especially hard to construct tests for these methods, since the number of possible inputs and results are too large to just test every case, and the methods themselves are often quite longish and can not be easily be refactored without sacrificing performance. I am especially interested in "good" tests for this kind of method.

答: Not quite so TDD, but after you have gone into QA you can improve your tests by setting up test cases to reproduce any bugs that come up during the QA process. This can be particularly valuable when you're going into longer term support and you start getting to a place where you risk people inadvertantly reintroducing old bugs. Having a test in place to capture that is particularly valuable.</p>

ContentLicense: CC BY-SA 2.5

Title: How to write "good" unit tests?


问:
C# Delegates are immutable - but why does that matter?
This is a followup question to this other question.

Background

Working from the MSDN Delegates Tutorial (C#), I see the following:

Note that once a delegate is created, the method it is associated with never changes — delegate objects are immutable.

And then, in the code sample, I see this (Spread out a little througout the code):

```<code>public delegate void ProcessBookDelegate(Book book);

bookDB.ProcessPaperbackBooks(new ProcessBookDelegate(PrintTitle));
bookDB.ProcessPaperbackBooks(new ProcessBookDelegate(totaller.AddBookToTotal));
</code>```

The Question

Now obviously, the way the code is written here a new delegate is created for each
process. I am guessing the immutability is relevant if you try to do stuff like

```<code>ProcessBookDelegate thisIsATest = new ProcessBookDelegate(PrintTitle);
ProcessBookDelegate thisIsATest = new ProcessBookDelegate(totaller.AddBookToTotal);
</code>```

which should... still compile when thisIsATest is immutable? So what problem has Microsoft solved by making it immutable? What problems would we run into if C# 6 made delegates mutable?

EDIT

I believe the immutability will prevent this:

```<code>ProcessBookDelegate thisIsATest = new ProcessBookDelegate(PrintTitle);

thisIsATest.ChangeTheDelegateInABadFashion();

someFunction(thisIsATest); //This function works as normal
                           //because the delegate is unchanged
                           //due to immutability
</code>```

but the immutability will NOT prevent this:

```<code>ProcessBookDelegate thisIsATest = new ProcessBookDelegate(PrintTitle);

thisIsATest = new ProcessBookDelegate(ChangeTheDelegateInABadFashion());

someFunction(thisIsATest); //This function works weird now because
                           //it expected the unchanged delegate
</code>```

Am I correct in this understanding?

答:
The simple answer is mutating a delegate makes very little sense. A delegate is very much a reference to a function, a set of executing code. Mutating that suggests that you are mutating that function. </p>

<p>Ask yourself, what would that method on a delegate look like, and what would do? In a sense, it would be rewriting the code of that function. That opens an enormous (almost intractable) amount of complexity to the C# specification and compiler implementations for very little benefit with large performance costs. Hence the restriction. </p>

Body:
The simple answer is mutating a delegate makes very little sense. A delegate is very much a reference to a function, a set of executing code. Mutating that suggests that you are mutating that function.

Ask yourself, what would that method on a delegate look like, and what would do? In a sense, it would be rewriting the code of that function. That opens an enormous (almost intractable) amount of complexity to the C# specification and compiler implementations for very little benefit with large performance costs. Hence the restriction.


问:
Is over-engineering a warning sign?
So we present a straightforward coding exercise to new candidates with some well defined requirements. Occasionally we receive solutions which don't really solve the problem at hand, but are over-engineered to solve a perceived problem - often outside the bounds of the exercise.

Now my question is, is this a warning sign?

EDIT: Quite a lot of the discussion is based on the test being flawed - which is a fair point. As I described in a comment, the basic premise of the test is to show how you can read the data from the file in a sensible way (and you'd be amazed at the variety of approaches we see), and how to match the items before calculating the latency between the updates. Now for this to work, certain assumptions have to be made about the data, and we look for these assumptions, and we also state explicitly that we want to see the approach you take (including OO approach etc.) All this in a two hour time frame.

IMHO, when I was interviewing it was the most complete exercise I came across.

The particular scenario which I'm pondering about is where a candidate, rather than reading from the file, accepted "network" input in a multi-threaded application, which clearly is not in scope.

答:
Maybe but consider the following:

Interviews are hard: People are under stress. This should be factored heavily into any problem you give someone

Requirement Length: How long and straight forward are the requirements? Did you make them extra wordy to make sure you included everything. As a result, they may be clear to you but the requirements maybe over engineered! I took a job interview once for an hour problem with about 3 pages of text for a problem that was relatively simple. Sometimes all that text can be tough to read and interpret on an interview and can be misinterpreted as well.

Sometimes Less is More: I would much rather have a few bullet points, sentences, and or examples showing the main requirements and then a discussion with someone to ask questions to and maybe reach out to along the way if needed. I guess what I am trying to say is you should first check your test requirements are not overly complicated for a simple problem.

Communication Skill: you should be testing the candidates ability to communicate and ask intelligent questions about the problem first and once you know they have demonstrated that they understand the problem then you can set them forth on their implementation.

Bottom Line: If you haven't checked that the problem is understood than you really don't know what to make of the over engineering. As others have said it could be a good or bad thing but if you didn't check the understanding or communicate with the candidate about the problem up front, it is harder to know their general understanding of the problem and what to make of it.

Title: Is over-engineering a warning sign?


问:
How should a REST API handle PUT requests to partially-modifiable resources?
Suppose a REST API, in response to a HTTP GET request, returns some additional data in a sub-object owner:

```<code>{
  id: 'xyz',
  ... some other data ...
  owner: {
    name: 'Jo Bloggs',
    role: 'Programmer'
  }
}
</code>```

Clearly, we don't want anyone to be able to PUT back

```<code>{
  id: 'xyz',
  ... some other data ...
  owner: {
    name: 'Jo Bloggs',
    role: 'CEO'
  }
}
</code>```

and have that succeed. Indeed, we probably aren't going to even implement a way for that to even potentially succeed, in this case.

But this question is not just about sub-objects: what, in general, should be done with data that should not be modifiable in a PUT request?

Should it be required to be missing from the PUT request?

Should it be silently discarded?

Should it be checked, and if it differs from the old value of that attribute, return a HTTP error code in the response?

Or should we use RFC 6902 JSON patches instead of sending the whole JSON?

答:
There is no rule, either in the W3C spec or the unofficial rules of REST, that says that a PUT must use the same schema/model as its corresponding GET.

It's nice if they're similar, but it's not unusual for PUT to do things slightly differently. For example, I've seen a lot of APIs that include some kind of ID in the content returned by a GET, for convenience. But with a PUT, that ID is determined exclusively by the URI and has no meaning in the content. Any ID found in the body will be silently ignored.

REST and the web in general is heavily tied to the Robustness Principle: "Be conservative in what you do [send], be liberal in what you accept." If you agree philosophically with this, then the solution is obvious: Ignore any invalid data in PUT requests. That applies to both immutable data, as in your example, and actual nonsense, e.g. unknown fields.

PATCH is potentially another option, but you shouldn't implement PATCH unless you're actually going to support partial updates. PATCH means only update the specific attributes I include in the content; it does not mean replace the entire entity but exclude some specific fields. What you're actually talking about is not really a partial update, it's a full update, idempotent and all, it's just that part of the resource is read-only.

A nice thing to do if you choose this option would be to send back a 200 (OK) with the actual updated entity in the response, so that clients can clearly see that the read-only fields were not updated.

There are certainly some people who think the other way - that it should be an error to attempt to update a read-only portion of a resource. There is some justification for this, primarily on the basis that you would definitely return an error if the entire resource was read-only and the user tried to update it. It definitely goes against the robustness principle, but you might consider it to be more "self-documenting" for users of your API.

There are two conventions for this, both of which correspond to your original ideas, but I'll expand on them. The first is to prohibit the read-only fields from appearing in the content, and return an HTTP 400 (Bad Request) if they do. APIs of this sort should also return an HTTP 400 if there are any other unrecognized/unusable fields. The second is to require the read-only fields to be identical to the current content, and return a 409 (Conflict) if the values do not match.

I really dislike the equality check with 409 because it invariably requires the client to do a GET in order to retrieve the current data before being able to do a PUT. That's just not nice and is probably going to lead to poor performance, for somebody, somewhere. I also really don't like 403 (Forbidden) for this as it implies that the entire resource is protected, not just a part of it. So my opinion is, if you absolutely must validate instead of following the robustness principle, validate all of your requests and return a 400 for any that have extra or non-writable fields.

Make sure your 400/409/whatever includes information about what the specific problem is and how to fix it.

Both of these approaches are valid, but I prefer the former one in keeping with the robustness principle. If you've ever experienced working with a large REST API, you'll appreciate the value of backward compatibility. If you ever decide to remove an existing field or make it read-only, it is a backward compatible change if the server just ignores those fields, and old clients will still work. However, if you do strict validation on the content, it is not backward compatible anymore, and old clients will cease to work. The former generally means less work for both the maintainer of an API and its clients.


问:
How to effectively share projects with other developers
I'm thinking of working with some other people on a c++ or java project. Usually for small projects, we collaborate mostly through emailing source code files back and forth, but on a larger scale, it becomes too easy for things to go wrong.

I read up on version control systems such as git and it seems to fit my needs of collaboration, but the problem is that tutorials show these tools being used through the command line, which could probably become tedious very quickly. I could use the git integration included in most IDEs, but I don't know what to do in the case of working in different IDEs or more importantly on different OS's.

How do most teams handle problems like this? What tools do they use? And how do they handle linked libraries? Any advice would be extremely helpful!

答:
git (and svn) integration across IDEs (and even OSes) are most of the time just convenience buttons for the commandline which will handle all the heavy lifting, you only need to fill in the commit message and remember to do an update once in a while

also both git and svn have pure gui tools available easily findable on google

for example tortoiseSVN has explorer integration which allows you to just right click a folder right in your windows explorer and say you want to commit, it'll ask you for a commit message and then send it over


答:
Jean Sammet's Programming Languages: History and Fundamentals is a good place to start.  From the top Amazon review, it gives is an overview of about 120 languages, with examples from about 30.

Wexelblat's History of Programming Languages and Bergin & Gibson's History of Programming Languages, Volume 2 cover quite a bit of territory.

All of these are quite dated, covering languages from years, even decades ago.  This is a Good Thing.  It will teach you that there were such things as computers and programming languages before IBM invented the PC and Microsoft invented the operating system.  (Yes, I'm joking.)  It will also give you some perspective on where we came from, and how and why some of the old languages are in fact considerable improvements on their more modern successors.

Beyond that, you have to start digging into the old literature, of the languages your father and even your grandfather used.

I'm 58.  My father and I learned FORTRAN IV at UT Austin in 1970.  I learned BASIC and PASCAL a few years later, while still in high school.  I started learning CDC 6600 COMPASS (central processor assembly language) around then, and got serious about it in Summer of 1973.  It wasn't until quite a few years later that I actually started really programming in C.  (I think it was 1987, hacking MIDI on an Atari 1040ST.  I had a copy of the floppy-based Software Toolworks C for CP/M, but I never really did anything with it.)

You absolutely must learn LISP.  I personally recommend the Scheme dialect, and I concur with the SICP recommendation in the other post.  There's an online version at MIT, and a supporting site.

I strongly recommend learning FORTH, or at least reading Leo Brodie's Starting FORTH.  It will give you a very different perspective on computing.  There's an online version at FORTH, Inc., and they offer a free (as in beer) unlimited-duration trial system.  FORTH, Inc. are good people, even though Liz Rather has retired, and even though she and I did disagree on one key point of what makes FORTH a great environment.

For a different perspective completely, read Henry Ledgard's paper "Ten Mini-Languages: A Study of Topical Issues in Programming Languages".  Rather than discussing full languages, he constructs "mini-languages" that illustrate important concepts in programming language theory and design.

This will give you something to chew on.


答:
I try to have every test only test one thing. I try to give each test a name like shouldDoSomething(). I try to test behaviour, not implementation. I only test public methods.

I usually have one or a few tests for success, and then maybe a handfull of tests for failure, per public method.

I use mock-ups a lot. A good mock-framework would probably be quite helpfull, such as PowerMock. Although I'm not using any yet.

If class A uses another class B, I'd add an interface, X, so that A doesn't use B directly. Then I'd create mock-up XMockup and use it instead of B in my tests. It really helps speeding up test execution, reducing test complexity, and also reduces the number of tests I write for A since I don't have to cope with the peculiarities of B. I can for example test that A calls X.someMethod() instead of a side effect of calling B.someMethod().

Keep you test code clean as well.

When using an API, such as a database layer, I'd mock it and enable the mock-up to throw an exception at every possible opportunity on command. I then run the tests one without throwing, and the in a loop, each time throwing an exception at the next opportunity until the test suceeds again. A bit like the memory tests available for Symbian.

Title: How to write "good" unit tests?

Body:
Triggered by this thread, I (again) am thinking about finally using unit tests in my projects. A few posters there say something like "Tests are cool, if they are good tests". My question now: What are "good" tests?

In my applications, the main part often is some kind of numerical analysis, depending on large amounts of observed data, and resulting in a fit function that can be used to model this data. I found it especially hard to construct tests for these methods, since the number of possible inputs and results are too large to just test every case, and the methods themselves are often quite longish and can not be easily be refactored without sacrificing performance. I am especially interested in "good" tests for this kind of method.


答:
Every time spent sharing code source by email is time wasted, even for small projects. Stop it now. :)

The most popular Version Control Systems are IDE and OS agnostic: they work at the file level. Sometimes you have plugins to make integration with IDE easier, but they are not strictly necessary.

So often you need not worry about these, as any major free VCS will do: Subversion, git, Mercurial... Just avoid outdated ones like CVS.

Command line is a non issue: these tools simply need you to tell them what you want to do "I want the get the last changes", "I am done making changes and I want to share them". Have you used Dropbox? It's a bit like having a Dropbox that synchronizes only when you tell it to.

This is often done by default through command line, so it is just a matter of getting used to it. But if you are still uncomfortable with it, there are GUI front ends that integrate with your IDE or with Explorer for example (TortoiseSVN and TortoiseGit).

Title: How to effectively share projects with other developers

Body:
I'm thinking of working with some other people on a c++ or java project. Usually for small projects, we collaborate mostly through emailing source code files back and forth, but on a larger scale, it becomes too easy for things to go wrong.

I read up on version control systems such as git and it seems to fit my needs of collaboration, but the problem is that tutorials show these tools being used through the command line, which could probably become tedious very quickly. I could use the git integration included in most IDEs, but I don't know what to do in the case of working in different IDEs or more importantly on different OS's.

How do most teams handle problems like this? What tools do they use? And how do they handle linked libraries? Any advice would be extremely helpful!


问:
Should We Code for Performance or Stability?
There is a point in time where you make design choices and debate them with management. In my case I have to debate my positions and design choices with senior management but it is frustrating that management only strives for performance while I think stability is a must while performance can be achieved later.

E.g. We are facing a design choice to make a recovery mechanism due to lack of transactionality in certain processes i.e. we need to guarantee transactionality of a those processes making them complete fully or rollback the changes it made to database. The current code makes this difficult because we are using stored procedures that manage their own transactions. This means that if the process calls 3 or 4 stored procedures, there is 3 or 4 transactions and if we want the recovery process we need to rollback those changes (yes, they are committed at that time, this means that we need to make more transactions to the database in order to leave it in a consistent state or at least somehow "ignore" those records).

Of course, I wanted to remove the transactions from the stored procedures and commit the transaction in the code after the process ends or rollback there if the process has exceptions.

The case is that management thinks that this approach will make the process slow and also will impact greatly in our code. I think this is correct but also I think that making the rollback process ourselves is plainly reinventing the wheel, error prone and IMHO it will take too much time in stabilize.

So, after the previous example, What could be the most beneficial approach in such cases? I mean, I want a Win-Win situation but I think it is just plainly impossible to agree on this because every time I want to talk about it I get responses like "there should be another way", "you should not tell me there is no way around", "this is not factible", "the performance will degrade", etc. and I think I will end making this faux recovery process just to comply with management.

OTOH I could be wrong and I should do what is told to me without complaining.

答:
Code should be maintainable, valid, and efficient, in that order of priority.

There is no point in having high performance code that doesn't do what it is supposed to do (there goes robustness), and whenever you hit a bug or a performance issue, it is maintainability that is going to make the difference. I have no experience in database, but I would be surprised if this principle didn't apply in database too.

Now the difficult part is getting management to accept that. And by the way, is performance a problem at all yet anyway?


问:
Correctly value a development?
I started a discussion on StackOverflow earlier this week about one of my work project and how to lead it correctly.

But it seems that this stack is a more appropriate place to ask those sort of questions, so here is my last question about my project:

How do you value your work? / How do you rate it in a financial way?

I'm working on a quite cool project with two other friends and people that we know ask us for an earlier access and how many it would cost per month for us to access it.

Unfortunately, I was not able to answer this simple question due to the fact that I'm not agree with my friends on this specific topic.

For me a bill of 80$/month/contract seems to be reasonable and appropriate for our targeted market (Institutions and Corporations) but my partner would rather count a charge of 500$/month/contract.

Our project is an asset manager in SAAS mode, and I don't really think that our potential clients would be ready to pay more than 90$/month/contract even if they have a lot of money due to their situation.

So, I would really like to have some opinions and advices on this kind of question.

PS: If my post is not on the appropriate stack, feel free to tell me.
PS2: I'm quite sorry if I'm not totally crystal clear, I'm not a native english, if you do not understand something, as above, feel free to notice me and I'll rephrase.

答:
Many thanks for all of you, I think that starting from those really interesting answers, I'll better study my case and use your great advices.

I have choose to select the answer of @user870018 because it seems to be the most usefull for me and my case, but all answers on this topic are awesome! Thanks a lot again!

Title: Correctly value a development?


答:
What you look for are two things: correctness and efficiency. It just so happens that sufficient simplicity will give you evident correctness and make efficiency easy to implement.

However, your system is long past that point. Unless there is some drastically different approach to the problem that will greatly simplify things, achieving both correctness and efficiency will be hard. If you want to do both to emerge from the same code, you will probably fail.

The only approach here is to use tests. You will have a separate body of simple code that is not at all concerned with efficiency, but correctness. And once your tests are in place, you can implement the actual solution and wrestle with it until its fast enough while all tests past.

Title: Should We Code for Performance or Stability?

Body:
There is a point in time where you make design choices and debate them with management. In my case I have to debate my positions and design choices with senior management but it is frustrating that management only strives for performance while I think stability is a must while performance can be achieved later.

E.g. We are facing a design choice to make a recovery mechanism due to lack of transactionality in certain processes i.e. we need to guarantee transactionality of a those processes making them complete fully or rollback the changes it made to database. The current code makes this difficult because we are using stored procedures that manage their own transactions. This means that if the process calls 3 or 4 stored procedures, there is 3 or 4 transactions and if we want the recovery process we need to rollback those changes (yes, they are committed at that time, this means that we need to make more transactions to the database in order to leave it in a consistent state or at least somehow "ignore" those records).

Of course, I wanted to remove the transactions from the stored procedures and commit the transaction in the code after the process ends or rollback there if the process has exceptions.

The case is that management thinks that this approach will make the process slow and also will impact greatly in our code. I think this is correct but also I think that making the rollback process ourselves is plainly reinventing the wheel, error prone and IMHO it will take too much time in stabilize.

So, after the previous example, What could be the most beneficial approach in such cases? I mean, I want a Win-Win situation but I think it is just plainly impossible to agree on this because every time I want to talk about it I get responses like "there should be another way", "you should not tell me there is no way around", "this is not factible", "the performance will degrade", etc. and I think I will end making this faux recovery process just to comply with management.

OTOH I could be wrong and I should do what is told to me without complaining.


答:
A well performing code that is unstable is no good

So the first and foremost lookout should be to achieve stability in code, and the way to do that is TESTS, build for yourself a great test suite.

When you have a great test suite that backs you, now you should try and do Load/Stress testing and if you find the performance lacking then and only then you should try to achieve performance.

And while achieving performance if you do something wrong your tests will warn you well ahead of production time.

Steps:

Tests, tests and tests

Flexible, Readable, Testable code

Load testing

Performance optimization if required and proved lacking from load/stress testing


答:
I guess all the good advices here on PSE to prefer maintainable code over fast code won't convince your management as long as both of you have only opinions, but no facts. So here is my advice how you might act in your specific situation.

Having stored procedures making their own commits without the ability to control the transactions from outside makes it really hard to reuse that procedures in a combined process (that is true for any kind of code updating a database, stored procedure or not). I see this typically as a heavy design error, typically made by beginners (but I have seen this kind of thing too often from more or less "experienced" devs).

The case is that management thinks that this approach [...] will impact greatly in our code.

Of course, it will impact your code (it will enhance its design). But IMHO in most cases you can refactor existing code in a way the risk of breaking things is not too big. For each of those stored procedure, add a parameter (for example bool autoCommit) which allows to switch the commit off optionally. Let the commit enabled be default (that has typically only a small impact on the existing code), and make sure you did not break anything so far.

Then, make a test version of your code (or at least a representative example) which uses the new feature to control the transaction from outside. This gives you an opportunity to measure the performance impact - and prove or disprove managements objections. This will also allow a direct comparison of the old and the new code showing how much better the new solution is.

Later, you may think of refactoring the changed procedures to a state where the autoCommit parameter is not needed any more.


问:
Clarification about Event Producer in StreamInsight
I need a small clarification about StreamInsight, I know by doc's that StreamInsight can handle multiple concurrent Events. But will the event producer be a separate function, for ex: I need to watch a folder for new Files because all my sensors will write readings every day in a new file in particular drive.

Method 1: FileSystemWatcher:

These is the traditional approach where we write a service using FileSystemWatcher to watch a folder for new files,etc.. Upon receiving event from FileSystemWatcher il perform some operations on these files.

How to do these using StreamInsight???

I came know that using IObservable i can push events to StreamInsight. But is there anything to watch folder is StreamInsight like FileSystemWatcher. OR In order to raise events to StreamInsight do we need to use FileSystemWacther?

Any suggestion regarding these is highly appreciated.

Thank in Advance

答:
You would need to create an IObservable input adapter that utilises the file system watcher, raising a new event when files change or are added. There's no out of the box support for this, you have to create your own adapter or check out the samples on MSDN.

You then create a query that observes the input adapter to process the changes.


问:
Is it a bad practice to modify code strictly for testing purposes
I have a debate with a programmer colleague about whether it is a good or bad practice to modify a working piece of code only to make it testable (via unit tests for example).

My opinion is that it is OK, within the limits of maintaining good object oriented and software engineering practices of course (not "making everything public", etc).

My colleague's opinion is that modifying code (which works) only for testing purposes is wrong.

Just a simple example, think of this piece of code that is used by some component (written in C#):

```<code>public void DoSomethingOnAllTypes()
{
    var types = Assembly.GetExecutingAssembly().GetTypes();

    foreach (var currentType in types)
    {
        // do something with this type (e.g: read it's attributes, process, etc).
    }
}
</code>```

I have suggested that this code can be modified to call out another method that will do the actual work:

```<code>public void DoSomething(Assembly asm)
{
    // not relying on Assembly.GetExecutingAssembly() anymore...
}
</code>```

This method takes in an Assembly object to work on, making it possible to pass your own Assembly to do the testing on. My colleague didn't think this is a good practice.

What is considered a good and common practice ?

答:
Your question gave not much context in which your colleague argued so there is room for speculation

"bad practice" or not depends on how and when the changes are made.

In my opition your example to extract a method DoSomething(types) is ok.

But i have seen code which is not ok like this:

```<code>public void DoSomethingOnAllTypes()
{
  var types = (!testmode)
      ? Assembly.GetExecutingAssembly().GetTypes()
      : getTypesFromTestgenerator();

  foreach (var currentType in types)
  {
     if (!testmode)
     {
        // do something with this type that made the unittest fail and should be skipped.
     }
     // do something with this type (e.g: read it's attributes, process, etc).
  }
}
</code>```

These changes made the code more difficuilt to understand because you increased the number of possible code-paths.

What i mean with how and when:

if you have a working implementation and for the the sake of "implementing testing-capabilities" you made the changes then you have to re-test you application because you may have broken your DoSomething() method.

The if (!testmode) is more more difficulilt to understand and test than the extracted method.

Body:
Your question gave not much context in which your colleague argued so there is room for speculation

"bad practice" or not depends on how and when the changes are made.

In my opition your example to extract a method DoSomething(types) is ok.

But i have seen code which is not ok like this:

public void DoSomethingOnAllTypes()
{
  var types = (!testmode)
      ? Assembly.GetExecutingAssembly().GetTypes()
      : getTypesFromTestgenerator();

  foreach (var currentType in types)
  {
     if (!testmode)
     {
        // do something with this type that made the unittest fail and should be skipped.
     }
     // do something with this type (e.g: read it's attributes, process, etc).
  }
}

These changes made the code more difficuilt to understand because you increased the number of possible code-paths.

What i mean with how and when:

if you have a working implementation and for the the sake of "implementing testing-capabilities" you made the changes then you have to re-test you application because you may have broken your DoSomething() method.

The if (!testmode) is more more difficulilt to understand and test than the extracted method.


问:
In my permissions API, how do I handle objects that don't exist?
Elgg is designing a permissions API loosely around the Activity Streams model. The user API could look (roughly) like:

```<code>function elgg_can($capability, $subject = null, $object = null, $target = null) { ... }
</code>```

$capability is a string

$subject is a user object

$object is the object acted upon

$target is the context in which the action would take place

E.g. Can the current user edit the title of an object?

```<code>if (elgg_can('edit title', $currentUser, $someObject)) {
    ...
}
</code>```

I'd like to know a good way to handle asking for permission to create objects. If the object doesn't yet exist, then the permissions system can't know anything about it, so there's a chicken-egg problem with a few obvious solutions:

Allow passing in a string in place of $object (e.g. the TypeName).

Put metadata about the object in the $capability. E.g. elgg_can("create PageObject", $currentUser, null, $group).

Have the API user create the object then pass it into the API to decide if it should be allowed to continue existing.

Am I missing another obvious solution? Are there permissions models similar to this (that one could reasonably call successful) that handle this?

答:
Are you sure that this is truly a permissions issue?

There are plenty of existing object-level security models, both role-based and policy-based, the most obvious example of which is the ACL. Each object may have its own permissions, which makes sense. But there is no permission for "create this object", there is only a permission for "create an object". There might be restrictions around the type of object a user can create, but that's usually about as far as it goes.

Of course, the actual operation of creating an object may fail for other reasons. For example, the object might be considered a duplicate, or might have some invalid data or violate some important rule (a tweet being too long, for example). Not being able to, let's say, add a photo to a photo album that you don't own, is more about validation of the request than permissions on the (nonexistent) object.

Of the options you propose, #2 is probably closest to modeling the actual permissions without also providing information it can't possibly know for sure at the time (i.e. whether or not creation of an object will succeed). There is no object when doing the permission check, so if a user can only create certain types of objects then there should be a different permission for each type.

You might also want to consider that an ultra-generic, one-size-fits-all function is often problematic for exactly this reason - there's always some scenarios that just don't fit, and if you try to make them fit, you end up with an ambiguous or hard-to-use specification. For example, shouldn't a user be able to ask the question, "What types of objects can I create in this location?" instead of having to figure it out one-by-one? I obviously don't know as much about the domain as you do, but just consider the possibility that you might be trying to fit 10 pounds into a 5-pound bag. If the API would be cleaner by having 2 or 3 or 10 functions instead of just 1, then expanding it might be the best answer.


问:
Designing application flow
I am creating a web application in java where I need to mock the following flow.

When user trigger a certain process (add product to cart), I need to pass through following steps

Need to see in HTTP Session if user is logged in.

Check HTTP Session if shopping cart is there

If user exist in HTTP Session and his/her cart do not exist in HTTP Session

Get user cart from the database.

add item to cart and save it to HTTP session and update cart in DB.

If cart does not exist in DB, create new cart and and save in it HTTP Session.

Though I missed a lot of use cases here (do not want question length to increase a lot), but most of the flow will be same as I described in above steps.

My flow will start from the Controller and will go towards Service Layer and than ends up in the DAO layer.

Since there will be a lot of use cases where I need to check HTTP session and based on that need to call Service layer, I was planning to add a Facade layer which should be responsible to do this for me like checking Session and interacting with Service layer.

Please suggest if this is a valid approach or any other best approach can be implemented here?

One more point where I am confused is how to handle HTTP session in facade layer? do I need to pass HTTP session object each time I call my Facade or any other approach can be used here?

答:
When I look at your use case, I start thinking about separation of concerns.

The controller shouldn't care if the cart is in the request or not.

The service call that adds Items to a cart shouldn't care if the user is logged in or not.

I then think:

Request objects are a pain in the butt to test with

A Facade feels kind of vague for specific use cases.  What if we could create a simple Data Transfer Object for each use case that has the data needed?

So I would start with something like:

Controller

```<code>Status addItemToCart(HttpServletRequest request, Item item) {
  if(request.getSession(false) == null) return needLogin(request)

  UserCart cart = service.addItemToCart(item, new UserCart(session))
  return cart.saveToSession(session)
}
</code>```

Service

```<code>UserCart addItemToCart(Item item, UserCart userCart) {
  if userCart.needsCart() {
     userCart = cartDAO.getNewCart(userCart)
  }
  userCart.addItem(Item)
  return cartDAO.updateCart(userCart)
}
</code>```

My Service layer tests would insist on something like UserCart to keep me from having to mock HTTPServletRequests and create 10 lines of setup code.  UserCart is just a dumb Data Transfer Object with some convenience methods, but it makes everything much simpler to understand.  User has-a shopping cart is important to this use case, so it's where my brain goes pretty quickly.  This also allows us to avoid all the null checks and nested blocks that become rampant when you go out of your way to avoid creating simple domain specific concepts.

Title: Designing application flow

Body:
When I look at your use case, I start thinking about separation of concerns.

The controller shouldn't care if the cart is in the request or not.

The service call that adds Items to a cart shouldn't care if the user is logged in or not.

I then think:

Request objects are a pain in the butt to test with

A Facade feels kind of vague for specific use cases.  What if we could create a simple Data Transfer Object for each use case that has the data needed?

So I would start with something like:

Controller

Status addItemToCart(HttpServletRequest request, Item item) {
  if(request.getSession(false) == null) return needLogin(request)

  UserCart cart = service.addItemToCart(item, new UserCart(session))
  return cart.saveToSession(session)
}

Service

UserCart addItemToCart(Item item, UserCart userCart) {
  if userCart.needsCart() {
     userCart = cartDAO.getNewCart(userCart)
  }
  userCart.addItem(Item)
  return cartDAO.updateCart(userCart)
}

My Service layer tests would insist on something like UserCart to keep me from having to mock HTTPServletRequests and create 10 lines of setup code.  UserCart is just a dumb Data Transfer Object with some convenience methods, but it makes everything much simpler to understand.  User has-a shopping cart is important to this use case, so it's where my brain goes pretty quickly.  This also allows us to avoid all the null checks and nested blocks that become rampant when you go out of your way to avoid creating simple domain specific concepts.


问:
How to use BDD to unit test a compiler?
My team is writing a compiler for a domain-specific language (DSL) which will be integrated into an IDE. Right now, we are focused on the analysis phase of the compiler. We are not using any existing parser-generators (such as ANTLR) because we need real-time performance and highly detailed error/warning/message information. We have

classes, each of which represents a node in the concrete syntax tree for the language, as well as

classes which act as annotations for each node (i.e., for errors and additional information), as well as

internal classes which build and manipulate the concrete syntax tree (i.e., lexer, parser, cache for strings, syntax visitors).

We are trying to decide on an overall strategy for organizing our tests. Our company is pushing behavior-driven development (BDD) and domain-driven design (DDD). Although we are building a DSL for our company’s domain, the domain of the compiler is a programming language.

We are still in the process of building the compiler and have some tests already. We are aiming to have 100% statement coverage.

We currently have tests in which we input source code to the syntax tree builder, and then run a verification on each property of every node of the resultant syntax tree to make sure that the expected information (line number, relevant error(s), child/parent tokens, width of token, type of token, etc.). Now, since each node is its own class, and certain annotations and errors attached to a node are separate classes, this test ends up referencing many classes.

We currently have tests for certain classes such as the lexer in which we can isolate the input (a string) and the output (a list of tokens) from other classes (e.g., the classes for the nodes of the syntax tree). These tests are more granular.

Now, the tests in the paragraph immediately above can be put in correspondence with the class under test (e.g., lexer, string cache). However, the tests from the second paragraph above really test the whole analysis phase of the compiler; that is, each test can have well over 300 assertions for the syntax tree, given the input source code. The tests are for the behavior of the analysis phase.

Is this an appropriate testing strategy? If not, what should we be doing differently? What organization strategy should we use for our tests?

答:
```<code>  > Is this an appropriate testing strategy?
</code>```

No, because the your subdomain is a DSL (a kind of programming language) and your compiler is part of an implementation detail for the use case that allows to automate actions/workflows in this domain using the DSL.

Since I do not know how your DSL looks like I assume that you have concepts like loop, condition, statement, variable using the example

```<code> for(int i=1;i =< 10;i++) {subtask();}
</code>```

Using a bdd-gherkin like language you could write something like

```<code>as a automation user
i want to have a for loop with startvalue, endvalue, loopincrement
so that i can repeat subtasks several times.

given startvalue=1
and endvalue = 10
and loopinclrement = 1
when i execute for(int i=%startvalue%;i =< %endvalue %;i+=%loopinclrement%)
then the subtask should have been executet 10 times.
</code>```

This is quite a lot of work to prove that your compiler works as expected.

```<code>  > If not, what should we be doing differently?
  > What organization strategy should we use for our tests?
</code>```

I would create a big repository of examples for input with corresponding output.

The automated test would iterate through the examples and verify that the compiler output matches the expected output.

Example: if your invoice/order-related dsl compiles to java a repository entry would look like:

```<code> example: loop over orderentries
 dsl-source: foreach orderitem in orders do calculateTaxes(orderitem)
 expected errormessage: none
 expected java output: for(OrderItemType orderitem : orders)
                          {calculateTaxes(orderitem);}

 example: loop with syntax errors
 dsl-source: foreach orderitem in orders
 expected errormessage: missing "do"-keyword in line 1
 expected java output: none
</code>```

So instead of writing a lot of code to fit bdd you simply have to add examples of hardcoded input/output values.

Title: How to use BDD to unit test a compiler?

Body:
  > Is this an appropriate testing strategy?

No, because the your subdomain is a DSL (a kind of programming language) and your compiler is part of an implementation detail for the use case that allows to automate actions/workflows in this domain using the DSL.

Since I do not know how your DSL looks like I assume that you have concepts like loop, condition, statement, variable using the example

 for(int i=1;i =< 10;i++) {subtask();}

Using a bdd-gherkin like language you could write something like

as a automation user
i want to have a for loop with startvalue, endvalue, loopincrement
so that i can repeat subtasks several times.

given startvalue=1
and endvalue = 10
and loopinclrement = 1
when i execute for(int i=%startvalue%;i =< %endvalue %;i+=%loopinclrement%)
then the subtask should have been executet 10 times.

This is quite a lot of work to prove that your compiler works as expected.

  > If not, what should we be doing differently?
  > What organization strategy should we use for our tests?

I would create a big repository of examples for input with corresponding output.

The automated test would iterate through the examples and verify that the compiler output matches the expected output.

Example: if your invoice/order-related dsl compiles to java a repository entry would look like:

 example: loop over orderentries
 dsl-source: foreach orderitem in orders do calculateTaxes(orderitem)
 expected errormessage: none
 expected java output: for(OrderItemType orderitem : orders)
                          {calculateTaxes(orderitem);}

 example: loop with syntax errors
 dsl-source: foreach orderitem in orders
 expected errormessage: missing "do"-keyword in line 1
 expected java output: none

So instead of writing a lot of code to fit bdd you simply have to add examples of hardcoded input/output values.


问:
Which if statement requires less computation?
I have

```<code>if (!b && c || a && c)
  //do action a
else
  //...
</code>```

Due to some internal relationship between a, b, and c. !b && c || a && c is proved to be equivalent to (! a && b) || c.

I just wonder will (! a && b) || c be simpler than !b && c || a && c? Can you prove it? Assume the chances of a,b,c to be True or False is equal.

I'm not asking which style is better. I'm asking which statement has lower computational complexity. Just like asking quick sort and Bubble Sort, which has lower computational complexity. You will not answer it depends, it is related to compiler and hardware because some hardware have special instruction for Bubble Sort. I hope to hear nlog(n) and n^2.

答:
Well cant really answer this because

```<code>if (!b && c || a && c)
</code>```

is not equal to

```<code>if ((! a && b) || c)
</code>```

The truth tables for each are below, abc output:

```<code>000 0
001 1
010 0
011 0
100 0
101 1
110 0
111 1
</code>```

this doesnt match the above

```<code>000 0
001 1
010 1
011 1
100 0
101 1
110 0
111 1
</code>```

test program

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

unsigned int a,b,c;

int main ( void )
{
    for(a=0;a<2;a++)
    for(b=0;b<2;b++)
    for(c=0;c<2;c++)
    {
        printf("%u%u%u ",a,b,c);
        if (!b && c || a && c)
        {
            printf("1\n");
        }
        else
        {
            printf("0\n");
        }
    }

    printf("\n");

    for(a=0;a<2;a++)
    for(b=0;b<2;b++)
    for(c=0;c<2;c++)
    {
        printf("%u%u%u ",a,b,c);
        if ((! a && b) || c)
        {
            printf("1\n");
        }
        else
        {
            printf("0\n");
        }
    }

    return(0);
}
</code>```

Please add more parenthesis to improve the order of operations, and/or post an equivalent equation, then we can talk about how they differ in complexity.

This is equivalent

```<code>    if (c && (!(!a && b)))
</code>```

note clang's opinion on this syntax:

```<code>fun.c:5:12: warning: '&&' within '||' [-Wlogical-op-parentheses]
    if (!b && c || a && c) return(1);
        ~~~^~~~ ~~
fun.c:5:12: note: place parentheses around the '&&' expression to silence this
      warning
    if (!b && c || a && c) return(1);
           ^
        (      )
fun.c:5:22: warning: '&&' within '||' [-Wlogical-op-parentheses]
    if (!b && c || a && c) return(1);
                ~~ ~~^~~~
fun.c:5:22: note: place parentheses around the '&&' expression to silence this
      warning
    if (!b && c || a && c) return(1);
                     ^
                   (     )
</code>```

Using arm as a test target, the answer is not going to be deterministic BTW, it is compiler and target and system dependent on which is faster, less computation, etc.  Looks on the surface with an arm and its instruction set features the first solution with gcc is clean and deterministic (no branches).

This will of course change with each compiler and target and also with whatever code surrounds that if statement. (note the version of gcc and clang/llvm can/will create different results).

```<code>unsigned int bool1 ( unsigned int a, unsigned int b, unsigned int c )
{
    if (!b && c || a && c) return(1);
    return(0);
}

unsigned int bool2 ( unsigned int a, unsigned int b, unsigned int c )
{
    if (c && (!(!a && b))) return(1);
    return(0);
}

//gcc

//00000000 <bool1>:
   //0: e2900000    adds    r0, r0, #0
   //4: 13a00001    movne   r0, #1
   //8: e3510000    cmp r1, #0
   //c: 03800001    orreq   r0, r0, #1
  //10: e3520000    cmp r2, #0
  //14: 03a00000    moveq   r0, #0
  //18: 12000001    andne   r0, r0, #1
  //1c: e12fff1e    bx  lr

//00000020 <bool2>:
  //20: e3520000    cmp r2, #0
  //24: 0a000005    beq 40 <bool2+0x20>
  //28: e2711001    rsbs    r1, r1, #1
  //2c: 33a01000    movcc   r1, #0
  //30: e3500000    cmp r0, #0
  //34: 01a00001    moveq   r0, r1
  //38: 13810001    orrne   r0, r1, #1
  //3c: e12fff1e    bx  lr
  //40: e1a00002    mov r0, r2
  //44: e12fff1e    bx  lr

//clang

//bool1:                                  @ @bool1
    //cmp   r1, #0
    //bne   .LBB0_2
    //cmp   r2, #0
    //movne r0, #1
    //movne pc, lr
//.LBB0_2:                                @ %lor.lhs.false
    //cmp   r2, #0
    //movne r2, #1
    //cmp   r0, #0
    //movne r0, #1
    //and   r0, r0, r2
    //mov   pc, lr

//bool2:                                  @ @bool2
    //mov   r3, r0
    //cmp   r2, #0
    //beq   .LBB1_2
    //mov   r0, #1
    //cmp   r3, #0
    //movne pc, lr
    //cmp   r1, #0
    //movne r0, #0
    //b .LBB1_3
//.LBB1_2:                                @ %if.end
    //mov   r0, #0
//.LBB1_3:                                @ %return
    //mov   pc, lr
</code>```

Body:
Well cant really answer this because

if (!b && c || a && c)

is not equal to

if ((! a && b) || c)

The truth tables for each are below, abc output:

000 0
001 1
010 0
011 0
100 0
101 1
110 0
111 1

this doesnt match the above

000 0
001 1
010 1
011 1
100 0
101 1
110 0
111 1

test program

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

unsigned int a,b,c;

int main ( void )
{
    for(a=0;a<2;a++)
    for(b=0;b<2;b++)
    for(c=0;c<2;c++)
    {
        printf("%u%u%u ",a,b,c);
        if (!b && c || a && c)
        {
            printf("1\n");
        }
        else
        {
            printf("0\n");
        }
    }

    printf("\n");

    for(a=0;a<2;a++)
    for(b=0;b<2;b++)
    for(c=0;c<2;c++)
    {
        printf("%u%u%u ",a,b,c);
        if ((! a && b) || c)
        {
            printf("1\n");
        }
        else
        {
            printf("0\n");
        }
    }

    return(0);
}

Please add more parenthesis to improve the order of operations, and/or post an equivalent equation, then we can talk about how they differ in complexity.

This is equivalent

    if (c && (!(!a && b)))

note clang's opinion on this syntax:

fun.c:5:12: warning: '&&' within '||' [-Wlogical-op-parentheses]
    if (!b && c || a && c) return(1);
        ~~~^~~~ ~~
fun.c:5:12: note: place parentheses around the '&&' expression to silence this
      warning
    if (!b && c || a && c) return(1);
           ^
        (      )
fun.c:5:22: warning: '&&' within '||' [-Wlogical-op-parentheses]
    if (!b && c || a && c) return(1);
                ~~ ~~^~~~
fun.c:5:22: note: place parentheses around the '&&' expression to silence this
      warning
    if (!b && c || a && c) return(1);
                     ^
                   (     )

Using arm as a test target, the answer is not going to be deterministic BTW, it is compiler and target and system dependent on which is faster, less computation, etc.  Looks on the surface with an arm and its instruction set features the first solution with gcc is clean and deterministic (no branches).

This will of course change with each compiler and target and also with whatever code surrounds that if statement. (note the version of gcc and clang/llvm can/will create different results).

unsigned int bool1 ( unsigned int a, unsigned int b, unsigned int c )
{
    if (!b && c || a && c) return(1);
    return(0);
}

unsigned int bool2 ( unsigned int a, unsigned int b, unsigned int c )
{
    if (c && (!(!a && b))) return(1);
    return(0);
}

//gcc

//00000000 <bool1>:
   //0: e2900000    adds    r0, r0, #0
   //4: 13a00001    movne   r0, #1
   //8: e3510000    cmp r1, #0
   //c: 03800001    orreq   r0, r0, #1
  //10: e3520000    cmp r2, #0
  //14: 03a00000    moveq   r0, #0
  //18: 12000001    andne   r0, r0, #1
  //1c: e12fff1e    bx  lr

//00000020 <bool2>:
  //20: e3520000    cmp r2, #0
  //24: 0a000005    beq 40 <bool2+0x20>
  //28: e2711001    rsbs    r1, r1, #1
  //2c: 33a01000    movcc   r1, #0
  //30: e3500000    cmp r0, #0
  //34: 01a00001    moveq   r0, r1
  //38: 13810001    orrne   r0, r1, #1
  //3c: e12fff1e    bx  lr
  //40: e1a00002    mov r0, r2
  //44: e12fff1e    bx  lr

//clang

//bool1:                                  @ @bool1
    //cmp   r1, #0
    //bne   .LBB0_2
    //cmp   r2, #0
    //movne r0, #1
    //movne pc, lr
//.LBB0_2:                                @ %lor.lhs.false
    //cmp   r2, #0
    //movne r2, #1
    //cmp   r0, #0
    //movne r0, #1
    //and   r0, r0, r2
    //mov   pc, lr

//bool2:                                  @ @bool2
    //mov   r3, r0
    //cmp   r2, #0
    //beq   .LBB1_2
    //mov   r0, #1
    //cmp   r3, #0
    //movne pc, lr
    //cmp   r1, #0
    //movne r0, #0
    //b .LBB1_3
//.LBB1_2:                                @ %if.end
    //mov   r0, #0
//.LBB1_3:                                @ %return
    //mov   pc, lr


问:
How to edit the HTML of an ASP.net site?
Assume that I'm a front-end developer (HTML, CSS)

And some one who got their website built using ASP.NET came to me and asked for a new design and I don't know about ASP.NET.

Then, how can I change the design of their website without affecting their code?

Do I have to learn a little bit of server side languages to be able to change to the look of sites without affecting the original server code?

答:
That strongly depends how the application was designed. Using a good MVC structure where all template files are excluded and it's even using a template engine, you might not need any ASP.NET skills, but that's the ideal world.
The worst case is that everything is inside a big spaghetti code like system, where it'S even hard to find places to change the design even when you know the programming language.

Do you know if there's any framework or template engine in place?


问:
How do I create a simple yet complex business layer?
I'm working with a fairly complex web application. It's split up into the following layers:

Presentation - HTML

Service layer - A REST and SOAP API communicating with the business layer

Business layer - Contains the business logic.

Data access - Provides access to the storage (SQL etc)

The business layers contains classes encapsulating specific areas, such as customer registration, user management and more. The problem we are seeing is that the business layer is starting to get a bit messy. We have a single class handling customer management but as this area of the application grows more and more complex, the class grows and grows and become messy.

For example, we may have the following classes

class CustomerManager

void CreateCustomer(...)

void DeleteCustomer(...)

class UserManager

void CreateUser(..)

void DeleteUser(...)

void ActivateUser(...)

void InactivateUser(...)

void ResetPassword(...)

Creating a customer involves creating users as well. So CustomerManager calls misc methods in the UserManager class. As the application has evolved, creating a new customer means roughly 10 different things needs to be done except for registring the customer in the database, such as informing sales, audit logging, configuring default user accounts, creating a default configuration for the customer, notifying end-users of their auto-generated passwords and more. So CustomerManager.CreateCustomer grows to ~100 lines of fairly hairy code.

I'm trying to think of a good way to handle this but am assuming that there's some common good way to do this which I'm simply not aware of.

I've considered creating "Task"/"Command" classes implementing small sub-processes and then let the CustomerCreation.CreateCustomer simply execute a set of tasks. I would have more classes but they would each do less things.

I've also considering implementing some kind of global application-level event/plug-in systems where CustomerManager.CreateCustomer just creates the customer in the database and then publishes an event that the customer is created. Plug-ins/something can then subscribe to these events and do stuff such as informing sales and logging the fact. Using this method, I wouldn't have to actually update CustomerManager.CreateCustomer when I want to do more stuff which is something which feels attractive to me.

What obvious design pattern am I missing?

答:
Plugins are nice if you want to let third-parties extend your current application, but if that is not the case, you risk to make the architecture more complex than necessary.

Do yourself a favor and before trying to throw randomly some patterns at your business layer, start with small and simple things first:

if you have a method with 100 lines of code, start refactoring to many smaller methods.

make sure your smaller methods have all a single responsibility (see also: SOLID), and try to achieve a state where the parts of the calling methods work all on the same level of abstraction

when you have enough small methods dealing around a specific topic, you may extract them to classes (especially when the smaller methods exclusively share some data)

you can have the "command" pattern in mind for the new classes you create. If it is really a good idea to use that pattern will reveal after you have created some of that helper classes and they look all like similar commands, with a command-like interface


答:
As @DocBrown said, plugins are mostly useful when you want to allow third parties to be able to extend your application. But that doesn't mean you can't use similar techniques in your design as what gets commonly used when interfacing with plugins.

For example, if a lot of the code you have is along the lines of "after creating the customer in the databse, components X, Y and Z need to be informed so they can take their appropriate actions", then you can use the Observer pattern there to decouple CustomerRegistration from X, Y and Z (and at a later time, A and B could get added to that list as well).

On the other hand, if your logic has a lot of ifs, buts and unless tests in it, then there is no real way to reduce the complexity of the code, because it is inherent in the business rules that the code represents.

Title: How do I create a simple yet complex business layer?

Body:
I'm working with a fairly complex web application. It's split up into the following layers:

Presentation - HTML

Service layer - A REST and SOAP API communicating with the business layer

Business layer - Contains the business logic.

Data access - Provides access to the storage (SQL etc)

The business layers contains classes encapsulating specific areas, such as customer registration, user management and more. The problem we are seeing is that the business layer is starting to get a bit messy. We have a single class handling customer management but as this area of the application grows more and more complex, the class grows and grows and become messy.

For example, we may have the following classes

class CustomerManager

void CreateCustomer(...)

void DeleteCustomer(...)

class UserManager

void CreateUser(..)

void DeleteUser(...)

void ActivateUser(...)

void InactivateUser(...)

void ResetPassword(...)

Creating a customer involves creating users as well. So CustomerManager calls misc methods in the UserManager class. As the application has evolved, creating a new customer means roughly 10 different things needs to be done except for registring the customer in the database, such as informing sales, audit logging, configuring default user accounts, creating a default configuration for the customer, notifying end-users of their auto-generated passwords and more. So CustomerManager.CreateCustomer grows to ~100 lines of fairly hairy code.

I'm trying to think of a good way to handle this but am assuming that there's some common good way to do this which I'm simply not aware of.

I've considered creating "Task"/"Command" classes implementing small sub-processes and then let the CustomerCreation.CreateCustomer simply execute a set of tasks. I would have more classes but they would each do less things.

I've also considering implementing some kind of global application-level event/plug-in systems where CustomerManager.CreateCustomer just creates the customer in the database and then publishes an event that the customer is created. Plug-ins/something can then subscribe to these events and do stuff such as informing sales and logging the fact. Using this method, I wouldn't have to actually update CustomerManager.CreateCustomer when I want to do more stuff which is something which feels attractive to me.

What obvious design pattern am I missing?


答:
Component architecture can provide good tools for fighting complexity of the business layer. For example, notifications can be done with registering subscribers (event handlers). A lot of logic can be done by adaptors, which will provide certain specific interfaces to your User and Customer interfaces. This way logic can be decoupled, making large monolithic classes unnecessary. Hopefully your platform already has some proven component architecture you can use, which is much better than implementing "plugins" from scratch.

Older answer (see first comment):

My first impression of having CustomerRegistration and
  UserRegistration classes with the methods mentioned is that OO
  analysis has not been properly accomplished. I always thought that
  having sensible entities at business layer is the only way to prevent
  the mess. My advice would be to redesign (if it is not late yet) the
  business layer classes to better reflect business entities and not
  frontend processes. It may well be, that after such a redesign
  complexity will be a fraction of what you have now, and, more
  important, natural representation of the problem domain will answer
  your goals better than classes, combined with seemingly related
  functions.

For example, even as such, UserRegistration should not have DeleteUser
  method! The task naturally belong to UsersManager class or maybe
  UserRegistry, if you wish.

In short, I think the problem is that classes are formed around
  action-like entities, which requires much more interconnections
  (=mess) than class system around (say) User, Customer, and Managers of
  those two (managers are more like containers).

There is little point of making User Management OOA from scratch. Good
  examples can be found from many frameworks, and sometimes they handle
  much more complex things, like fine-grained authorization,
  role/permission management, group management, etc.


问:
What is the downside of returning a string instead of a void function or throwing an exception?
Say I have a method that inserts a record into the database. I don't need to know the newly-inserted ID or anything else. I have two options:

public void Insert()

public string Insert()

In the first: if an insert is successful, the calling code will continue. If it fails, an exception with the details will be returned and the calling code will handle it in the catch.

In the second: the calling code will interrogate the return string for specific words to see whether or not it was successful.

Which option is better and why?

答:
IMO the void method is preferred. In OO programming it is better style to simply use objects and if there is an error throw an exception which can be caught. The exception thrown should be pertinent to the error and descriptive - the descriptive message may not be shown to the user but logged, depending on the scenario. This is also the most common approach of the developers I have encountered using .Net.

The problem with returning a string is that soon your code will be cluttered with similarly crafted methods, causing conditional statements to proliferate in the codebase. Ultimately this becomes a maintenance problem as it reduces readability. It is error prone as developers may forget to check for certain failures. It provides less information to the caller if there was an error, unlike an exception, unless you filled the string with all sorts of information which would then need to be parsed. It requires silently handling exceptions in methods then returning some failure message, a rather strange approach to say the least!

In fact the more I think about it the more horrifying it seems. Follow the KISS philosophy - keep it simple and stupid! Don't pollute your code base with all of these decision points.

Don't go the other way though and put try/catch everywhere you think an exception will occur either. Let exceptions bubble up the call stack and handle at appropriate junctures according to the specifics of the application. Clean code will be more achievable then.

OwnerDisplayName: Jaycee


答:
Overall there is nothing to add Jaycee's answer.
But If I would write an API, I would write it always returning the ID of the record if the insertion suceeded.

```<code>public Guid CreateCustomer(Customer c){

}
</code>```

Or something the like. Even if you never need the return value, you could call the method simply without caring CreateCustomer(customer) and you're done. But if the case is needed, that you have to know the Guid, you get it for free:

```<code>Guid itemCreated=CreateCustomer(customer)
</code>```

There is no obligation to use a return value, but if you do not define one, there is no chance at getting the value without a further request. To return the Guid doesn't hurt.

In case an error occured an exception is the appropriate way to go.

Title: What is the downside of returning a string instead of a void function or throwing an exception?

Body:
Say I have a method that inserts a record into the database. I don't need to know the newly-inserted ID or anything else. I have two options:

public void Insert()

public string Insert()

In the first: if an insert is successful, the calling code will continue. If it fails, an exception with the details will be returned and the calling code will handle it in the catch.

In the second: the calling code will interrogate the return string for specific words to see whether or not it was successful.

Which option is better and why?

Body:
Overall there is nothing to add Jaycee's answer.
But If I would write an API, I would write it always returning the ID of the record if the insertion suceeded.

public Guid CreateCustomer(Customer c){

}

Or something the like. Even if you never need the return value, you could call the method simply without caring CreateCustomer(customer) and you're done. But if the case is needed, that you have to know the Guid, you get it for free:

Guid itemCreated=CreateCustomer(customer)

There is no obligation to use a return value, but if you do not define one, there is no chance at getting the value without a further request. To return the Guid doesn't hurt.

In case an error occured an exception is the appropriate way to go.