答:
A void pointer says nothing about what it is pointing to - it's a "pointer to anything".  So info -> simTime is not meaningful to the compiler.  You need to cast the pointer back to the correct type before dereferencing it.  If you know that it will always be a shiftInfo, then try something like ((shiftInfo *) info) -> simTime.

Your second warning is probably pointing out a bug in your program.  The 3rd parameter is supposed to be a pointer-to-function, but you are passing it customer, which is a pthread_t.

Title: Using a global struct with pthreads in C

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

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

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

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

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

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

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

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

And the timer thread function is:

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

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

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

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


问:
Unit testing the variables passed to the view from the controller
Let's say I want to test a controller that gets some value from a service and then pass some of all of those values to the view.

Do you test that the view gets the result that the controller took from the service, without taking care of seeing the exact variables being passed, or do you test specifically for the variables that you need on the view?

So if in the view you have var 'foo' and 'foo2', you can test that the controller is simply passing the info it gets from the service, or you can test that the variables being passed are effectively called 'foo' and 'foo2'.

What approach do you use?

答:
Whenever you test a class or a method, you provide the inputs and then verify that it produces the outputs that it is responsible for.

If the documented behaviour of your class is to pass on whatever it gets, then you would write a test passing in "foo" and "bar", or "grumpy" and "slouchy", or any other set of inputs, and verify that they are passed on. The check that "foo" is produced belongs into another test (the test for the service).

But if the behaviour requires that the controller sends values for  particular set of attributes, then your test should verify that it produces exactly this output, and check both the attributes and their values.

ContentLicense: CC BY-SA 3.0


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

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

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

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

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

答: As a rule of thumb, a standard function should be able to accept the broadest list of inputs and give feedback on it, there are many examples where programmers use functions in ways that the designer had not planned, with this in mind i believe the function should be able to accept not only empty collections but a wide range of input types and gracefully return feedback, be it even an error object from whatever operation was performed on the input... </p>


问:
Should a class validate argument using external method/service with unit testing?
I have a class that runs as a service and returns html code of a website when supplied with a URL.

The code:

```<code>public interface IHtmlDownloader
{
    IWebProxy Proxy { get; set; }
    string UserAgent { get; set; }

    string GetHtml(string url)
}

public class HtmlDownloader : IHtmlDownloader
{
    WebClient _client;

    public IWebProxy Proxy
    {
        get { return _client.Proxy; }
        set { _client.Proxy = value; }
    }

    public string UserAgent
    {
        get
        { return _client.Headers[HttpRequestHeader.UserAgent].ToString(); }
        set
        { _client.Headers[HttpRequestHeader.UserAgent] = value; }
    }

    public HtmlDownloder()
    {
        _client = new WebClient();
    }

    public string GetHtml(string url)
    {
        this.CheckValidity(url);

        var htmlOfWebsite = _client.DownloadString(url);

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

Now I am not sure how exactly I should validate the URL. I know that it should not be null or whitespace or anything else, but should I validate that it is indeed a properly built URL?

Doing so would result in a method which would perform the validation. I could simply create a public static method inside HtmlDownloader so that the caller can validate the URL, or maybe even not a static one (GetUrl(string url) is after all called after the object has been instantiated), but it would be wrong for at least two reasons:

It would be a validator applicable in so many places, and it should be available to other classes.

I can't contract a static method with an interface.

Furthermore, it shouldn't be made static, but rather a service, so I could unit test HtmlDownloader (service would be injected through the constructor).

All of those ideas are quite dreadful and I am starting to think, that I shouldn't validate anything, but simply create a try/catch block that would catch the proper exception and then throw a UrlNotFoundException with the original exception supplied through InnerException.

Still, it would be nice to check for the validity of the URL. But to whom and how? Should the caller be injected with the proper service? But then, what if the URL is generated higher than the caller and the caller simply passes it on to the HtmlDownloader? Where should I validate the URL? Or is the simple fact that the URL have to passed through a few levels a code smell?

答: As much as possible try and make your classes as independent as possible during unit testing, keeping cross referencing of functions down to a minimum will help in debugging, after all unit testing is done you could then create standalone utility functions that can handle operations that will be cross referenced by your classes...</p>


问:
What is the role of QA in a BDD project?
If running a project using BDD with 100% coverage of user stories with automated acceptance tests, what would be the role of a tester / quality assurance person?

I guess I am imagining that developers would write the acceptance tests in conjunction with the product owner, let me know if that seems like a foolish assumption.

答:
Part of BDD is applying the 3 Amigos approach where the stakeholders collaborate to produce the acceptance criteria. QA/Dev can write the step code to make scenarios execute as acceptance tests. Where is the value of QA to execute manually the same acceptance tests that a BDD tool will execute automatically? The value add of QA is to validate those acceptance tests and perform manual exploratory testing outside the scripted acceptance tests. Duplication will usually yield the same result.

Developers don't rewrite requirements and specs, QA don't rewrite app code...it is possible for QA to not have to perform the very same scripted tests that developers execute as acceptance tests. It is time for Devs to wear some of the QA hat!


问:
Good design pattern for linq to sql
I currently have a linq to sql project that was used for one project and not much work was put into it, only the generated context and entities were used. Since then the project has started to become referenced in other projects and is growing rather quickly. My concern at first was duplicate code, for example:

```<code>using (DataContext dc = new DataContext())
{
    User myUser = dc.Users.Where(u => u.UserId == 1).SingleOrDefault();
}
</code>```

This could be used in my project, but also used in someone else's project. I don't want smelly projects...

Lately we have started implementing the repository design so we even have a single repository that can handle multiple entities, so now queries go to the repository rather than the data context directly.

We have implemented a generic repository with methods like All() and FindAll() etc... but my question is when we come to doing more complex things like creating a record that involves creating numerous different entities, does this go into the repository layer or do I need to start looking at another design pattern?

答:
A Save() method for a complex object would go into your Repository pattern interface. No, you don't necessarily need to use a different pattern.

A Repository should ideally abstract away all underlying storage (i.e. DB, memory collection, XML file etc) implementation detail from the object model that it works with. So if you are creating a complex object which has relationships between different entities, model this as a set of classes and write a method on your Repository to accept that type and do the dirty work of creating the classes in your physical storage device (whatever that may be).

Title: Good design pattern for linq to sql


问:
Getting your user agreement right
I'm planning to provide a little service with which you can control your computer from anywere. It exists out of a server (which I will be providing), and two clients (a controlled one and a controlling one). Now I want to provide that service for a little fee. However, the server is actually a small old Dell laptop with a broken screen at my home with Ubuntu as OS. It's not very reliable, but I want to use it, because it's cheep.

Now, as I said already, the laptop maybe isn't the most reliable machine, along with my Internet connection, which also can go down if there are some unexpected problems. But I don't want to take risks, and let the user, before he pays, know that this can occur. But I also want me to be safe, so I won't need to give any money back.

It is my first application that I will be giving away for a little fee, and I don't know about the legal responsibility I have to take. Basically I don't want to give any money back, even at a 100% downtime (which will be very unlikely), but I also don't want it to be my fault if someone loses data, by using my software, even if it is a bug, or someone intercepted his data.

So, I have put this in the agreement, and this only. Is it enough and is it legally binding?

What should I also know?

iControl actually implements a  client-server-client protocol, where  one client let's the other client execute a shell command. Then the    controlled client will return the  termination status, the standard    output, and the standard error of that command.

iControl uses no encryption to send    data over the network. It is a    potential security risk to use this    service, because all data is sent raw over the network. You can compare it   with the FTP protocol, the HTTP   protocol, which you're using right    now, and the telnet protocol.

iControl's maker does not in any way    stand in for the damage this  service    can do. Not by misuse by  the user,    not by a bug in the  software. No    illegal activities maybe done using    this service. The  provider of this    service may suspend you from his    service at any  time without an    explanation, without a money-back    guaranty. The  collector of the rent    fees does not  need, in any    circumstances, to  return the payed    money.

The iControl service is maintained by    one man and one man only. Any    downtime of the used server may     occur. In case of any length of    downtime, the service provider does  not have to give any money back,    however he'll do his best to make you  as happy as possible by trying to   make the service be up all of the    time.

I'm planning to let the user check a box that they read this and agreed to it, when they register. Is this enough?

答:
Disclaimer - I am not an attorney and this is not to be taken as legal advice. These are my opinions only and I accept no liability for them whatsoever.

While hiring an attorney is truly the best option, as a point of legal thought, these "Terms and Conditions" really don't form a contract.  In order for there to be a contract, there must be:

A bargained-for exchange (the parties must negotiate to an agreement)

Consideration (each party must give up something of value)

Intention to create a binding arrangement

So, it would be a valid contract if you provide the service in exchange for money, but you have one statement in there that arguably negates the third requirement:

The provider of this service may suspend you from his service at any time without an explanation, without a money-back guaranty [sic]. The collector of the rent fees does not need, in any circumstances, to return the payed money

That statement, in my opinion, makes the agreement an illusory promise made in bad faith. If someone pays you for a service, then you "suspend them" without reason, they really aren't paying you for anything and there is no intention to have an agreement.

A better option is to, in good faith, disclose your limitations and disclaim all liability, and you should also provide for a pro-rated refund should the service be unusable for any reason. You can do all of this without a lawyer, and I think you have a lot of legal precedent on your side should worst come to worst. In any circumstance, you need to have liability insurance, so if a legal action is brought against you, your insurance company will defend.

For further reading, this article by Forbes discusses additional software terms and conditions legal considerations.

Title: Getting your user agreement right


问:
What is Banana split and fusion in functional programming?
These terms got mentioned in my university course. Quick googling pointed me to some university papers, but I am looking for a simple explanation.</p>

答:
So this is actually a referenced to a paper by Meijer and a few others called "Functional Programming with Bananas, Lenses, Envelopes and Barbed Wire", the basic idea is that we can take any recursive data type, like say

```<code> data List = Cons Int List | Nil
</code>```

and we can factor out the recursion into a type variable

```<code> data ListF a = Cons Int a | Nil
</code>```

the reason why I appended that F is because this is now a functor! It also allows us to mimic lists, but with a twist: to build lists we have to nest the list type

```<code>type ThreeList = ListF (ListF (ListF Void)))
</code>```

To recover our original list we need to keep nesting this infinitely. That will give us a type ListFF where

```<code>  ListF ListFF == ListFF
</code>```

To do this define a "fixed point type"

```<code>  data Fix f = Fix {unfix :: f (Fix f)}
  type ListFF = Fix ListF
</code>```

As an exercise, you should verify this satisfies our above equation.Now we can finally define what bananas (catamorphisms) are!

```<code>  type ListAlg a = ListF a -> a
</code>```

ListAlgs are the type of "list algebras", and we can define a particular function

```<code>  cata :: ListAlg a -> ListFF -> a
  cata f = f . fmap (cata f) . unfix
</code>```

Further more

```<code>  cata :: ListAlg a -> ListFF -> a
  cata :: (Either () (Int, a) -> a) -> ListFF -> a
  cata :: (() -> a) -> ((Int, a) -> a) -> ListFF -> a
  cata :: a -> (Int -> a -> a) -> ListFF -> a
  cata :: (Int -> a -> a) -> a -> [Int] -> a
</code>```

Look familiar? cata is precisely the same as right folds!

What's really interesting is that we can do this over more than just lists, any type which is defined with this "fixed point of a functor" has a cata and to accomdate them all we just have to relax the type signature

```<code>  cata :: (f a -> a) -> Fix f -> a
</code>```

This is actually inspired from a piece of category theory which I wrote about, but this is the meat of the Haskell side.

Body:
So this is actually a referenced to a paper by Meijer and a few others called "Functional Programming with Bananas, Lenses, Envelopes and Barbed Wire", the basic idea is that we can take any recursive data type, like say

 data List = Cons Int List | Nil

and we can factor out the recursion into a type variable

 data ListF a = Cons Int a | Nil

the reason why I appended that F is because this is now a functor! It also allows us to mimic lists, but with a twist: to build lists we have to nest the list type

type ThreeList = ListF (ListF (ListF Void)))

To recover our original list we need to keep nesting this infinitely. That will give us a type ListFF where

  ListF ListFF == ListFF

To do this define a "fixed point type"

  data Fix f = Fix {unfix :: f (Fix f)}
  type ListFF = Fix ListF

As an exercise, you should verify this satisfies our above equation.Now we can finally define what bananas (catamorphisms) are!

  type ListAlg a = ListF a -> a

ListAlgs are the type of "list algebras", and we can define a particular function

  cata :: ListAlg a -> ListFF -> a
  cata f = f . fmap (cata f) . unfix

Further more

  cata :: ListAlg a -> ListFF -> a
  cata :: (Either () (Int, a) -> a) -> ListFF -> a
  cata :: (() -> a) -> ((Int, a) -> a) -> ListFF -> a
  cata :: a -> (Int -> a -> a) -> ListFF -> a
  cata :: (Int -> a -> a) -> a -> [Int] -> a

Look familiar? cata is precisely the same as right folds!

What's really interesting is that we can do this over more than just lists, any type which is defined with this "fixed point of a functor" has a cata and to accomdate them all we just have to relax the type signature

  cata :: (f a -> a) -> Fix f -> a

This is actually inspired from a piece of category theory which I wrote about, but this is the meat of the Haskell side.


问:
QA and Feature Branches in Web Development
I am trying to introduce to my team a more sophisticated branching model than "commit to master and push".

We are a small team of two analysts, three developers and one tester. At the moment, a developer will commit their changes to master, then build the master branch on our test environment. They will then notify the tester that the changes are available to test.

My proposed workflow is based on this, with GitHub enabling code reviews via pull-requests on merging feature branches. Each feature or bug has its own branch created, on which the work is done. When the developer is finished they request a merge and their code is reviewed and then merged into the dev branch.

My question is this: At what point during the new process is it appropriate to ask the tester to test the functionality? As I see it, the options are:

The tester tests the functionality after the code has been reviewed and the branch has been merged into dev

Pro - the review hopefully caught some bugs and saved the tester from rejecting the work

Con - the team has to wait until someone does the review before the tester can sign it off

Or, the tester tests the functionality before the code has been reviewed

Pro - the tester is able to test and sign off the work before the code is reviewed

Con - if any changes are suggested, the tester will need to re-test the changed code

There is also the question of how the tester would be able to access the feature branch before it is merged. We use TeamCity as a deployment tool, and can specify a branch name to build - but I am concerned that it won't be clear which feature branch is currently 'active' on our test server.

So really this boils down to: when should the tester do their testing, and if it is before the branch has been merged, how should that situation be dealt with?

答: If you really believe in code reviews, then coding isn't finished until the review-revise-repeat loop exits.  Until then, the code is in a sequence of preliminary forms, not its final form.  Your tester could test one or more preliminary versions of the code, but the tests ought to be repeated from the beginning on the final code.  Good testing practice certainly would not allow a sign-off on code that still needed to be revised.


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

This is what we currently have:

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

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

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

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

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

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

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

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

Are there any reasons not to?

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

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

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

Are there any reasons not to?

The answer to this question depends on whether you want to allow the client to change the ID?

If the client can change the ID, via a PUT, then the URI for the resource will change, and you should provide a 301 Moved Permanently any time a resource accesses the old URI.

So for example you start with a resource at

```<code>/users/123
</code>```

and the client PUTs the following onto the resource

```<code>{id: 222, name: "Adrian"}
</code>```

the resource has been updated and its URI is now

```<code>/users/222
</code>```

The Location field in the PUT response should contain the new URI, and if you go to /users/123 you should get a 301 response with the Location field pointing to the new /users/222 resource.

In most cases though you don't actually want the client to be able to change the ID, as this can get pretty messy pretty quickly. In that case the ID is something only the server can change, and you should leave it out of the PUT body, as the client cannot update this state.

If you PUT a require to a different URI on the same resource, say

```<code>/users/adian_lync
</code>```

then if that resource does not exist the server should create it and create and ID when it is doing it

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

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

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

Are there any reasons not to?

The answer to this question depends on whether you want to allow the client to change the ID?

If the client can change the ID, via a PUT, then the URI for the resource will change, and you should provide a 301 Moved Permanently any time a resource accesses the old URI.

So for example you start with a resource at

/users/123

and the client PUTs the following onto the resource

{id: 222, name: "Adrian"}

the resource has been updated and its URI is now

/users/222

The Location field in the PUT response should contain the new URI, and if you go to /users/123 you should get a 301 response with the Location field pointing to the new /users/222 resource.

In most cases though you don't actually want the client to be able to change the ID, as this can get pretty messy pretty quickly. In that case the ID is something only the server can change, and you should leave it out of the PUT body, as the client cannot update this state.

If you PUT a require to a different URI on the same resource, say

/users/adian_lync

then if that resource does not exist the server should create it and create and ID when it is doing it


问:
Dealing with Users and User-Owned Data in an API
I have a question about the way I am architecting an API.

Structure

My API structure so far is like so (there is about 10 classes total, but many are similar, so I've reduced to these classes, and removed fields that are not relevant to the question):

Profile

id (unique identifier for this Profile)

Allergies

X-Rays

Allergies

id (unique ID for this allergy)

Profile (this points back to the Profile that owns these allergies)

name (what they are allergic to)

X-Rays

id (unique ID for this X-Ray)

Profile (points back to the Profile that owns these X-Rays)

thumbnail (a compressed version of the X-Ray image)

fullImage (the full, uncompressed X-Ray image)

Use Cases

Profiles are sent down the wire in full, except that in the X-Rays class, the thumbnail is sent instead of the full image. When the user wishes to see the full X-Ray image, then they make another call to download the full image (this is done to save bandwidth, it's possible that a user has 100 X-Rays at 10MB each!).

A user can make modifications to Allergies or X-Rays, and these changes would have to be sent back to the server. It'd be wasteful to send the entire Profile object back, so I'd like to send just the individual X-Ray or Allergies object back to the server.

Concerns

What should my API return (the response format will be JSON) when a user downloads a full profile?

```<code>{
  "Profile": {
    "id": "1234",
    "Allergies": {
      "id": "5678",
      "Profile": {
        "What goes here? This is a circular reference!
         I need to include a reference back to the profile
         so I can edit this Allergy client side and push the changes.
         Maybe it should be the User ID of the profile,
         but I'm not so sure that is a good idea"
      },
      "name": "peanuts"
    },
    "X-Rays": {
      "id": "3456",
      "Profile"{
          ...
      },
      "thumbnail": "Base 64 encode of the thumbnail image"
    }
  }
}
</code>```

答:
It looks like you are confusing your underlying model objects with your API resources, they are not necessarily mutually exclusive. If you are simply serializing your classes as JSON, you going to duplicate content (and get the profile appearing several times) which is not needed and a smell.

You could:

Create specific resource models that represent your resources better (kind of like View Models in a MVC Framework). So you could create model objects such as PatientResource, XRayResource and a AllergyResource (you don't have to suffix the name Resource here, they could just sit somewhere separately to your other models).  that better represent what your clients need to consume instead of every property of the domain model.

c# here:

```<code>public class PatientResource
{
    public int Id { get; set; }
    public IEnumerable<AllergyResource> Allergies { get; set; }
    public IEnumerable<XrayResource> XRays { get; set; }
}

public class AllergyResource
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ProfileId { get; set; }
}

public class XrayResource
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ProfileId { get; set; }
}
</code>```

All very basic, the allergy and xray resource do not hold profile objects, they hold a reference id for a profile, even that would look slightly out of place, so you may need to restrict some properties depending on where your data is consumed, for example, do you really need to show an profileId if you are representing an AllergyResource in the AllergyResource collection of a PatientResource, probably not, so for that serialization you would omit that property.  However, if you were in a standalone AllergyResource you would probably like to show the reference.

I like to use links in my API's

I don't really know what flavour of API you are creating (RESTFul, RPC, HATEOS etc) so this may not apply.  I mainly deal with REST style (some may not be REST in the truest sense of the word) but when i am building an API i like to be a succinct as possible with my response objects but give the clients the ability to discover linked resources via links.  This can be as complicated or simple as you like, you can use JSON or a more specific media type like HAL+JSON but the point is, you send your resources down the wire, and you enable the discover-ability of related resources via standard HTTP links.

BasecampX as an example: where they have a person, but the todo list is available at another resource endpoint which is specified in response.  The objects are simplified but it does make calling the API more verbose in that multiple requests are required.  It really depends on how your clients will consume the data and work with it.

Body:
It looks like you are confusing your underlying model objects with your API resources, they are not necessarily mutually exclusive. If you are simply serializing your classes as JSON, you going to duplicate content (and get the profile appearing several times) which is not needed and a smell.

You could:

Create specific resource models that represent your resources better (kind of like View Models in a MVC Framework). So you could create model objects such as PatientResource, XRayResource and a AllergyResource (you don't have to suffix the name Resource here, they could just sit somewhere separately to your other models).  that better represent what your clients need to consume instead of every property of the domain model.

c# here:

public class PatientResource
{
    public int Id { get; set; }
    public IEnumerable<AllergyResource> Allergies { get; set; }
    public IEnumerable<XrayResource> XRays { get; set; }
}

public class AllergyResource
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ProfileId { get; set; }
}

public class XrayResource
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ProfileId { get; set; }
}

All very basic, the allergy and xray resource do not hold profile objects, they hold a reference id for a profile, even that would look slightly out of place, so you may need to restrict some properties depending on where your data is consumed, for example, do you really need to show an profileId if you are representing an AllergyResource in the AllergyResource collection of a PatientResource, probably not, so for that serialization you would omit that property.  However, if you were in a standalone AllergyResource you would probably like to show the reference.

I like to use links in my API's

I don't really know what flavour of API you are creating (RESTFul, RPC, HATEOS etc) so this may not apply.  I mainly deal with REST style (some may not be REST in the truest sense of the word) but when i am building an API i like to be a succinct as possible with my response objects but give the clients the ability to discover linked resources via links.  This can be as complicated or simple as you like, you can use JSON or a more specific media type like HAL+JSON but the point is, you send your resources down the wire, and you enable the discover-ability of related resources via standard HTTP links.

BasecampX as an example: where they have a person, but the todo list is available at another resource endpoint which is specified in response.  The objects are simplified but it does make calling the API more verbose in that multiple requests are required.  It really depends on how your clients will consume the data and work with it.


问:
Creating entities with validated Addresses via REST API
I am building a REST service. This services enables the user to create an entity that has an Address. For simplification, let say this other entity is 'House', so 'A House has an Address'.

The system has to geocode every House so along with the Address, a House must have latitude/longitude at the moment of being created, but those are not requested to the user.

The user will be asked to enter an Address. From this address the system will try to retrieve latitude/longitude using a third party service. This service will return the best match for the address entered by the user, so sometimes it will return a different address (e.g could happen that there is two different streets with the same name in different cities and the services could return information regarding the wrong one).

I have to make sure that the address I am storing with the House is the one the user wanted, so the workflow for the user would be something like this:

The user wants to create a new House.

The user Enter an address.

The user sees the best match for that address in a map.

The user confirms that the address is OK.

The system saves the House with the address and the lat/long retrieved from the service.

Approach 1

The entities model would be:

House has an Address

Address has a Coordinates (lat/long)

and I would have an endpoint for POST addresses and another for POST houses. The workflow would be:

The user wants to create a new House.

The user Enter an address and make a POST to the addresses endpoint.

The system retrieves the lat/long for the best match.

The system saves the address retrieved by the geocoding service in the DB. Note that it can be different from the address the user entered.

As a response to the POST request, the system returns the address that have saved and show it to the user.

The user confirms that the address is OK.

The system makes a POST to the houses endpoint with the ID for the address that has been created before, so in DB the house will be linked to the address that was created before.

With this approach, if the user doesn't accept the address provided, I would end up with some 'orphan' addresses (addresses that are not linked to any House). I would need to make a periodic clean on the DB for those addresses.

Approach 2

In this approach, I would have an endpoint /validate-address, so the user would POST an address, and the system would returns the best match. Nothing would be created in the DB at this point. The user then would accept the returned address and would make a POST to /houses with the information of the house and the address.

With this approach, I cannot assure that all the Address in the DB are correctly geocoded as some user could make a POST to /houses without a previous call to /validate-address.

Also, it doesn't seem quite right from a REST perspective to have a POST /validate-address request that doesn't create anything on the DB.

What would be the best approach to this situation? Can you see an alternative approach to this two? Any feedback would be appreciated.

答:
This answer expands on toniedzwiedz comments, so anyone else read them as well.

So reading through the question it becomes clear that you do not trust the user's description of the address, but you DO trust the user's description of the geo-code id of the address.

That is to say the user is not the authority of the address format for the house, the geo-code database is the authority. But the is the authority of which geo-code address ID is mapped to the house.

So when the user tells the system "This is the address of the house" what they are really saying is "This is the geo-code address ID of the house".

In that case the flow is

User creates a house by POSTing to /users/123/houses

User creates address of house by PUTting address geo-code ID to /users/123/houses/1/address

How does the user get the geo-code ID? As toniedzwiedz says they can query that independently to the flow. You can have an end point that simply returns geo-code ids for addresses

```<code>GET /geo-codes?address=1600 Pennsylvania Ave NW

{
    "matches": [
    {
        "geo-id":122,
        "address": "1600 Pennsylvania Ave NW, Washington, D.C., United States"
    },
    {
        "geo-id":9837,
        "address": "1600 Pennsylvania Ave, Sweden,"
    }]
}
</code>```

The user then PUTs the geo-id to the URI /users/123/houses/1/address.

Body:
This answer expands on toniedzwiedz comments, so anyone else read them as well.

So reading through the question it becomes clear that you do not trust the user's description of the address, but you DO trust the user's description of the geo-code id of the address.

That is to say the user is not the authority of the address format for the house, the geo-code database is the authority. But the is the authority of which geo-code address ID is mapped to the house.

So when the user tells the system "This is the address of the house" what they are really saying is "This is the geo-code address ID of the house".

In that case the flow is

User creates a house by POSTing to /users/123/houses

User creates address of house by PUTting address geo-code ID to /users/123/houses/1/address

How does the user get the geo-code ID? As toniedzwiedz says they can query that independently to the flow. You can have an end point that simply returns geo-code ids for addresses

GET /geo-codes?address=1600 Pennsylvania Ave NW

{
    "matches": [
    {
        "geo-id":122,
        "address": "1600 Pennsylvania Ave NW, Washington, D.C., United States"
    },
    {
        "geo-id":9837,
        "address": "1600 Pennsylvania Ave, Sweden,"
    }]
}

The user then PUTs the geo-id to the URI /users/123/houses/1/address.


答:
This question is actually about exceptions. If you look at it that way and ignore the empty collection as an implementation detail, the answer is straightforward:

1) A method should throw an exception when it can't proceed: either unable to do the designated task, or return the appropriaate value.

2) A method should catch an exception when it is able to proceed despite the failure.

So, your helper method should not be "helpful" and throw an exception unless it is unable to do it's job with an empty collection.  Let the caller determine whether the results can be handled.

Whether it returns an empty collection or null, is a bit more difficult but not much: nullable collections should be avoided if possible.   The purpose of a nullable collection would be to indicate (as in SQL) that you don't have the information -- a collection of children for example might be null if you don't know if someone has any, but you don't know that they don't.  But if that is important for some reason, it's probably worth an extra variable to track it.

Title: Should I accept empty collections in my methods that iterate over them?

Body:
I have a method where all logic is performed inside a foreach loop that iterates over the method's parameter:

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

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

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

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


问:
Is console logging inappropriate for chatty applications?
12 Factor states that applications should log to the console, those console logs should should be unbuffered, and the logs should be redirected to someplace useful (file, database, whatever).

But writing unbuffered data to anywhere is extremely slow.

Does this mean that 12 Factor is inappropriate when an application is doing a lot of logging (for example, due to regulatory requirements)?

答:
I believe you misunderstood the recommendations for logging.

The 12 Factor site states

A twelve-factor app never concerns itself with routing or storage of its output stream. It should not attempt to write to or manage logfiles. Instead, each running process writes its event stream, unbuffered, to stdout. During local development, the developer will view this stream in the foreground of their terminal to observe the app’s behavior.

Unless you configure your environment otherwise, stdout will be buffered. Specifically, the runtime environment standard performs line-buffering on stdout.

What I believe is meant by 12 Factors is that the application should not concern itself with this buffering and particularly not implement additional buffering above what the environment does for you.


问:
Kafka, is it possible to get the message offset after producing?
While using Apache Kafka, is it possible to get the offset of the message that has been produced?

From the Kafka documentation page it says:

each message in the partition are assigned a unique sequential id/number called Offset

Now suppose when I am producing any message I want to retrieve the offset that has been assigned to it.

答:
The producer response protocol provides the offset of the first message sent in the messageset. Provided the API/Implementation you're using exposes this information, you should be able to retrieve it from the response to producing your message.
More here:
https://cwiki.apache.org/confluence/display/KAFKA/A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol-ProduceResponse</p>


问:
Should access logic go in controllers?
I want to know if all the logic related to permissions and access control belongs to controllers (Application logic) or models (Business logic).

Currently I have a controller that does something like that:

```<code>function delete (resource) {
   if (resource.belongsTo (currentUser) {
       resource.delete ();
   }
   else {
       throw Exception ("you can't do this");
   }
}
</code>```

Is this kind of logic application logic or business logic?

PS. I already read Where to put business logic in MVC design?, but I still have doubts

答:
It is helpful to distinguish two types of access control:

Vertical - functions that some users can access and some users cannot. For example, anyone can view the home page, but only admin can ban a user.

Horizonal - functions that multiple users can access, but the data is segregated. For example, everyone can access "inbox" - but they see only their own messages, not other people's.

Vertical access control is almost always enforced at the controller layer.

Most applications also enforce horizontal access control at the controller layer. This works, but there is a disadvantage: access checks need to be repeated in multiple places, which invites mistakes. Complex applications need a lot of checks to properly enforce horizontal access control.

But there is an alternative: perform horizontal access control in the model. This tends to reduce the number of checks needed - e.g. you have an access control check on the Email object, rather that 15 separate checks in controller methods that access the object. One criticism of this approach is that is requires the model to be identity-aware, which could be unwanted coupling between model and controller. However, I think it's worth it. I've written more about this topic on my website.

Title: Should access logic go in controllers?


问:
In an MVC, should models use libraries, or should libraries use models?
When I build a RESTful API, I use an MVC pattern. And in order to make controllers skinny and code reusable outside of the API (e.g. in Cron tasks), I put much of my code into services (commonly known as libraries).

My routers delegate to controllers which then delegate to services, which use models.

I am wondering: Does it make sense for services to use models? So

```<code>router > controller > services > models
</code>```

Or, should models use services? So

```<code>router > controller > models > services
</code>```

答:
It helps to make a distinction between:

Helpers - support code that is not aware of your model, e.g. date formatting.

Services - support code that is aware of your model, e.g. bills credit card, updates user record, sends user email

I'm not quite sure which of these you mean by "library". Anyway, following your terminology,  I suggest this chain:

```<code>router > controller > services > models
</code>```

The service layer is optional: for simple operations the controller can call the model directly. And anything can call a helper.

To refine your terminology a bit more, you can modularise the model.

Body:
It helps to make a distinction between:

Helpers - support code that is not aware of your model, e.g. date formatting.

Services - support code that is aware of your model, e.g. bills credit card, updates user record, sends user email

I'm not quite sure which of these you mean by "library". Anyway, following your terminology,  I suggest this chain:

router > controller > services > models

The service layer is optional: for simple operations the controller can call the model directly. And anything can call a helper.

To refine your terminology a bit more, you can modularise the model.


问:
Async properties in interfaces to cater for the possibility of expensive first-time evaluation: Is this a good idea?
First of all, sorry if this post is too long. I'll start with the…

Short version:

Is it generally advisable or a good idea to design an interface property as asynchronous simply because we cannot be sure whether each and every implementation can guarantee that it's evaluation will be cheap? That is, can it be a good idea to design an interface like this:

```<code>interface IFoo
{
    Task<IEnumerable<Bar>> BarsAsync { get; }
}
</code>```

instead of like this:

```<code>interface IFoo
{
    IEnumerable<Bar> Bars { get; }
}
</code>```

Long version:

Now let me explain how I arrived at this design question.

Let's start with the non-asynchronous version of the interface (shown right above).

Microsoft's framework design guidelines demand that getting the value of a property be cheap; but when we program against an interface, instead of against a particular implementation of IFoo, we cannot be certain that each and every implementation of IFoo that we might be using can and will adhere to that guideline.

What each and every implementation could do is to ensure "amortized cheapness", i.e. cache the property's value upon its first computation, so that at least subsequent accesses will be cheap. Eric Lippert writes in his blog article "When should I write a property?":

A common pattern is for a property to be a cache of an expensive, lazily-computed value […]. Though the property is expensive on its first access, every subsequent access is cheap, so the property is cheap in an amortized sense.

He goes on to suggest using Lazy<T> as an implementation detail towards that end, so let's look at a possible implementation of the above interface where evaluating Bars for the first time would be expensive, but not on subsequent calls:

```<code>internal class ExpensiveFoo : IFoo
{
    private readonly Lazy<IEnumerable<Bar>> bars;
    public IEnumerable<Bar> Bars { get { return bars.Value; } }
    public ExpensiveFoo() { bars = new Lazy<IEnumerable<Bar>>(GetBars); }
    private IEnumerable<Bar> GetBars() { … /* some expensive computation */ }
}
</code>```

What I am wondering at this point is, wouldn't it be better to simply leak the possibility of an expensive first-time evaluation into the interface and change it to:

```<code>interface IFoo
{
    Task<IEnumerable<Bar>> BarsAsync { get; }
}
</code>```

This would allow you to write both "always cheap" implementations as well as "amortized-cheap" implementations (like the above), with the consumer being aware of that fact.

```<code>internal class ExpensiveFoo : IFoo
{
    private Lazy<Task<IEnumerable<Bar>>> bars;
    public Task<IEnumerable<Bar>> BarsAsync { get { return bars.Value; } }
    public ExpensiveFoo() { bars = new Lazy<Task<IEnumerable<Bar>>>(GetBarsAsync); }
    private async Task<IEnumerable<Bar>> GetBarsAsync() { … };
}

internal class CheapFoo : IFoo
{
    public Task<IEnumerable<Bar>> BarsAsync { get { return Task.FromResult(bars) } }
    private IEnumerable<Bar> bars;
    public CheapFoo(IEnumerable<Bar> bars) { this.bars = bars; }
}
</code>```

No matter which implementation gets used, one could then write code that potentially doesn't block even on the first property access:

```<code>Foo foo = …;
foreach (Bar bar in await foo.BarsAsync) …
</code>```

Is this ever a good idea?

答:
One of the reasons properties should never be "fancy" in terms of implementation, is they typically contain code that is executed in the debugger, in the watch windows and other places where variables can be viewed, such as tool tips. Methods are only executed on demand.

Some types of "fancy" properties:

Those that allocate memory when computing their value.

Those that do not return in constant time.

Those that return in constant time, but it is a "long" time (greater than a few milliseconds)

Those that have side effects: some argue this can be ok if the side effect is to initialize a field lazily. But even this can cause different behavior when attaching a debugger.


答:
When you say, a user has a house; and each house has adress data, that means in reverse: no address without a house - which makes by the way no sense. From that the procedure should be clear:

Usecase: Creation of house

1) User enters all relevant data

2) A GET-Request is sent to a geocode-Service, which returns possible addresses

3) Only after the user entered valid data / accepted one data-set from the geocode-Service a POST-Request with the complete data (house-data and address) is made to /houses: since you are creating a new house-ressource. POST ing to /user/{id}/houses is also a possibility; the stress is then (semantically) on the user. I prefer the first variant. The relation belongs to user {id} is an attribute of the house.

4) When the house-ressource is created the new ressource is returned (you get the idea):

```<code>{
    "name": "Casa di falcone",
    "id": "123",
    "links": [
        {
            "rel": "self",
            "href": "http://www.example.com/houses/123"
        },
        {
            "rel": "users",
            "href": "http://www.example.com/users/1"
        },
        {
            "rel": "addresses",
            "href": "http://www.example.com/addresses/27/"
        }
    ],
    "address": {
        "id": "27",
        "links": [
            {
                "rel": "self",
                "href": "http://www.example.com/addresses/27"
            },
            {
                "rel": "houses",
                "href": "http://www.example.com/houses?address=27"
            },
            {
                "rel": "users",
                "href": "http://www.example.com/users?address=27"
            }
        ]
    },
        "user": {
        "id": "1",
        "links": [
            {
                "rel": "self",
                "href": "http://www.example.com/users/1"
            },
            {
                "rel": "houses",
                "href": "http://www.example.com/houses?user=1"
            },
            {
                "rel": "addresses",
                "href": "http://www.example.com/addresses?user=1"
            }
        ]
    }
}
</code>```

Implicitely there was an address generated and its id is embedded in the result. Of course adress and house are in your model two different things/ressources, but it makes no sense to handle them separately.

Title: Creating entities with validated Addresses via REST API

Body:
I am building a REST service. This services enables the user to create an entity that has an Address. For simplification, let say this other entity is 'House', so 'A House has an Address'.

The system has to geocode every House so along with the Address, a House must have latitude/longitude at the moment of being created, but those are not requested to the user.

The user will be asked to enter an Address. From this address the system will try to retrieve latitude/longitude using a third party service. This service will return the best match for the address entered by the user, so sometimes it will return a different address (e.g could happen that there is two different streets with the same name in different cities and the services could return information regarding the wrong one).

I have to make sure that the address I am storing with the House is the one the user wanted, so the workflow for the user would be something like this:

The user wants to create a new House.

The user Enter an address.

The user sees the best match for that address in a map.

The user confirms that the address is OK.

The system saves the House with the address and the lat/long retrieved from the service.

Approach 1

The entities model would be:

House has an Address

Address has a Coordinates (lat/long)

and I would have an endpoint for POST addresses and another for POST houses. The workflow would be:

The user wants to create a new House.

The user Enter an address and make a POST to the addresses endpoint.

The system retrieves the lat/long for the best match.

The system saves the address retrieved by the geocoding service in the DB. Note that it can be different from the address the user entered.

As a response to the POST request, the system returns the address that have saved and show it to the user.

The user confirms that the address is OK.

The system makes a POST to the houses endpoint with the ID for the address that has been created before, so in DB the house will be linked to the address that was created before.

With this approach, if the user doesn't accept the address provided, I would end up with some 'orphan' addresses (addresses that are not linked to any House). I would need to make a periodic clean on the DB for those addresses.

Approach 2

In this approach, I would have an endpoint /validate-address, so the user would POST an address, and the system would returns the best match. Nothing would be created in the DB at this point. The user then would accept the returned address and would make a POST to /houses with the information of the house and the address.

With this approach, I cannot assure that all the Address in the DB are correctly geocoded as some user could make a POST to /houses without a previous call to /validate-address.

Also, it doesn't seem quite right from a REST perspective to have a POST /validate-address request that doesn't create anything on the DB.

What would be the best approach to this situation? Can you see an alternative approach to this two? Any feedback would be appreciated.

Body:
When you say, a user has a house; and each house has adress data, that means in reverse: no address without a house - which makes by the way no sense. From that the procedure should be clear:

Usecase: Creation of house

1) User enters all relevant data

2) A GET-Request is sent to a geocode-Service, which returns possible addresses

3) Only after the user entered valid data / accepted one data-set from the geocode-Service a POST-Request with the complete data (house-data and address) is made to /houses: since you are creating a new house-ressource. POST ing to /user/{id}/houses is also a possibility; the stress is then (semantically) on the user. I prefer the first variant. The relation belongs to user {id} is an attribute of the house.

4) When the house-ressource is created the new ressource is returned (you get the idea):

{
    "name": "Casa di falcone",
    "id": "123",
    "links": [
        {
            "rel": "self",
            "href": "http://www.example.com/houses/123"
        },
        {
            "rel": "users",
            "href": "http://www.example.com/users/1"
        },
        {
            "rel": "addresses",
            "href": "http://www.example.com/addresses/27/"
        }
    ],
    "address": {
        "id": "27",
        "links": [
            {
                "rel": "self",
                "href": "http://www.example.com/addresses/27"
            },
            {
                "rel": "houses",
                "href": "http://www.example.com/houses?address=27"
            },
            {
                "rel": "users",
                "href": "http://www.example.com/users?address=27"
            }
        ]
    },
        "user": {
        "id": "1",
        "links": [
            {
                "rel": "self",
                "href": "http://www.example.com/users/1"
            },
            {
                "rel": "houses",
                "href": "http://www.example.com/houses?user=1"
            },
            {
                "rel": "addresses",
                "href": "http://www.example.com/addresses?user=1"
            }
        ]
    }
}

Implicitely there was an address generated and its id is embedded in the result. Of course adress and house are in your model two different things/ressources, but it makes no sense to handle them separately.


问:
can you have too many dto/bo - mapping method
I have a windows service, 2 web services and a web interface that need to follow the same path (data wise).

So I came up with two ways of creating my solution.

My concern is the fact that the UI/WS/etc will have their own kind of DTO (let's say the model in ASP.Net MVC) that should be mapped to a DTO so the SL can then map it to a BO then mapping it to the proper EF6 DTO so that I can save it in a database.

So I'm thinking of doing it this way

to remove one level of mapping.

Which one should I take? Or is there a 3rd solution?

答:
I wrote an implementation of an enterprise service bus. We have a customer-facing web service API, a web service that drives the web-based user interface, at least a dozen different windows services that run on client machines, a half-dozen services that run on servers, along with three different databases (Couchbase, Elasticsearch, SQL).

I made the decision up front to create a "core" library which is essentially nothing but simple objects and utility code. This contains the objects and messages that get passed around the application. I then have another set of similar libraries for the client-side and server-side services.  Finally, I have my web service libraries, where either they pass simple objects from the core, or I have created endpoint-specific input/output classes for each web method, which are promptly converted into "core" classes so they can be moved around the application.

The advantage to this is that I have a write-once, use anywhere architecture which is extremely efficient. It is easy to promote and demote classes into the core when necessary. The drawback is that if you have multiple solutions in Visual Studio, any sort of refactoring really requires all projects in existence to be open so you can accomplish the renaming without introducing compiler errors.  In the end, if I had to do this over again, I would do the same thing. It really has been a good structure for me.


问:
if a c# interface contain only getter and setter definition, is it a code smell?
A project that I am working on has the following code for interface
example:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    public interface IDeviceEssentials
    {
        string Model { get; set; }
        string Manufacturer { get; set; }
        string BIOSVersion { get; set; }
        string TotalPhysicalMemory { get; set; }
        string TotalVirtualmemory { get; set; }
        string OSName { get; set; }
    }
}
</code>```

every other class implementing this interface uses Automatic properties which renders the getters and setters useless so the effective implementation is reduced to

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    public interface IDeviceEssentials
    {
        string Model;
        string Manufacturer;
        string BIOSVersion;
        string TotalPhysicalMemory;
        string TotalVirtualmemory;
        string OSName;
    }
}
</code>```

For which simply a structure or class is enough to hold the data..

The main usage of interface is polymorphism making use of liskov substitution, even though the above code is using the getter setter it is effectively reduced to variable decleration by all the classes implementing it (by using automatic property). That is there is no need i want to mock the above interface. even if it is designed as a class I can simply mock by creating new class of it.

Question are :-

I think the above properties are providing data representation only. is it ok to use interface only for data representation?

答:
This interface is perfectly fine.  I often see this kind of interface used on an object that's responsible for data storage, to hide the data storage code from the consumer.

As long as you follow SOLID principles in your class design, it really doesn't matter what your interfaces define.

Is the class behind this interface only responsible for one thing?

Is it open for extension and closed for modification?

Does it follow the Liskov Substitution principle?

Does it follow the interface segregation principle?

Does it follow the dependency inversion principle?

If you can answer yes to each of these questions then your class design should be ok.  The interface then becomes almost a by-product of this thought process.


问:
Advanced subversion techniques, what am I missing?
I started using SVN about 9 months ago and it's been a game changer to say the least.  Although, I feel I'm still a bit lost.  I feel like there is a lot more I need to take advantage of to really step up my application development.

For example

I would like to be able to quarantine any volatile/major changes into some kind of 'sub-repository' or something.  I'm finding that major changes are impeding minor bug fixes that are quite urgent.  How can I push one simple update without pushing incomplete or broken code?

答:
The current size of my working copy is 10GB, with more than 50.000 files.  I can have several copies for different branches, but it takes a while just to create the new copy!

When an urgent bug comes, I usually save all my changes in a patch, revert everything, work on the bug and commit, then apply the patch I saved...  Much easier and quicker than getting a fresh working copy.  If I would need to do this often, I would have two working copies: one for long-term changes, the other for bug fixes.

ContentLicense: CC BY-SA 2.5


答:
No it isn't a code smell in itself. Having many implementations using only auto properties is a code smell - this is where you refactor common code into a base class and define it as virtual so that the extending class can override it where necessary.

every other class implementing this interface uses Automatic properties which renders the getters and setters useless

No, automatic properties do not render the interface definition useless. Your two illustrated interfaces are not the same - in fact the second one is illegal as you cannot define a field in an interface. Automatic properties still use getters and setters (they're inserted by the compiler), so using automatic properties satisfies the requirements of the interface. Simply declaring the field public string Model; in your implementation does not satisfy the interface.

You'll see from the following image that even though I used automatic properties in the implementation there are still getters and setters implemented for me:

If that still makes no sense, think of it this way: the interface defines a contract. If I later refactor my implementation so that I don't use auto properties then the interface guarantees that I expose both a getter and setter. Consuming code uses my implementation via its interface, not directly accessing the concrete implementation. This means I can refactor the implementation and the caller doesn't have to change at all.

Title: if a c# interface contain only getter and setter definition, is it a code smell?

Body:
A project that I am working on has the following code for interface
example:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    public interface IDeviceEssentials
    {
        string Model { get; set; }
        string Manufacturer { get; set; }
        string BIOSVersion { get; set; }
        string TotalPhysicalMemory { get; set; }
        string TotalVirtualmemory { get; set; }
        string OSName { get; set; }
    }
}
</code>```

every other class implementing this interface uses Automatic properties which renders the getters and setters useless so the effective implementation is reduced to

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    public interface IDeviceEssentials
    {
        string Model;
        string Manufacturer;
        string BIOSVersion;
        string TotalPhysicalMemory;
        string TotalVirtualmemory;
        string OSName;
    }
}
</code>```

For which simply a structure or class is enough to hold the data..

The main usage of interface is polymorphism making use of liskov substitution, even though the above code is using the getter setter it is effectively reduced to variable decleration by all the classes implementing it (by using automatic property). That is there is no need i want to mock the above interface. even if it is designed as a class I can simply mock by creating new class of it.

Question are :-

I think the above properties are providing data representation only. is it ok to use interface only for data representation?


问:
Do we still need manual code review if we use sonarqube code review tools
We were using git gerrit for manual code review . but recently we are planning to integrate sonarqube in our Jenkins  integration server. Do we still need manual code review? Or we can stop manual code review and sonarqube is enough. I would appreciate if you share your experience with sonarqube.</p>

答:
Yes, you should keep code reviews.

SonarQube, like any other automated tool, is great as a tool which helps pointing out some of the possible problems, including problems which are not easily seen by humans.

Duplicate code, for example, can be checked automatically, as shown by Visual Studio or SonarQube, while a reviewer may not easily see that the same piece of code was copy-pasted and slightly modified afterwards.

In the same way, style checking can and should be automated, because an automated checker will perform better than an human. Static analysis is another great example.

But then, there are issues which can hardly be automated. For example, would an automated tool find something wrong in this JavaScript code?

// The price should be incremented when a rebate is available.
if (this.rebates.findFor(this.customer, this.product)) {
    this.customPrice -= this.computeRebate(this.customer);
}
```

<p>On the other hand, any reviewer will immediately find two issues:</p>

<ul>
<li>The comment is plainly wrong and misleading. We are not incrementing the price.</li>
<li>Even if it were correct, the comment remains useless. If the two lines of code are not clear in the context, a minor refactoring can make it explicit enough to be able to get rid of the comment.</li>
</ul>

<p>Another benefit of code reviews is the <strong>ability to teach junior programmers</strong>. For example, an automated checker will find this piece of C# code written by a beginner programmer correct:</p>

<pre class="lang-cs prettyprint-override"><code>var result = new List<Day>();
foreach (var day in days)
{
    if (day.HasAppointment)
    {
        result.Add(day);
    }
}

return result;
</code>```

while any more experienced developer will suggest rewriting it like this:

return days.Where(day => day.HasAppointment);
```

Even if an automated tool will do such suggestions (after all, it is possible to programmatically detect procedural code which can be rewritten using functional style), would this tool be able to explain to the beginner programmer the caveats of such rewrite (lazy evaluation)?

Body:
Yes, you should keep code reviews.

SonarQube, like any other automated tool, is great as a tool which helps pointing out some of the possible problems, including problems which are not easily seen by humans.

Duplicate code, for example, can be checked automatically, as shown by Visual Studio or SonarQube, while a reviewer may not easily see that the same piece of code was copy-pasted and slightly modified afterwards.

In the same way, style checking can and should be automated, because an automated checker will perform better than an human. Static analysis is another great example.

But then, there are issues which can hardly be automated. For example, would an automated tool find something wrong in this JavaScript code?

// The price should be incremented when a rebate is available.
if (this.rebates.findFor(this.customer, this.product)) {
    this.customPrice -= this.computeRebate(this.customer);
}

On the other hand, any reviewer will immediately find two issues:

The comment is plainly wrong and misleading. We are not incrementing the price.

Even if it were correct, the comment remains useless. If the two lines of code are not clear in the context, a minor refactoring can make it explicit enough to be able to get rid of the comment.

Another benefit of code reviews is the ability to teach junior programmers. For example, an automated checker will find this piece of C# code written by a beginner programmer correct:

var result = new List<Day>();
foreach (var day in days)
{
    if (day.HasAppointment)
    {
        result.Add(day);
    }
}

return result;

while any more experienced developer will suggest rewriting it like this:

return days.Where(day => day.HasAppointment);

Even if an automated tool will do such suggestions (after all, it is possible to programmatically detect procedural code which can be rewritten using functional style), would this tool be able to explain to the beginner programmer the caveats of such rewrite (lazy evaluation)?


答:
IMO, Manual code reviews helps in forming a shared understanding of the codebase, reducing dependency on a single or a small group of individuals. It may also teach a thing or two in programming style/language features for the reviewer reviewing the code. It works great if everyone reviews every other person's code or pair with someone senior who is good at reviewing.

So unless it is a single person reviewing the code of 10+ individuals and you introduce sonarqube to automate some of that process, I would rather keep manual code reviews for the sake of the points stated above.

Title: Do we still need manual code review if we use sonarqube code review tools

Body: We were using git gerrit for manual code review . but recently we are planning to integrate sonarqube in our Jenkins  integration server. Do we still need manual code review? Or we can stop manual code review and sonarqube is enough. I would appreciate if you share your experience with sonarqube.</p>


问:
Why 'String' objects are immutable with an explicit constructor in java?
It make sense to make class String objects immutable with following declarations, because they share the same storage in common pool.

```<code>String str1 = "abc";
String str2 = "abc";
</code>```

But, am not sure, if it make sense to have class String objects immutable with following explicit constructor declarations, because they do not share the same storage in heap.

```<code>String str3 = new String("def");
String str4 = new String("def");
</code>```

So, if the content of a class String object has to be modified frequently, it is recommended to learn class StringBuffer and class StringBuilder.

Does it make sense to know, What is the reason that class String has been designed to maintain immutable content with an explicit constructor?

答: They are immutable so they behave like values. You can pass reference to the string and don't have to fear that whatever code you passed it to might change it.</p>


问:
Where is it specified that Java is call by value?
I know that Java is by default call-by-value but I am not sure where in the Java Language Specification this is addressed. Google searching only seems to find me unofficial sources but never points to where the actual part of the specification that describes this is.

Where in the JLS does it state that Java is call-by-value and how does that part of the specification actually say that it is call-by-value rather than some other convention?

答:
Definitive source for Java

As the comments already indicated, there is but one official specification for the Java language, namely the Java Language Specification made available from Oracle.

The answer to your particular question of the calling behavior is found in section 8.4.1:

When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables

Source of the confusion

Note, however, that the folks who write the JLS may not share the same definition of terms as others. In particular, the discussion whether Java is call-by-value or something else typically stems from looking at other definitions.

Call-by-value is typically defined as passing a copy of the argument to the function. This behavior is most exposed in C++ where you have an actual choice of whether you want call-by-value or call-by-reference per argument and for call-by-value you even have things like copy-constructors.

This general idea, that call-by-reference allows you to change the original object, whereas call-by-value leaves it untouched is kind of pointless in Java though (at least if you ignore primitive types). Unlike the C-family of languages, Java has no concept of a pointer to some object, so every single variable is like a pointer to some object instead. This gives the appearance to people familiar with C, that Java does in fact always pass around references (after all, if you pass an object into a function, you do not know if that function changes the internal attributes of the object).

You can argue against this argument by accepting the notion of pointers, which in turn means, that a function call is still using call-by-value, because it simply creates a copy of that pointer, which will end up pointing to the same object again.

What is most confusing is that passing an object to a method in Java will never create a full (deep!?) copy of that object - despite the fact that Java is call-by-value. Other languages (like C++) call their function calling semantics call-by-value as well, but in those languages the actual semantics differ.

Code examples

Assume you have the following two methods in your class:

```<code>private void f(C c) {
  c.setSomething();
  c = new C();
  c.setSomething2();
}
private void g(final C c) {
  c.setSomething();
}
</code>```

Now on the call-site you find something like this:

```<code>C myC = // get some C instance
f(myC); // passes the value
</code>```

The f method would now change the attributes of the myC object, because it works on exactly the same instance. In contrast, the variable c can be assigned a different instance, such that the call to setSomething2 will not affect the instance myC is referring to.

If you swap f for g on the call-site, a typical rookie-mistake from C/C++ programmers that became Java programmers is to assume that final does somehow ensure your object is not modified. Of course, the above code still works and modifies the object though. What does no longer work due to final is merely, that the variable c is re-assigned to a different C instance within that method.

This behavior also tricks more experienced Java developers. While few forget that a final List<C> argument is allowed to modify the list, not so few run into bugs, after having written a method that returns a List<C> (be it final or not, as that does not make any relevant difference) and being bitten by usage-site code that modifies it.

Body:
Definitive source for Java

As the comments already indicated, there is but one official specification for the Java language, namely the Java Language Specification made available from Oracle.

The answer to your particular question of the calling behavior is found in section 8.4.1:

When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables

Source of the confusion

Note, however, that the folks who write the JLS may not share the same definition of terms as others. In particular, the discussion whether Java is call-by-value or something else typically stems from looking at other definitions.

Call-by-value is typically defined as passing a copy of the argument to the function. This behavior is most exposed in C++ where you have an actual choice of whether you want call-by-value or call-by-reference per argument and for call-by-value you even have things like copy-constructors.

This general idea, that call-by-reference allows you to change the original object, whereas call-by-value leaves it untouched is kind of pointless in Java though (at least if you ignore primitive types). Unlike the C-family of languages, Java has no concept of a pointer to some object, so every single variable is like a pointer to some object instead. This gives the appearance to people familiar with C, that Java does in fact always pass around references (after all, if you pass an object into a function, you do not know if that function changes the internal attributes of the object).

You can argue against this argument by accepting the notion of pointers, which in turn means, that a function call is still using call-by-value, because it simply creates a copy of that pointer, which will end up pointing to the same object again.

What is most confusing is that passing an object to a method in Java will never create a full (deep!?) copy of that object - despite the fact that Java is call-by-value. Other languages (like C++) call their function calling semantics call-by-value as well, but in those languages the actual semantics differ.

Code examples

Assume you have the following two methods in your class:

private void f(C c) {
  c.setSomething();
  c = new C();
  c.setSomething2();
}
private void g(final C c) {
  c.setSomething();
}

Now on the call-site you find something like this:

C myC = // get some C instance
f(myC); // passes the value

The f method would now change the attributes of the myC object, because it works on exactly the same instance. In contrast, the variable c can be assigned a different instance, such that the call to setSomething2 will not affect the instance myC is referring to.

If you swap f for g on the call-site, a typical rookie-mistake from C/C++ programmers that became Java programmers is to assume that final does somehow ensure your object is not modified. Of course, the above code still works and modifies the object though. What does no longer work due to final is merely, that the variable c is re-assigned to a different C instance within that method.

This behavior also tricks more experienced Java developers. While few forget that a final List<C> argument is allowed to modify the list, not so few run into bugs, after having written a method that returns a List<C> (be it final or not, as that does not make any relevant difference) and being bitten by usage-site code that modifies it.


答:
Of course it makes sense.

When you get the value you should not care how it was constructed.

It would make no sense if immutability would be dependent of the way an object was constructed:

"abc" immutable, new String("def") mutable. It would create a mess.

Title: Why 'String' objects are immutable with an explicit constructor in java?

Body:
It make sense to make class String objects immutable with following declarations, because they share the same storage in common pool.

```<code>String str1 = "abc";
String str2 = "abc";
</code>```

But, am not sure, if it make sense to have class String objects immutable with following explicit constructor declarations, because they do not share the same storage in heap.

```<code>String str3 = new String("def");
String str4 = new String("def");
</code>```

So, if the content of a class String object has to be modified frequently, it is recommended to learn class StringBuffer and class StringBuilder.

Does it make sense to know, What is the reason that class String has been designed to maintain immutable content with an explicit constructor?


答:
Immutability for strings has a lot of advantages even with an explicit constructor (I am sure you know them already: cheap copies, no side-effects, value semantics). The explicit constructor is exactly what everyone expects to be available, without it we would always have to write something ugly like

```<code> String s = (new StringBuilder("abc").toString());
</code>```

The only caveat, where the classic value semantics fails, is the point you asked for: with

```<code>String str3 = new String("def");
String str4 = new String("def");
</code>```

the equality test  str3==str4 will fail (one has to use equal instead), something one would expect to work for classic value semantics.

So the design flaw here is neither the immutability nor the fact there is an explicit constructor for strings, but only the fact the creators of Java did not design the language in a way == works as expected. But that is a minor price to pay for not having every string constructed by the tedious string builder line above.

Body:
Immutability for strings has a lot of advantages even with an explicit constructor (I am sure you know them already: cheap copies, no side-effects, value semantics). The explicit constructor is exactly what everyone expects to be available, without it we would always have to write something ugly like

 String s = (new StringBuilder("abc").toString());

The only caveat, where the classic value semantics fails, is the point you asked for: with

String str3 = new String("def");
String str4 = new String("def");

the equality test  str3==str4 will fail (one has to use equal instead), something one would expect to work for classic value semantics.

So the design flaw here is neither the immutability nor the fact there is an explicit constructor for strings, but only the fact the creators of Java did not design the language in a way == works as expected. But that is a minor price to pay for not having every string constructed by the tedious string builder line above.


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

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

答:
Of those two, prefix (postfix could be used the same way, but the only languages I know of that use that are PS and Forth).

It removes the need for any kind of operator precedence and left/right associativity. Both in the sense that you don't have to think about it, and in the sense that the language implementation is slightly simpler since these forces are pre-resolved.

If applied consistently, the resulting code is very close to a tree, which makes parsing easier or unnecessary (and this allows things like programmatic manipulation of that tree structure).


问:
It is safe to accept money for open source software that you've written?
I've written an open source library for iOS, and I've received an email from an overseas developer who wants to pay me for my work so that he doesn't have to attribute in his app.

The code is released under the MIT license, which allows for reuse so long as the license is distributed along with the code. I told him that he can just use it without attribution, but he insists on sending me something.

What's the practice in the open source community, bearing in mind that several others have contributed to my library? Is there a standard or convention in the OSS community for this sort of thing?

答:
In principle, there is nothing wrong with accepting payment for software you provide, not even if that software is freely available through other channels.

Some gotchas to look out for are:

Bank account details are loved by criminals. If possible, prefer to use services like PayPal.

Be careful with what you promise and what contracts you sign.

What level and duration of (free) support are you are entering into

If the contract states the software is written for/on behalf of someone, you may be signing over your copyrights. Be sure to review it with a lawyer before signing.

If you get paid regularly or large sums, you may have to pay (income) tax over it.

If the buyer wants to do something that isn't possible under the current license, you can give them a version under a different license, provided that either you are the sole copyright holder, or all copyright holders agree, or the license explicitly gives you the right to sub-license the work.

But in no case should you allow the buyer to remove the copyright statements from the source code, as that probably indicates they want to claim the work as their own.


答:
Your biggest problem is the other contributors. Unless you have a written agreement with them, they own the copyright to the bits they contributed. This means you need to get all of them to agree to release the software under a different license.

Established projects require all contributors to sign a contributor's license agreement. If you have done this, whether you can accept payment for a dual license depends on the wording of the agreement.

Title: It is safe to accept money for open source software that you've written?

Body:
I've written an open source library for iOS, and I've received an email from an overseas developer who wants to pay me for my work so that he doesn't have to attribute in his app.

The code is released under the MIT license, which allows for reuse so long as the license is distributed along with the code. I told him that he can just use it without attribution, but he insists on sending me something.

What's the practice in the open source community, bearing in mind that several others have contributed to my library? Is there a standard or convention in the OSS community for this sort of thing?


问:
Why is python treated as a interpreted language when it has a compiling stage?
Why is that python is treated as only an interpreted language when there is in fact a compiling stage where the code we write gets converted into byte code(.pyc), which is later interpreted by the PVM. Is it wrong to say python is just an interpreted language?</p>

答:
There is no clear distinction anymore between compiled and interpreted languages any more, as there are very few languages left that are purely interpreted.

It seems like that the term 'interpreted language' is actually being used for scripting languages, where you can work in a tight "modify - execute" cycle without an explicit compilation step in the workflow.


答:
Java strings have to be immutable because Java's security model depends on the value of them not changing between them being inspected by a SecurityManager instance and consumed by whatever part of the runtime is being protected by the SecurityManager.

For example, if you have a SecurityManager on your thread and you execute:

```<code>String str = new String ("innocent.txt");
new FileReader(str);
</code>```

what happens is that the filename is checked by calling the security manager's canRead method, and only if that allows the access is the file opened.

But if we could start another thread that could modify the string to a value that wouldn't be allowed by the security manager between the call to canRead and the file being opened, we could subvert the security and preform operations we're not supposed to be allowed to do.

An alternative solution would be to make defensive copies of any security-critical string, but this would (1) be error-prone and (2) make the runtime less efficient.

Body:
Java strings have to be immutable because Java's security model depends on the value of them not changing between them being inspected by a SecurityManager instance and consumed by whatever part of the runtime is being protected by the SecurityManager.

For example, if you have a SecurityManager on your thread and you execute:

String str = new String ("innocent.txt");
new FileReader(str);

what happens is that the filename is checked by calling the security manager's canRead method, and only if that allows the access is the file opened.

But if we could start another thread that could modify the string to a value that wouldn't be allowed by the security manager between the call to canRead and the file being opened, we could subvert the security and preform operations we're not supposed to be allowed to do.

An alternative solution would be to make defensive copies of any security-critical string, but this would (1) be error-prone and (2) make the runtime less efficient.


问:
What are the key areas to evaluate software (codebase) on?
I have been asked to do a code review of about 50 applications over a period of 6 weeks. (Management has changed and the new CTO asked for an full internal software audit)

I am wondering, what are the key areas to evaluate software on?
(The focus should purely be on the quality of the codebase and not e.g. how it was deployed)

Please note: This is not the same question as "What are the 9 or 10 qualities of software?".

The first few things that came to my mind are:

Code readability (descriptive variable/method/class names, comments etc)

Layering (data/business/UI)

Configuration (no hardcoding)

Sufficient level of abstraction (to remain flexible)

Organisation of the code

Use of 3rd party libraries (approved or not etc)

Separation of concerns

Test coverage (if applicable)

Modularity of code

Penalties for breaking principles such as "DRY"

...

I will appreciate your answers to help me identify an extensive list of what you think are the key areas for software evaluation.

答:
50 applications in 6 weeks sounds enormously ambitious. You need to tell your new CTO that this is only a lightweight review; there's no way you're going to detect bugs or security flaws in this time.

I'm mostly familiar with code review for security, and the rule of thumb I use is 10 KLOC per day - and even that is ambitious, and can only be achieved by focusing on the parts of code that really matter for security.

A few suggestions:

Design a report template at the beginning, and get the CTO to approve this. It should be concise: a few red/amber/green statuses for different areas, maybe a few list of key people, issues, etc.

Include documentation in your review. This could include tickets on your issue tracker.

Speak to key people related to each application. This lets you get to the important issues more quickly.

Establish what coding standards you have, and whether they are mandatory or advisory.

Take a risk-based approach, where you spend more time on applications that matter more.

Try to establish whether you could reasonably make changes to the application. You sound like you've got decent coding skills: if you think you'd struggle, this is clearly a concern for future maintenance of the app.

Apart from that, good luck! This is an opportunity to shine, so make the most of it.


答:
Prefix, simply because operator precedence is explicit.

FYI, Longer calculations (really, any chain of operations) in Clojure can be broken out using the -> and ->> macros.  e.g.:

```<code>(-> (get-some-value)
  inc
  (* 2)
  (max 50))
</code>```

is the equivalent of:

```<code>(max (* (inc (get-some-value)) 2) 50)
</code>```

While the -> macro prepends prior results to the arguments of the next expression, ->> appends them.  This is typically very handy when used with functions that expect collections and seqs:

```<code>=> (->> "some string we want to capitalize"
     (partition-by #{\space})
     (mapcat #(cons (Character/toUpperCase (first %)) (rest %)))
     (apply str))
"Some String We Want To Capitalize"
</code>```

Providing facilities for easily composing simpler operations into compound ones like this is one of Clojure's big advantages.  For additional reading, check out fogus' post on the -> macro, and then his later post on the topic of "properly thrushy" thrush combinators in Clojure.

Title: Infix vs Prefix Notation - Which do you prefer?

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

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

Body:
Prefix, simply because operator precedence is explicit.

FYI, Longer calculations (really, any chain of operations) in Clojure can be broken out using the -> and ->> macros.  e.g.:

(-> (get-some-value)
  inc
  (* 2)
  (max 50))

is the equivalent of:

(max (* (inc (get-some-value)) 2) 50)

While the -> macro prepends prior results to the arguments of the next expression, ->> appends them.  This is typically very handy when used with functions that expect collections and seqs:

=> (->> "some string we want to capitalize"
     (partition-by #{\space})
     (mapcat #(cons (Character/toUpperCase (first %)) (rest %)))
     (apply str))
"Some String We Want To Capitalize"

Providing facilities for easily composing simpler operations into compound ones like this is one of Clojure's big advantages.  For additional reading, check out fogus' post on the -> macro, and then his later post on the topic of "properly thrushy" thrush combinators in Clojure.


答:
The constructor public String(String original) is a copy constructor. Its sole purpose is to make a copy of a String object.

Since String is immutable, making copies is rarely needed. That has been covered in the Javadoc of that constructor. However, since String is a core class and it is used everywhere, there could be some special cases requiring copying a String.

The String class has plenty of constructors which are rarely needed in most applications. Actually, using any String constructor to create a new String object is not a common way to get hold of a String in most applications.


答:
This is a bit of a simplification, but there are three main steps in compiling code:

Parse the source code to a syntax tree

Compile the syntax tree into machine-independent byte code

Translate byte code to machine code

A C compiler does all three, and is without doubt a compiler. A Java compiler does 1 and 2, producing .class files, and the runtime does 3. The Python "compiler" only does step 1 when producing .pyc files, while the runtime does 2 and 3.

So, as Bart says, the difference between "compiled" and "interpreted" is somewhat subjective. But step 2 is a very significant step, and it is the most difficult to do in reverse, i.e. decompile. So that's why Java is usually called compiled and Python usually called interpreted.

The above is my original post. Since posting I've read more about .pyc files and need to correct it. The Python compiler does actually do step 2; the contents of pyc files is a stack-based intermediate language, quite similar to Java class files.

I wonder if the reason that Python is considered "interpreted" is because there's a single binary to compile and execute.

Title: Why is python treated as a interpreted language when it has a compiling stage?

Body: Why is that python is treated as only an interpreted language when there is in fact a compiling stage where the code we write gets converted into byte code(.pyc), which is later interpreted by the PVM. Is it wrong to say python is just an interpreted language?</p>