问:
What to do about "stopping point syndrome"?
I have noticed a behavior in myself that I call "stopping point syndrome"... it means I cannot stop working until I reach a "stopping point" (or I become exhausted).  In other words, if I am in the zone working on getting a feature completed, I won't stop until I get it done.   If it's a bug I'm working on, this effect is even more pronounced... I won't stop until it's fixed, or at the very least, understood.  Even though I work from a laptop and have VPN and could easily go home and pick up on the work later that evening, that fact does not help me leave work... it's like I'm afraid I will die before I find the bug.

I have a very hard time explaining this to family members who can't figure out why I never come home from work at the same time and sometimes come home at 11 pm.  Even managers have been mystified by this, and I've noticed that most of my colleagues have no trouble working the same hours every day.

Does anyone else have this problem?  Should I be worried about this and/or try to change it?  If so how?

答:
Yes, I have this too. Well actually as I have got older its less pronounced.

I also noticed that at the end of the day, and when tired, I make more mistakes. On arrival back to work the next day the solution becomes obvious and I have to rewrite a load of code. However, it takes a fraction of the time as it was the day before.


问:
Integrating a mobile website into a mobile app
I'm trying to redevelop a mobile website so we can integrate it into a mobile app that is being developed by another department, but still keep it functional on the web. The app has its own menu, so it's redundant to leave the menu on the mobile site.

We considered simply removing the menu, headers and footers from the site, and provide the links to the pages to the other department so they can add them to the app menu. This obviously leaves our website menu-less.

I've considered creating a new front page, that has a similar menu to the app, and loading the pages either in frames, or using jquery .load(), or ASP includes... Frames would give me the functionality I want that is most similar to the app opening pages in a browser using it's native menu, but frames are so... 1990's.

What is best solution that uses modern standards?

答:
URL variables and CSS

This is the solution I came up with using user1741807's suggestion to use a GET variable:

The portal app is going to be on OSX, Android and Windows, and simply links to our mobile website and displays it in a nested browser, so I used the URL to create a cookie and then used CSS to hide the menu.

Our mobile website is written in Classic ASP, PHP, and HTML, so I wrote a different script for each language. I had originally planned on writing one script in Javascript, but when I discovered how easy it was to do what I wanted in ASP and PHP I decided to scrap Javascript. It was later on that I realized I had some pages that weren't in ASP or PHP and ended up having to write the Javascript anyways.

The code below will hide the menu only when the homepage is visited from the link that contains the variable in the app menu, and will persist for as long as the session lasts, but will not hide the menu when visited from a browser without the variable.

The variable at the end of the URL string: ?display=portal

Classic ASP

Asp has function that can easily get variables from a URLS: request.querystring()

I put the code below on index.asp to set the cookie, then put Request.Cookies() code on the rest of our asp pages.

```<code><%
fromPortalApp = request.querystring("display")
If fromPortalApp = "portal" Then
    Response.Cookies("display")="portal"
Else
    Response.Cookies("display")="web"
End If

portalCheck = Request.Cookies("display")
If portalCheck = "portal" Then
    MenuDisplay = "none"
Else
    MenuDisplay = "normal"
End If
%>

<style>
#topbar {
    display:<%=MenuDisplay%>;
}
</style>
</code>```

PHP

On the PHP pages I didn't need to set the cookie, so I just needed to include a script to check for it:

```<code><?php
if (isset($_COOKIE["display"])){
    $sessionDisplay = $_COOKIE["display"];
    if ($sessionDisplay == "portal"){
        $portalcheck = "none";
    } elseif ($sessionDisplay == "web"){
        $portalcheck = "normal";
    }
} else {
    $portalcheck = "normal";
}
?>
<style>
#topbar {
    display:<?php echo $portalcheck; ?>;
}
</style>
</code>```

Pure Javascript

Javascript was the tricky one, we have some HTML pages on a different server at a different subdomain, so I had to use a written function to get the variables, another function to write the cookies, a third function to get the cookies, and then write a fourth function to modify the CSS and hide the #topbar div with the menu. The set and get cookies functions are right out of w3schools.

```<code>function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,    function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
    }
    return "";
}

var portalcheck = getUrlVars()["display"];
var hostcheck = window.location.hostname;
if(portalcheck=="portal" && hostcheck=="darius.uleth.ca"){
    setCookie("display", "portal")
} else if (hostcheck=="darius.uleth.ca"){
    setCookie("display", "web")
}

window.onload = init;

function init(){
    var topbar = document.getElementById("topbar");
    var portalcookie = getCookie("display");

    if(portalcookie=="portal" && hostcheck=="darius.uleth.ca"){
        topbar.style.display= "none";
        document.getElementById("content").style.margin="0";
    } else if (portalcookie=="web"){
        topbar.style.display= "normal";
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
URL variables and CSS

This is the solution I came up with using user1741807's suggestion to use a GET variable:

The portal app is going to be on OSX, Android and Windows, and simply links to our mobile website and displays it in a nested browser, so I used the URL to create a cookie and then used CSS to hide the menu.

Our mobile website is written in Classic ASP, PHP, and HTML, so I wrote a different script for each language. I had originally planned on writing one script in Javascript, but when I discovered how easy it was to do what I wanted in ASP and PHP I decided to scrap Javascript. It was later on that I realized I had some pages that weren't in ASP or PHP and ended up having to write the Javascript anyways.

The code below will hide the menu only when the homepage is visited from the link that contains the variable in the app menu, and will persist for as long as the session lasts, but will not hide the menu when visited from a browser without the variable.

The variable at the end of the URL string: ?display=portal

Classic ASP

Asp has function that can easily get variables from a URLS: request.querystring()

I put the code below on index.asp to set the cookie, then put Request.Cookies() code on the rest of our asp pages.

<%
fromPortalApp = request.querystring("display")
If fromPortalApp = "portal" Then
    Response.Cookies("display")="portal"
Else
    Response.Cookies("display")="web"
End If

portalCheck = Request.Cookies("display")
If portalCheck = "portal" Then
    MenuDisplay = "none"
Else
    MenuDisplay = "normal"
End If
%>

<style>
#topbar {
    display:<%=MenuDisplay%>;
}
</style>

PHP

On the PHP pages I didn't need to set the cookie, so I just needed to include a script to check for it:

<?php
if (isset($_COOKIE["display"])){
    $sessionDisplay = $_COOKIE["display"];
    if ($sessionDisplay == "portal"){
        $portalcheck = "none";
    } elseif ($sessionDisplay == "web"){
        $portalcheck = "normal";
    }
} else {
    $portalcheck = "normal";
}
?>
<style>
#topbar {
    display:<?php echo $portalcheck; ?>;
}
</style>

Pure Javascript

Javascript was the tricky one, we have some HTML pages on a different server at a different subdomain, so I had to use a written function to get the variables, another function to write the cookies, a third function to get the cookies, and then write a fourth function to modify the CSS and hide the #topbar div with the menu. The set and get cookies functions are right out of w3schools.

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,    function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
    }
    return "";
}

var portalcheck = getUrlVars()["display"];
var hostcheck = window.location.hostname;
if(portalcheck=="portal" && hostcheck=="darius.uleth.ca"){
    setCookie("display", "portal")
} else if (hostcheck=="darius.uleth.ca"){
    setCookie("display", "web")
}

window.onload = init;

function init(){
    var topbar = document.getElementById("topbar");
    var portalcookie = getCookie("display");

    if(portalcookie=="portal" && hostcheck=="darius.uleth.ca"){
        topbar.style.display= "none";
        document.getElementById("content").style.margin="0";
    } else if (portalcookie=="web"){
        topbar.style.display= "normal";
    }
}


问:
Implementing a simple controller in embedded C
Is there a known method or pattern to implement a simple controller for an MVC design in pure C or the switch case approach is the standard?

Background :

I have an embedded application and I'm pleased with how the business logic turned out. I also finished the UI which boils down to basically 2 functions:

```<code>uint8_t getInput(void);
void display(logger toDestination, char* message, ...)
</code>```

Inputs can come from multiple sources and outputs can be sent to several destinations. All of that is taken care of so the application has no idea if its run by a PC on on the device. It also has no idea if the events come from humans or are faked by unit tests.

Where I struggle is with the application logic. My views are in charge of where and how to display the outputs. My drivers, regrouped into behavioral models providing clear features, know how to do their jobs very well but not when.

Here's my functional rough draft, which in my opinion violates principles like DRY, cohesion, flexibility and may present scalability problems:

Rough draft : (I faked the names and reduced the size but you get the idea)

menu.h

```<code>void goToMainMenu(void); // This is the entry point of the application after everything was setup correctly

    void goToFirstSubMenu(void);
        void firstFunctionality(void); //The last levels are the ones doing the calls to the business logic
        void secondFunctionality(void);
        //Other functionality or nested sub-sub-menus

    void goToSecondSubMenu(void);
        void thirdFunctionality(void);

    int doSomethingWithTheBusinessLogic(int arg1, char arg2, void* arg3);

    //Other sub-menus and options

    /* And so on, the function prototype are indented to reflect the logical level of the menus.*/
</code>```

Then most of the functions will roughly look like this:

menu.c

```<code>void goToMainMenu(void)
{
  uint8_t choice = 0;
  resetDefaultState();

  do
  {
    display(toTerminal, "Press 1 to go to sub-menu 1" ENDL);
    display(toTerminal, "Press 2 to go to sub-menu 2" ENDL);
    display(toTerminal, "Press 3 to do something with the drivers" ENDL);
    display(toTerminal, "Press z to go back." ENDL);

    choice = getChar(); /* Blocking thread waiting for events to pop from the other threads */

    if     (choice == '1'){ goToFirstSubMenu(); }
    else if(choice == '2'){ goToSecondSubMenu(); }
    else if(choice == '3'){ doSomethingWithTheBusinessLogic(); }

  }while(choice != 'z');

  resetDefaultState();
  /* When a submenu returns we're taken to the parent menu's do-while loop */
}
</code>```

Is it a good way to do things for small-medium systems?

How could this be improved considering the limits of C and embedded environnements?

What has been tried :

I tried a n-ary tree approach where nodes are menus and leaves are functionality but without polymorphism it's hard to define elegently how both should behave to inputs. The strongly typed system also makes it hard to do a simple callbacks system because I end up needing tons of wrappers around the drivers to unifiy a single callback signature (void myCallback(void*)).

It also seem to be overkill for this simple state-flow; I feel like I'm working against KISS and productivity only because I've been hammered with "chains of if-elses is the devil".

What I would like :

With higher level languages usually you can bind events and callbacks. Something along the lines of bind(myMenu, thisInput, theCallback) so whenever myMenu is focused and an event thisInput it raised theCallback is called.

I'm unsure how to do this in C without going way overboard.

答:
To take a step back, I think that you may be over-complicating things with your design. You mention an MVC pattern at the beginning, so I'm assuming that you're knowledgeable about web-frameworks and high level designs.

You should neatly tuck that away and put it in your pocket.

When working on an embedded system, you are making some serious tradeoffs between abstraction and complexity. On one hand, you could create well crafted interfaces for each component you use, and each microprocessor would have a different implementation for that, and you'd live in this beautiful, neatly coded world where you never actually did anything useful, and if you did, it would take 13 different interfaces, which worked for 300 chips and modules you never actually intended to use, and when you tried to program it you would realize the chip you targeted isn't big enough.

On the other hand, you could decide that there is value in simply having a working device, and that simplicity will help in debugging an already error-prone system. Between chip errata, incorrect spec sheets, and the wide array of possible chips you could use, tracking down why your serial port doesn't actually communicate to your LCD can be a nightmare even without extra interfaces on top of it.

It may seem counter-intuitive with the high-level work you've done previously, but it's simply a way of life when working on an embedded system. Extra complexity means extra bugs, and you can't always update the system once it's out in the real world.


问:
Is it a good idea to merge multiple HTTP requests to save bandwidth?
I am preparing a single page application that would be sometimes used over slow mobile connection. Some of its part are quite heavy in terms of API requests (fetching ten different resources for a new screen display).

Now, is it a good idea to merge these services to one that provides all required data, but is not as "pure" in terms of REST principles? Are there significant performance gains to be expected?

答:
Your intuition is somewhat correct -- by and large making fewer requests is certainly preferable; chunky APIs tend to be better. Especially with spotty connectivity where you can see some work and some fail creating nightmarish fallback scenarios as nothing can rely upon anything.

There is one big caveat -- you can get way too chunky and your calls and responses become bloated. For example it might make sense to have one big call when you first hit a page and then have updates stream in in smaller bites rather than forcing a big page refresh every time you want data.

Or, you will want to do it both ways in all likelihood.


问:
Windows Permissions for Developers?
I work at a Fortune 500 company as a Windows software developer in R&D. Corporate IT is currently gearing up for a company-wide Win7 deployment and as a part of it they are looking to completely lock down admin rights on all boxes (including our dev workstations).

I've been tasked to work with them to make the transition as smooth as possible. Lucky me.

I'd like to know if there are any published or other highly respected resources out there that I can use to:

figure out where to draw a line in the sand

back up my position.

Personally, my take is that we're R&D and our job is to do things that are 'out of the box'.  Thus we need admin rights.  However, having started my career as a Windows Admin, I'm aware of their goals and what they need to achieve. What I need to figure out and back up is a way to build the environment in a way that both IT and R&D can live with it and continue to perform their jobs productively.

Development VMs with local admin rights will definitely help a lot, but not in all cases since we interface with lots of custom hardware.

The CIO pushing these changes is definitely a 'pure IT' kind of guy with limited knowledge of the development process so I need some references that would be appropriate to share with someone like that.

I'm not looking to gather a lot of personal opinions (a lot of which have already been shared here), I really need whitepapers, magazine articles, scholarly works, etc to use to make a strong case to upper management.

答:
Software development is a fundamentally different beast from literally every other use of a computer, and it has to be treated as such.

The ability to write your own code, and more importantly trace your code execution in debugging, requires you to have permissions on your computer that, under any other context, would pose a huge risk to local security. Rephrased in sound-bite form:

Permissions required for software development are not appropriate for typical users.

In order to get your job done, you need to be local admin. But by being local admin and circumventing security policy, you're theoretically posing a risk to the rest of the network. So that concern needs to be addressed as well. The way security-critical companies solve this issue is by imposing two simple rules:

Programmers are local admin access on their development machine.

Development machines are not connected to the company network.

How the second rule plays out is up to the IT department. Sometimes the development machine is isolated on its own with no network in or out (seen in several Defense contractors), and sometimes the machine is connected to a "Guest" or "DMZ" network to allow for Internet access (downloading patches, accessing documentation, etc.) without putting the company network at undue risk.

Now, will you find some offical source on this? I guess that depends on whom you see as official. The opinion on this matter is basically unanimous. But it's so well-understood that it's rarely stated. It's a bit like asking: "Should my car have a parking brake?" You're not going to find authoritative sources speaking out of the subject because they have better things to do and everyone already knows that answer.

OwnerDisplayName: Dan

ContentLicense: CC BY-SA 2.5

Title: Windows Permissions for Developers?


答: If the mobile app is a PhoneGap app (or at least, something with an embedded webview), you can define a value in the JavaScript interface (ie, within the link between Java/ObjC to the web view) to test against.  When the JavaScript on the HTML page is first executed, check if that value is assigned.  If it is, its the mobile app.  If its not, its the web page.  Then adjust the menus accordingly.</p>

Title: Integrating a mobile website into a mobile app

Body:
I'm trying to redevelop a mobile website so we can integrate it into a mobile app that is being developed by another department, but still keep it functional on the web. The app has its own menu, so it's redundant to leave the menu on the mobile site.

We considered simply removing the menu, headers and footers from the site, and provide the links to the pages to the other department so they can add them to the app menu. This obviously leaves our website menu-less.

I've considered creating a new front page, that has a similar menu to the app, and loading the pages either in frames, or using jquery .load(), or ASP includes... Frames would give me the functionality I want that is most similar to the app opening pages in a browser using it's native menu, but frames are so... 1990's.

What is best solution that uses modern standards?


问:
Efficiency of self-education
Do you think being self-educated in software development is good? Please give an example of what you have learnt successfully by yourself.</p>

答:
@Kramii is correct; programmers will have to self-educate throughout their career

Q: What have i learned successfully by myself?

A: Everything

Teaching is a myth; the teacher can only make the information available, the student must listen and decide to learn or not, and what to learn. The teacher can only show you the path. In other words all education is fundamentally self-education

Now if you just mean 'what did you learn outside of a classroom that was useful', my answer would be

A: Almost Everything

because when I was in school the universities were in general 12-15 years behind the market in what they taught. For example, during the day the university was 'teaching' me procedural programming using PL/1, and at night I was writing an object-oriented programming language in Assembly.

Since then, books and google are my teachers.

Title: Efficiency of self-education


问:
Where should I put bindings for dependency injection?
I'm new to dependency injection and though I've really liked it so far, I'm not sure where bindings should go. I'm using Guice in Java, so some of what I say might be specific to just Guice. As I see it, there's two options:

Accompanying the class(s) its needed for. Then, just write install(OtherClassModule.class) in whatever other modules want to be able to use said class. As I see it, the advantage of this is that classes that want to use it (or manage classes that want to use it) don't need to know any of the implementation detail. The issue I see is that what if two classes want to use two different versions of the same class? There's a lot of customization possible because of DI and this seems to restrict it a lot.

Implemented in the module of the class(s) its needed for. It's the flip of what I said above. Now you have customization, but not encapsulation.

Is there a third option? Am I misunderstanding something obvious? What's the best practice?

答:
There's a third solution that I've been using instead.

Have the module accompany the class(s) it's needed for, but have multiple different versions (using inheritance in Guice) with different configurations. Then just install(...) whichever version I want. The advantage is that it's still encapsulated, but it is also customizable.


问:
Should I put extension methods of an interface in the interface.cs file?
Imagine this set up:

```<code>public interface IMass{
    double Mass {get;}
}

public static class IMassExtension {
    public static double ToKg(this IMass massObject) {
        return massObject.Mass / 1000.0;
    }

    public static double CalculateInteractiveGravity(this IMass massObject, IMass otherMassObject)
    {
         return blah;
    }
}
</code>```

Is it ok to put the extension class in the same file as the interface (i.e. IMass.cs) or should it be in a separate file (IMassExtension.cs)?

A base class is not possible here. Imagine

```<code>public class Person : Animal, IMass {}
</code>```

and

```<code>public class House : Building, IMass {}
</code>```

答:
Normally, I wouldn't put extension methods in the same file as the interface. Same library/package? Sure.

In this example, I would definitely wouldn't. What if someone implemented mass in imperial units (slugs)? The toKg() should be in the interface (and maybe well as toSlug(), but that would technically be derivable from toKg()), and the extension methods would be methods like toG(), toMcg(), etc., which could be implemented using the interface methods.


答:
In summary: Having the extension methods in a separate file would be the approach to go. It is also very important to name extensions appropriately, as that will definitely safe time during the maintenance.

I would definitely prefer the name MassExtensions over IMassExtensions. The reason being that to most programmers an I prefix on a type implies that it is an interface. This is both a very common pattern and part of the .NET Design Guidelines.

Adding an I prefix for the extension method case breaks both assumptions and established guidelines.

There is also precedence for this in the Base Class Library. The majority of the extension methods available for IEnumerable are contained in the type Enumerable.

Following related posts might be helpful:

C# - using extension methods to provide default interface implementation

C# Extension methods namespace and promoting extension methods

Title: Should I put extension methods of an interface in the interface.cs file?

Body:
Imagine this set up:

```<code>public interface IMass{
    double Mass {get;}
}

public static class IMassExtension {
    public static double ToKg(this IMass massObject) {
        return massObject.Mass / 1000.0;
    }

    public static double CalculateInteractiveGravity(this IMass massObject, IMass otherMassObject)
    {
         return blah;
    }
}
</code>```

Is it ok to put the extension class in the same file as the interface (i.e. IMass.cs) or should it be in a separate file (IMassExtension.cs)?

A base class is not possible here. Imagine

```<code>public class Person : Animal, IMass {}
</code>```

and

```<code>public class House : Building, IMass {}
</code>```


答:
I would put it in a separate file, and I would give it a more descriptive name than
"IMassExtension.cs". Perhaps something like "MassConversions.cs", since that's what the class actually does.

Don't forget, the extension methods can still be called as if they were simple static methods (e.g. MassConversions.ToKg(massObject) ), so the class should be named with that in mind. Also, your extension class isn't an interface, so it could be misleading to name it with the leading 'I'.


答:
One of the advantages of REST is the ability to cache the requests via traditional http caches (assuming that these are cacheable requests).

When you have single, larger, less frequently used, and possibly different requests (I'm going to fetch items a,b,c,d this time and items a,b,d,e next time) you make the request more likely to be a cache miss and get expired from a cache that may be sitting somewhere between you and the source.

Given the two sets of requests mentioned above, the second request may have a 75% cache hit rate and be substantially faster fetching just e, rather than all four things.

Note that this may not be immediately apparent to people using it as the person who does the first set of cache miss requests will still have the cache misses.

This isn't to say that it would be ideal on a mobile network connection where one is less likely to get non-local cache hits.  But for hot spots or other wifi situations, the cache hits could be much more useful.

Much of this, again, is subject to how your application works.  Is it asking for all this data at startup? or are we talking about a page load where response time expectations are different?

The ideal thing to do would be to test this to see how your application preforms in a variety of situations.  Consider setting up a situation where you've bound your mobile device to a local wifi network that you can monitor (that is just the first hit on google) and simulating a bad internet connection to see how things actually work (or don't) and which one has the best performance.

Title: Is it a good idea to merge multiple HTTP requests to save bandwidth?

Body:
I am preparing a single page application that would be sometimes used over slow mobile connection. Some of its part are quite heavy in terms of API requests (fetching ten different resources for a new screen display).

Now, is it a good idea to merge these services to one that provides all required data, but is not as "pure" in terms of REST principles? Are there significant performance gains to be expected?


答:
In short: Your approach is somewhat correct and could benefit from a wrapper Service.

This service will combine existing single calls into one service side method. Doing that by combining calls from client to service side & utilizing all single, atomic, restful calls that you probably have in place by now.

Thus, you would continue to have benefit from REST as the ability to cache the requests.

However, at the end point it will all boil down to the service/server infrastructure performance and client environment that should consume it.


答:
Yeah, that's totally fine. Further, I would encourage you to do that, as it makes the functionality available in the interface more discoverable, while reducing the noise in the "what functionality is in this csproj?" view in visual studio.

The only arguments I've heard against this are:

"but then you have 2 types per file!" - guidelines are there to help you, not tie your hands. You'd make it only one type if you could.

"but that extension uses XYZ!" - yeah, if you wouldn't include the method if it were an abstract class, then you shouldn't hard-wire it to the interface either. That's not a problem with this practice, but with your design.


答: I think this is normal behaviour, same here, and the best way to handle it is NOT to start a new working point if it doesn't look like you can complete until your planned departure. You surely have enough busywork to do to fill those 50 minutes, don't you?</p>

Title: What to do about "stopping point syndrome"?

Body:
I have noticed a behavior in myself that I call "stopping point syndrome"... it means I cannot stop working until I reach a "stopping point" (or I become exhausted).  In other words, if I am in the zone working on getting a feature completed, I won't stop until I get it done.   If it's a bug I'm working on, this effect is even more pronounced... I won't stop until it's fixed, or at the very least, understood.  Even though I work from a laptop and have VPN and could easily go home and pick up on the work later that evening, that fact does not help me leave work... it's like I'm afraid I will die before I find the bug.

I have a very hard time explaining this to family members who can't figure out why I never come home from work at the same time and sometimes come home at 11 pm.  Even managers have been mystified by this, and I've noticed that most of my colleagues have no trouble working the same hours every day.

Does anyone else have this problem?  Should I be worried about this and/or try to change it?  If so how?


答:
There is a development process question which should be understood and answered before worrying too much about the code.

IMHO, any organisation which employes more than one software developer, and especially one using interns to develop code, should have sane, rational, understood, shared development processes. There is a tremendous amount of evidence that reviewing code helps a lot. They help all developers to get onto the same page about coding techniques, style, libraries, tools, etc.

Recommendation 1: Ask your supervisor about doing a review of your code or design as soon as practical. It'll give you some feedback from people who's views are much more relevant than ours. Also it'll provide a way for your supervisor to understand your code well in advance of you leaving, with a clear invitation to direct you to fix things they don't like.

Let's try to look at it from some other persons position. They have to change the code, without breaking it, or fix a bug. They might be the next intern, with less knowledge than you. They want life to be straightforward. Ideally they will look at your code and say to their supervisor "this code is great, I can understand it really easily, and I am confident the set of test cases they built will catch most of the types of errors that I might make."

When I have to read other peoples code, I like it 'as simple as possible, but no simpler'.

The less code I have to read, the fewer ideas, and the less 'stacking' or 'cross-referencing' (I wonder how that works, I'll have to go and read that before I can progress), the better. So callbacks are unwelcome unless they reduce the total amount of effort a lot. Big libraries, with lots of extra features mainly obscure the code. Good unit tests and test cases help me to understand what the developer intended.

Your code seems like a model of how this might be done.
My only slight criticism is:

```<code>    display(toTerminal, "Press 2 to go to sub-menu 2" ENDL);
</code>```

then later

```<code>    else if(choice == '2'){ goToSecondSubMenu(); }
</code>```

requires someone to ensure the text of the terminal message, and the value in the if test matches. If the program really is that level of complexity. I wouldn't worry. Hoever if it is significantly larger, then I might be tempted to create some named constants, and write something like:

```<code>#define SUB_MENU_2 '2'
...

    display(toTerminal, "Press " SUB_MENU_2 " to go to sub-menu 2" ENDL);

    else if(choice == SUB_MENU_2){ goToSecondSubMenu(); }
</code>```

You might be tempted to put the message and choice character into an array of structs, so that the choice value and message are kept together. That is making the reader of your code have to think a bit harder, but you might find it helps if there are some other requirements. For example, it might help to identify values explicitly, so that more ways of  navigation can be made to work, e.g. driving up and down the menu with cursor keys, or pressing the digit. However, resist the temptation to write 'clever' code; it causes a new reader to have to move around the code, rather than simply read it in sequence.

MVC is useful when you need to separate concerns when one or more parts are complex, or there is a lot of value in reusing solutions to part of the overall problem.

For example, the code to manage a view, menus, mouse clicks, and keyboard input in a windowing system is complex to write and test. It is worth reusing that. Your 'view library' is display() and getchar(). That's it. The rest is your code to do more view stuff.

There seems to be very little control state. In the example you've shown, the view isn't changing what is offered to the user depending on the state of the model or rules managed by the controller. Further, the actions seem to be straightforward too. So the controller seems very simple, and the model encapsulated.

If that changes, and the view must dynamically respond to reflect the state of the model, or their are several ways to get at the model, or more 'input validation' of data, their may be a need for a more explicit implementation of MVC.

The stuff you have been taught is typically designed for very large systems (or is just another new fad). Unfortunately, when it is taught, the reasoning or rationale might be poorly explained.

IMHO, some of that complexity comes from people trying to implement things in a language which is not a good fit. For example, SmallTalk, the original home of MVC, makes some things easy because it is so dynamic and rich, however some of its mechanisms are ugly to implement in other languages. Hence we end up with a lot of complication, to address complex and very general situations.

Also, there is quite a lot of money, marketing and ego tied up in offering very clever solutions designed for extremely complex problems, then selling the skills capable of applying those clever solutions. It is unlikely you'll hear a large system integrator say "no, you don't need anything this clever and expensive, you just need that very simple, straightforward approach that any competent developer will use successfully". Just my $0.02.

Title: Implementing a simple controller in embedded C

Body:
Is there a known method or pattern to implement a simple controller for an MVC design in pure C or the switch case approach is the standard?

Background :

I have an embedded application and I'm pleased with how the business logic turned out. I also finished the UI which boils down to basically 2 functions:

```<code>uint8_t getInput(void);
void display(logger toDestination, char* message, ...)
</code>```

Inputs can come from multiple sources and outputs can be sent to several destinations. All of that is taken care of so the application has no idea if its run by a PC on on the device. It also has no idea if the events come from humans or are faked by unit tests.

Where I struggle is with the application logic. My views are in charge of where and how to display the outputs. My drivers, regrouped into behavioral models providing clear features, know how to do their jobs very well but not when.

Here's my functional rough draft, which in my opinion violates principles like DRY, cohesion, flexibility and may present scalability problems:

Rough draft : (I faked the names and reduced the size but you get the idea)

menu.h

```<code>void goToMainMenu(void); // This is the entry point of the application after everything was setup correctly

    void goToFirstSubMenu(void);
        void firstFunctionality(void); //The last levels are the ones doing the calls to the business logic
        void secondFunctionality(void);
        //Other functionality or nested sub-sub-menus

    void goToSecondSubMenu(void);
        void thirdFunctionality(void);

    int doSomethingWithTheBusinessLogic(int arg1, char arg2, void* arg3);

    //Other sub-menus and options

    /* And so on, the function prototype are indented to reflect the logical level of the menus.*/
</code>```

Then most of the functions will roughly look like this:

menu.c

```<code>void goToMainMenu(void)
{
  uint8_t choice = 0;
  resetDefaultState();

  do
  {
    display(toTerminal, "Press 1 to go to sub-menu 1" ENDL);
    display(toTerminal, "Press 2 to go to sub-menu 2" ENDL);
    display(toTerminal, "Press 3 to do something with the drivers" ENDL);
    display(toTerminal, "Press z to go back." ENDL);

    choice = getChar(); /* Blocking thread waiting for events to pop from the other threads */

    if     (choice == '1'){ goToFirstSubMenu(); }
    else if(choice == '2'){ goToSecondSubMenu(); }
    else if(choice == '3'){ doSomethingWithTheBusinessLogic(); }

  }while(choice != 'z');

  resetDefaultState();
  /* When a submenu returns we're taken to the parent menu's do-while loop */
}
</code>```

Is it a good way to do things for small-medium systems?

How could this be improved considering the limits of C and embedded environnements?

What has been tried :

I tried a n-ary tree approach where nodes are menus and leaves are functionality but without polymorphism it's hard to define elegently how both should behave to inputs. The strongly typed system also makes it hard to do a simple callbacks system because I end up needing tons of wrappers around the drivers to unifiy a single callback signature (void myCallback(void*)).

It also seem to be overkill for this simple state-flow; I feel like I'm working against KISS and productivity only because I've been hammered with "chains of if-elses is the devil".

What I would like :

With higher level languages usually you can bind events and callbacks. Something along the lines of bind(myMenu, thisInput, theCallback) so whenever myMenu is focused and an event thisInput it raised theCallback is called.

I'm unsure how to do this in C without going way overboard.

Body:
There is a development process question which should be understood and answered before worrying too much about the code.

IMHO, any organisation which employes more than one software developer, and especially one using interns to develop code, should have sane, rational, understood, shared development processes. There is a tremendous amount of evidence that reviewing code helps a lot. They help all developers to get onto the same page about coding techniques, style, libraries, tools, etc.

Recommendation 1: Ask your supervisor about doing a review of your code or design as soon as practical. It'll give you some feedback from people who's views are much more relevant than ours. Also it'll provide a way for your supervisor to understand your code well in advance of you leaving, with a clear invitation to direct you to fix things they don't like.

Let's try to look at it from some other persons position. They have to change the code, without breaking it, or fix a bug. They might be the next intern, with less knowledge than you. They want life to be straightforward. Ideally they will look at your code and say to their supervisor "this code is great, I can understand it really easily, and I am confident the set of test cases they built will catch most of the types of errors that I might make."

When I have to read other peoples code, I like it 'as simple as possible, but no simpler'.

The less code I have to read, the fewer ideas, and the less 'stacking' or 'cross-referencing' (I wonder how that works, I'll have to go and read that before I can progress), the better. So callbacks are unwelcome unless they reduce the total amount of effort a lot. Big libraries, with lots of extra features mainly obscure the code. Good unit tests and test cases help me to understand what the developer intended.

Your code seems like a model of how this might be done.
My only slight criticism is:

    display(toTerminal, "Press 2 to go to sub-menu 2" ENDL);

then later

    else if(choice == '2'){ goToSecondSubMenu(); }

requires someone to ensure the text of the terminal message, and the value in the if test matches. If the program really is that level of complexity. I wouldn't worry. Hoever if it is significantly larger, then I might be tempted to create some named constants, and write something like:

#define SUB_MENU_2 '2'
...

    display(toTerminal, "Press " SUB_MENU_2 " to go to sub-menu 2" ENDL);

    else if(choice == SUB_MENU_2){ goToSecondSubMenu(); }

You might be tempted to put the message and choice character into an array of structs, so that the choice value and message are kept together. That is making the reader of your code have to think a bit harder, but you might find it helps if there are some other requirements. For example, it might help to identify values explicitly, so that more ways of  navigation can be made to work, e.g. driving up and down the menu with cursor keys, or pressing the digit. However, resist the temptation to write 'clever' code; it causes a new reader to have to move around the code, rather than simply read it in sequence.

MVC is useful when you need to separate concerns when one or more parts are complex, or there is a lot of value in reusing solutions to part of the overall problem.

For example, the code to manage a view, menus, mouse clicks, and keyboard input in a windowing system is complex to write and test. It is worth reusing that. Your 'view library' is display() and getchar(). That's it. The rest is your code to do more view stuff.

There seems to be very little control state. In the example you've shown, the view isn't changing what is offered to the user depending on the state of the model or rules managed by the controller. Further, the actions seem to be straightforward too. So the controller seems very simple, and the model encapsulated.

If that changes, and the view must dynamically respond to reflect the state of the model, or their are several ways to get at the model, or more 'input validation' of data, their may be a need for a more explicit implementation of MVC.

The stuff you have been taught is typically designed for very large systems (or is just another new fad). Unfortunately, when it is taught, the reasoning or rationale might be poorly explained.

IMHO, some of that complexity comes from people trying to implement things in a language which is not a good fit. For example, SmallTalk, the original home of MVC, makes some things easy because it is so dynamic and rich, however some of its mechanisms are ugly to implement in other languages. Hence we end up with a lot of complication, to address complex and very general situations.

Also, there is quite a lot of money, marketing and ego tied up in offering very clever solutions designed for extremely complex problems, then selling the skills capable of applying those clever solutions. It is unlikely you'll hear a large system integrator say "no, you don't need anything this clever and expensive, you just need that very simple, straightforward approach that any competent developer will use successfully". Just my $0.02.


问:
Moving a multi-activity android app into a navigation drawer activity
I'm making an Android app and have it structured as a simple multi-activity app. I want to add a navigation drawer to it, and it looks like I will need to completely restructure the app and load everything as fragments. (http://developer.android.com/training/implementing-navigation/nav-drawer.html)

How should I begin performing this "movement" of code? Should I completely copy and paste my class variables and functions into a giant file? This definitely feels like it would be prone to bugs and errors. Perhaps there's a method of separating the class files but still having one navigation drawer?

答:
I have recently had to do something similar with a relatively complex app (lots of NFC + networking + custom views). I found that I ended up with a massive ~1500 line main class.

So I split up the various functional parts of the app into several classes. All of these subclass a manager superclass which I defined as having only one method: attach(). It takes an activity as an argument and stores it as a local variable. This allows the manager classes to have a reference to a context.

So now I have several manager classes all instantiated in my Main onCreate. UIManager, NfcManager, NetworkManager, etc. Each is responsible for its respective logic and is easy to modify individually without having to modify the main activity class.


问:
Specific reasons why a top left origin is better/worse than a bottom left origin for computer graphics
I have been researching why the origins for most graphic applications are located in the top left corner of the screen. From everything I have read, they are located there because that is where the electron gun on a cathode ray tube would start to scan, from top to bottom.

Other than this historical reason, is there any usefulness to having the origin in the upper left hand corner versus (which is personally more natural to me) the bottom left hand corner?

From my knowledge, I can't think of any reason that one origin might be more useful than the other.

In terms of math, I don't think it should make any difference, as long as the relation between the pixels/point in the image stay the same you should be able to apply any mathematical transformation in the same way using either origin.

I am specifically looking for examples that show why it would be better to use one origin over the other, and not just for the reason that "this is the way it was done before" or "its easier this way because device x uses it" because all of those reasons relate back to the historical reason.

答:
I believe it is somewhat bound up with development of technology and applications.

The case

Text sent over serial communications, goes first character first, second character second, and so on. IMHO, it makes no sense to do otherwise because we can start reading as soon as the message starts, and we don't need any extra layout information. For western languages, that is top left, to bottom right. This started with the telegraph. The West developed much of the technology, so it makes sense that we made it easy for ourselves.

Text stored in computer memory is easiest to receive low address to high address, and easiest to manipulate when it is in the same order as we read it, first character at the lowest address, last character at the highest address.

Early text terminals did not store pixels, but instead stored character codes, and converted character codes to pixels on the fly (in hardware). So storing the received character codes in screen memory was the simplest option. Early personal computers did the same, and for some personal computers, the screen memory was just ordinary memory. So it uses less resources, or is easier to make, and easier to program for screen memory and in-memory text to store characters in the same order.

Screen memory must be serialised to an image representation in the order the screen needs it, i.e. for the electron gun to paint it.  Technically, the electron-gun scan direction may be arbitrary, and could start in any corner, but IMHO culturally it makes sense for western language readers. Hence existing display devices (CRT's painting top-left to bottom-right) worked perfectly as computer displays.

It makes sense for western languages to have the text 0, 0 origin for a text display start at the top left.

IMHO, it makes a lot of sense to match a graphics device 0,0 origin to the textual display origin (though, IIRC, some devices did not!).

More Detail

The in-memory screen image is a chunk of memory with linearly increasing addresses. So the electronics to retrieve memory for display would be a more convenient if the screen-refresh counter started at '0' (i.e. the start of image memory), and just incremented in synch with drawing the screen. Simple DMA systems do this. It would then make some more sense that the graphic coordinate system map to that memory address simply. Minimum complexity would argue for aligning screen refresh addressing with graphics coordinate addressing; and they would share an origin.

The opposite case, where the two addressing schemes work in the opposite direction seems to increase hardware complexity for no apparent hardware benefit. At the time these decisions were being made, hardware was expensive.

However, I think the story starts with text terminals, remote text display devices for shared computers. Some old fashioned 'dumb character terminals' (which were CRT based) were addressed from the first line down, when they moved to a character position. So if you think about textual displays as a starting point, it might make more sense than starting with graphics.

Top-left origin makes sense for things like textual menu's and textual user interfaces (e.g. forms), which is typically read top to bottom left to right in western languages.

It is easy to write text onto a screen starting top left (western language), and it is somewhat independent of screen resolution; just let the device fold text or scroll when a boundary is reached.

Further, it took quite a lot of processing power to scroll the text up the screen (yes, seriously), and that visual effect was quite unpleasant (scrolling an entire row of text by a character height, on a long persistence phosphor screen), so it would make some sense to make it easy to start writing at the top of the screen, and minimise scrolling.

Typically the screen could be cleared completely, and the cursor set top left with a single command. Also it might be using communications systems with under 300 characters/second, 2400 baud (I know people who read faster than that).

Those display devices would typically wrap onto the next line automatically and silently (yes, seriously).

So it takes no maths to write (western) text, top to bottom, staring at the top, the devices can be quite simple, and the comms quite slow.

So, the display is doing some of the work autonomously, it is not all done by the program, and in-terminal processing is limited. It might even struggle to receive text, and write it if it had to scroll every line it receives.

The terminal is connecting to the computing system over public telephone lines, using modems, their is limited bandwidth (say 2400 baud). The shared computer might not know what type of terminal is connecting.

It is practical to write from the top left, using little more than tab, line-feed, return and clear screen. As long as the developer ensures the textual menu does not scroll off the screen on the smallest screens, then it is somewhat deice and screen resolution independent. The effect is quite pleasing because the screen text 'stays still', making it easy to read before the whole screen is finished, rather than flickering with scrolling.

Driving round the screen (e.g. using cursor keys), or jumping to a specific character location is straightforward because the in-memory coordinates of the text and the screen coordinates are 'the same'.


答:
In the days of old, we had things like CRTs and input devices like the light pen.

CRT scan lines are from left to right, top to bottom.  This had implications when accessing memory or clock cycles for drawing images - one wanted to be able to access the memory in the order that it was being used.

Thus, the index for video information started in the upper left.  Later conventions for video memory and graphics followed on this.

See also Why are graphics coordinates measured from the upper left? on Stack Overflow.

Title: Specific reasons why a top left origin is better/worse than a bottom left origin for computer graphics

Body:
I have been researching why the origins for most graphic applications are located in the top left corner of the screen. From everything I have read, they are located there because that is where the electron gun on a cathode ray tube would start to scan, from top to bottom.

Other than this historical reason, is there any usefulness to having the origin in the upper left hand corner versus (which is personally more natural to me) the bottom left hand corner?

From my knowledge, I can't think of any reason that one origin might be more useful than the other.

In terms of math, I don't think it should make any difference, as long as the relation between the pixels/point in the image stay the same you should be able to apply any mathematical transformation in the same way using either origin.

I am specifically looking for examples that show why it would be better to use one origin over the other, and not just for the reason that "this is the way it was done before" or "its easier this way because device x uses it" because all of those reasons relate back to the historical reason.


问:
Alternatives to the use of the Id/Name properties with non-inputs elements in HTML
I'm migrating a website that use Javacsript/HTML/PHP using reusable javascript code, in certain moment I saw the opportunity to simplify code in functions that use almost the same code.

Let's say: I want to display values from the database into various  or
 elements using AJAX. all the referred elements use the same layout to display the data, the difference only resides in the element id or a minimal procedure to validate data. That's all.

However, I quickly came to the conclusion that I don't have a way to refer a specific element in HTML without use the id property, and the only alternative that I think was the use of name property. I know that this property it's only for <input> in a <form>,and because this elements are not <input> this rule doesn't apply (I know that in HTML the rules are not enforced).

The basic idea is to stop using ids to make my code more reusable.

To pass from this:

```<code><div id='sGroupName1'>
  +---<div id='elementA1'>
  |     +---<span id='txtA1'>
  +---<div id='elementB1'>
        +---<span id='txtB1'>

<div id='sGroupName2'>
  +---<div id='elementA2'>
  |     +---<span id='txtA2'>
  +---<div id='elementB2'>
        +---<span id='txtB2'>
</code>```

to this:

```<code><div id='sGroupName1'>
  +---<div name='elementA'>
  |     +---<span name='txtA'>
  +---<div name='elementB'>
        +---<span name='txtB'>

<div id='sGroupName2'>
  +---<div name='elementA'>
  |     +---<span name='txtA'>
  +---<div name='elementB'>
        +---<span name='txtB'>
</code>```

Doing my code in this way, i think will break the HTML5 conformity rules. I know this isn't a problem per se, because I have solved in not orthodox way, but I want to hear what is the best way to deal with this situations.

I know that exist a question related HTML - Alternative for ID when ID is only unique within a certain scope? but in this case I don't want to deal with classes and CSS rules because the current page is using a lot of CSS and there are a lot Javascript function in the page that manipulates the CSS class, using Class as kind of identifier, I think would lead to some bugs (but not so sure).

答:
If for some reason parent / child selectors won't work as GrandmasterB suggests another idea that doesn't violate HTML standards is to use CSS classes to mark your elements.

```<code><div id='sGroupName1'>
  +---<div class='boxy elementA'>
  |     +---<span class='txtA'>
  +---<div class='boxy elementB'>
        +---<span class='txtB'>

<div id='sGroupName2'>
  +---<div class='boxy elementA'>
  |     +---<span class='txtA'>
  +---<div class='boxy elementB'>
        +---<span class='txtB'>
</code>```

Since you can stack classes you can do this without interfering with the visual layout. In fact, this was a time honored tradition amongst ASP.NET developers back in the days of web forms when you had no control of element IDs.

I also suspect that lookups by class name are about the 3rd fastest DOM lookups after ID and tag name as you really need to optimize for CSS and jQuery performance these days.

Body:
If for some reason parent / child selectors won't work as GrandmasterB suggests another idea that doesn't violate HTML standards is to use CSS classes to mark your elements.

<div id='sGroupName1'>
  +---<div class='boxy elementA'>
  |     +---<span class='txtA'>
  +---<div class='boxy elementB'>
        +---<span class='txtB'>

<div id='sGroupName2'>
  +---<div class='boxy elementA'>
  |     +---<span class='txtA'>
  +---<div class='boxy elementB'>
        +---<span class='txtB'>

Since you can stack classes you can do this without interfering with the visual layout. In fact, this was a time honored tradition amongst ASP.NET developers back in the days of web forms when you had no control of element IDs.

I also suspect that lookups by class name are about the 3rd fastest DOM lookups after ID and tag name as you really need to optimize for CSS and jQuery performance these days.


答:
Beyond the class attributes that have already been suggested, you may be interested in data-* attributes. Those are whatever you want them to be. Not many rules to abide by. Check this out for details :  MDN documentation

```<code><div id='sGroupName1'>
  <div data-my-own-whatever='elementA'>
       <span data-my-own-whatever='txtA'>
  <div data-my-own-whatever='elementB'>
        <span data-my-own-whatever='txtB'>

<div id='sGroupName2'>
  <div data-my-own-whatever='elementA'>
       <span data-my-own-whatever='txtA'>
  <div data-my-own-whatever='elementB'>
        <span data-my-own-whatever='txtB'>
</code>```

Most frameworks will let you get down to your dom node with a CSS-like selector, such as : #sGroupName2 [data-my-own-whatever="txtB"].

Hope this helps.

Title: Alternatives to the use of the Id/Name properties with non-inputs elements in HTML

Body:
I'm migrating a website that use Javacsript/HTML/PHP using reusable javascript code, in certain moment I saw the opportunity to simplify code in functions that use almost the same code.

Let's say: I want to display values from the database into various  or
 elements using AJAX. all the referred elements use the same layout to display the data, the difference only resides in the element id or a minimal procedure to validate data. That's all.

However, I quickly came to the conclusion that I don't have a way to refer a specific element in HTML without use the id property, and the only alternative that I think was the use of name property. I know that this property it's only for <input> in a <form>,and because this elements are not <input> this rule doesn't apply (I know that in HTML the rules are not enforced).

The basic idea is to stop using ids to make my code more reusable.

To pass from this:

```<code><div id='sGroupName1'>
  +---<div id='elementA1'>
  |     +---<span id='txtA1'>
  +---<div id='elementB1'>
        +---<span id='txtB1'>

<div id='sGroupName2'>
  +---<div id='elementA2'>
  |     +---<span id='txtA2'>
  +---<div id='elementB2'>
        +---<span id='txtB2'>
</code>```

to this:

```<code><div id='sGroupName1'>
  +---<div name='elementA'>
  |     +---<span name='txtA'>
  +---<div name='elementB'>
        +---<span name='txtB'>

<div id='sGroupName2'>
  +---<div name='elementA'>
  |     +---<span name='txtA'>
  +---<div name='elementB'>
        +---<span name='txtB'>
</code>```

Doing my code in this way, i think will break the HTML5 conformity rules. I know this isn't a problem per se, because I have solved in not orthodox way, but I want to hear what is the best way to deal with this situations.

I know that exist a question related HTML - Alternative for ID when ID is only unique within a certain scope? but in this case I don't want to deal with classes and CSS rules because the current page is using a lot of CSS and there are a lot Javascript function in the page that manipulates the CSS class, using Class as kind of identifier, I think would lead to some bugs (but not so sure).

Body:
Beyond the class attributes that have already been suggested, you may be interested in data-* attributes. Those are whatever you want them to be. Not many rules to abide by. Check this out for details :  MDN documentation

<div id='sGroupName1'>
  <div data-my-own-whatever='elementA'>
       <span data-my-own-whatever='txtA'>
  <div data-my-own-whatever='elementB'>
        <span data-my-own-whatever='txtB'>

<div id='sGroupName2'>
  <div data-my-own-whatever='elementA'>
       <span data-my-own-whatever='txtA'>
  <div data-my-own-whatever='elementB'>
        <span data-my-own-whatever='txtB'>

Most frameworks will let you get down to your dom node with a CSS-like selector, such as : #sGroupName2 [data-my-own-whatever="txtB"].

Hope this helps.


问:
Will hosting documents on AWS reduce our load?
Due to partnerships, we are required to host our website through our partner company. However, we had an idea that perhaps we could offload the document storage to an AWS document server.  The thinking is that we could serve the html from our server, and serve any large document files from the AWS server, which would greatly reduce our bandwidth load.

Having never used AWS, can I simply provide a relatively secure AWS URL to the browser which will pull the document from AWS and bypass our web server altogether?

答:
You can indeed. In fact, you can simply have your Web server send links that look like yourbucket.s3.amazonaws.com/yourdir/yourfile.txt

You can even use cloudfront as a cdn, and optionally protect your files from direct access.

You'll have to do some reading on s3 as a minimum, and cloudfront as well if you want.

Also depending on your framework you will want to search for a module to stick things directly on the remote server. For instance boto for Python/Django


问:
iOS chat application design, sending/relaying the message over to the end user
I have a design question. Let us say you were tasked with building a chat application, specifically for iOS (iOS Chat Application). For simplicity let us say you can only chat with one person at a time (no group chat functionality).

How then can you achieve sending a message directly to an end user from phone A to phone B?

Obviously there is a web service layer with some API calls. One of the API calls available will be startChat(). After starting a chat, when you send a message, you make another async call, let us call it sendMessage() and pass in a string with your message. Once it goes to the web service layer, the message gets stored in a database.

Here is where I am currently stuck. After the message gets sent to the web service layer, how do we then achieve sending/relaying the message over to the end user? Should the web server send out a message to the end user and notify them, or should each client call a receiveMessage() method periodically, and if the server side has some info for them it can then respond with that info?

Finally, how can we handle the case in which the user you are trying to send a message to is offline? How can we make sure the end user gets the packet when he moves back to an area with signal?

答: APNS is the most obvious way to do this. It does mean you will need a central server, and it also means there will be some maintenance, as you are expected to clean up expired tokens. There's also registration with Apple when it comes to doing your certificates, but nothing too stressful. One thing to take note of is the relatively low character limit.</p>


问:
Dictionary vs List
So I ran into a Dictionary<int, int> today at work. This just seemed weird to me because I would have probably just used a List<int> instead. Is there a difference and would there be a use case where one structure would be preferred over the other?

答: If the code in question is storing two sets of correlated values, the Dictionary class provides an indexed way of looking up values by a key. If there is only one set of values, but that set needs to be accessed randomly (perhaps to check for the existence of a key in a set), and the values are unique, a HashSet might be the best set class to use.

Title: Dictionary vs List


问:
When to declare @throws with a Scala annotation - abstract parent or concrete implementation?
In this StackOverflow question I asked about the behavior of the @throws annotation in Scala. Now that I understand how it works I want to ask about best practices with using it. Here's a repost of my code from that question:

```<code>abstract class SFoo {
    def bar(): Unit
}

class SFoobar extends SFoo {
    @throws[Exception]
    override def bar(): Unit = {
        throw new Exception("hi there")
    }
}
</code>```

The problem here is that if I declare a variable as a SFoo in Java, but instantiate it as a SFoobar, the Java compiler is unable to detect the checked exception and a runtime exception will occur. So my inclination would be to declare @throws in the parent class, SFoo.

But say I have another concrete implementation of SFoo:

```<code>class SBarfoo extends SFoo {
    override def bar(): Unit = {
        println("no exception here!")
    }
}
</code>```

In this case, is it appropriate to declare @throws in the parent class if one of its implementations does not throw an exception? What is the best practice here? (Sorry for the subjective question.)

答:
You don't have to throw the exception every single time in order for the @throws contract to be fulfilled.  In fact, the vast majority of the time, you won't.  There's nothing wrong with having an implementation that never throws an exception, if it truly belongs as a subclass.  I can think of lots of applications where that would make sense.  For example, one implementation might use a disk cache, where another one might use a memory cache.

That being said, Scala purposely omitted checked exceptions for a good reason:  they violate the open/closed principle because you can't throw a new exception in a subclass without propagating it around to all the existing classes in the hierarchy, as well as methods calling those methods.  Checked exceptions were omitted from C# and other recent languages in large part because of how problematic checked exceptions proved to be in real life Java applications.  Scala only has checked exceptions for compatibility with Java code.  If you won't be calling Scala code from Java code, you shouldn't use them.


问:
Why is the complexity of fetching a value from an array be O(1)?
How come the complexity of fetching a value from an array by it's index is O(1)?

I thought the algorithm has to go through all the indexes, find the correct index, and then know what value to return. So that means the complexity is O(n/2) on average.

Why is it actually O(1)?

答:
Because the index n of an array points to the n+1th element in the array (using zero-based indexing).  Some simple math allows you to calculate the exact position of the desired element in O(1).

Further Reading

Java Arrays


答:
Simple answer:

Because you can calculate 453 + 6 in O(1) time too.

Lets write some code and look at it more closely.

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

int main(int argc, char **argv) {
  int index = atoi(argv[1]);
  int a[10];
  for(int i = 0; i < 10; i++) { a[i] = 42 + i; }

  printf("foo!\n");
  int val = a[index];
  printf("%d\n",val);
  return 0;
}
```

<p>Running this through <code>gcc -S</code> we can get the assembly for it and look at that more closely.</p>

<p>The reason that <code>foo</code> is in there, is so that I can quickly spot the spot between the two <code>printf</code>s.</p>

```    leaq    L_.str(%rip), %rdi
    movb    $0, %al
    callq   _printf
    leaq    L_.str1(%rip), %rdi
    movslq  -28(%rbp), %rcx
    movl    -80(%rbp,%rcx,4), %edx
    movl    %edx, -88(%rbp)
    movl    -88(%rbp), %esi
    movl    %eax, -92(%rbp)         ## 4-byte Spill
    movb    $0, %al
    callq   _printf
```

<p><sub>Disclaimer: I'm not an assembly guy - its been decades since I worked with MIPS, and have never done more than glance at intel.  I may have this wrong.  This may be different on your system, because I didn't actually run gcc, but rather clang.</sub></p>

<p>After the first <code>printf</code> is done, it starts out by loading the address of the format for str1 (<code>"%d\n</code>).  From a bit above that I didn't include, <code>-28(%rbp)</code> is the result from the <code>atoi</code> call.  I have this to avoid the system trying to optimize it all out (because it will do that).  And it does some other moving around things too.</p>

<p>However, there is no loop there.  Its done in a constant number of instructions no matter what index you are looking for.  This is the definition of O(1).</p>

<p>Lets look at an earlier part - the population of the array.</p>

```        movl    $0, -84(%rbp)
LBB0_1:                                 ## =>This Inner Loop Header: Depth=1
        cmpl    $10, -84(%rbp)
        jge     LBB0_4
## BB#2:                                ##   in Loop: Header=BB0_1 Depth=1
        movl    -84(%rbp), %eax
        addl    $42, %eax
        movslq  -84(%rbp), %rcx
        movl    %eax, -80(%rbp,%rcx,4)
## BB#3:                                ##   in Loop: Header=BB0_1 Depth=1
        movl    -84(%rbp), %eax
        addl    $1, %eax
        movl    %eax, -84(%rbp)
        jmp     LBB0_1
LBB0_4:
        leaq    L_.str(%rip), %rdi
        movb    $0, %al
        callq   _printf
```

And hear you can see the loop which populates the array.  There is a compare, a jump if greater than down to a label, stuff, and the jump back to the head after incrementing 1.

The number of times this will run is dependent on the size of the array (in this case 10). There is only one loop which iterates over all of the indexes. That is O(N).

Now, if this was a linked list rather than array, you would have to walk the linked list in order to find the nth element.  Then going to the nth element would also be O(N).  There are ways to make accessing a particular element of a linked list faster by using other data structures - but its still not O(1).

Title: Why is the complexity of fetching a value from an array be O(1)?

Body:
How come the complexity of fetching a value from an array by it's index is O(1)?

I thought the algorithm has to go through all the indexes, find the correct index, and then know what value to return. So that means the complexity is O(n/2) on average.

Why is it actually O(1)?

Body:
Simple answer:

Because you can calculate 453 + 6 in O(1) time too.

Lets write some code and look at it more closely.

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

int main(int argc, char **argv) {
  int index = atoi(argv[1]);
  int a[10];
  for(int i = 0; i < 10; i++) { a[i] = 42 + i; }

  printf("foo!\n");
  int val = a[index];
  printf("%d\n",val);
  return 0;
}

Running this through gcc -S we can get the assembly for it and look at that more closely.

The reason that foo is in there, is so that I can quickly spot the spot between the two printfs.

    leaq    L_.str(%rip), %rdi
    movb    $0, %al
    callq   _printf
    leaq    L_.str1(%rip), %rdi
    movslq  -28(%rbp), %rcx
    movl    -80(%rbp,%rcx,4), %edx
    movl    %edx, -88(%rbp)
    movl    -88(%rbp), %esi
    movl    %eax, -92(%rbp)         ## 4-byte Spill
    movb    $0, %al
    callq   _printf

Disclaimer: I'm not an assembly guy - its been decades since I worked with MIPS, and have never done more than glance at intel.  I may have this wrong.  This may be different on your system, because I didn't actually run gcc, but rather clang.

After the first printf is done, it starts out by loading the address of the format for str1 ("%d\n).  From a bit above that I didn't include, -28(%rbp) is the result from the atoi call.  I have this to avoid the system trying to optimize it all out (because it will do that).  And it does some other moving around things too.

However, there is no loop there.  Its done in a constant number of instructions no matter what index you are looking for.  This is the definition of O(1).

Lets look at an earlier part - the population of the array.

        movl    $0, -84(%rbp)
LBB0_1:                                 ## =>This Inner Loop Header: Depth=1
        cmpl    $10, -84(%rbp)
        jge     LBB0_4
## BB#2:                                ##   in Loop: Header=BB0_1 Depth=1
        movl    -84(%rbp), %eax
        addl    $42, %eax
        movslq  -84(%rbp), %rcx
        movl    %eax, -80(%rbp,%rcx,4)
## BB#3:                                ##   in Loop: Header=BB0_1 Depth=1
        movl    -84(%rbp), %eax
        addl    $1, %eax
        movl    %eax, -84(%rbp)
        jmp     LBB0_1
LBB0_4:
        leaq    L_.str(%rip), %rdi
        movb    $0, %al
        callq   _printf

And hear you can see the loop which populates the array.  There is a compare, a jump if greater than down to a label, stuff, and the jump back to the head after incrementing 1.

The number of times this will run is dependent on the size of the array (in this case 10). There is only one loop which iterates over all of the indexes. That is O(N).

Now, if this was a linked list rather than array, you would have to walk the linked list in order to find the nth element.  Then going to the nth element would also be O(N).  There are ways to make accessing a particular element of a linked list faster by using other data structures - but its still not O(1).


答:
The key to understanding why array access is O(1) is understanding that they have a known length. In a language like C, we can guarantee this by allocating a sequential block of memory. Since it's sequential in memory, we can use pointer arithmetic for direct addressing and thus direct access. An array object would follow a similar principle with its internal organization though the implementation might be more complex. Since all we are doing is some addition, an operation that takes O(1) time, we have an operation that over all takes O(1) time. This addition is also why in C and C++ at least, all items in an array need to be the same type. They all are required to occupy the same number of bytes for this pointer arithmetic to work.

Contrast this to a singly linked list where we have a defined beginning of the list and then we add on to that list by having a pointer or reference address point to the next node in the list. Each node contains two things, a pointer to the next node in the list and a data item. Since you can't go back, each time you want an item from the list, even if you know exactly where it is, you need to traverse the whole list up to that item. Thus, we wind up with O(n/2) for average case access and O(n) for worst case. We can mitigate this some by doing a doubly linked list with a tail pointer as well as a head pointer but we still are limited to a form of sequential, rather than truly random, access. We set the last pointer to null to essentially tell the computer the same thing we are telling it when we give in the size of an array.


答:
How can anyone consider them equivalent?

Dictionary is sparse and permits random insertions but makes in-order traversal a problem, List is not sparse and an out of order insertion is expensive, it inherently provides in-order traversal.

There would be very few situations where one wasn't dramatically superior to the other.

Title: Dictionary vs List

Body: So I ran into a Dictionary<int, int> today at work. This just seemed weird to me because I would have probably just used a List<int> instead. Is there a difference and would there be a use case where one structure would be preferred over the other?


问:
How to explain the difference between a variable and a key in a key-value pair?
Variables and the keys in key-value pairs are both identifiers for values, so, on a conceptual level, these seem very similar ideas.

How would you explain the difference between these two concepts?

Is it that key-value pairs are used in collections?

Is it that variables point to a memory location?

Or something else?

(If I look at code, I'm instinctively aware of the difference, the question's more about how to explain it which doesn't seem too obvious given that they do similar things.)

答:
Generally speaking, both are used like memory aliases. But, a variable more directly aliases a memory offset at compile time, and a key informs a memory mapping algorithm at runtime.

Conceptually, the primary difference is one of scope: Whether the alias operates at compile time versus runtime.

Functionally, the primary difference is one of runtime mutability (of all such aliases): Whether the collection of aliases can be changed at runtime. You can't compile your code and add Int32 xyz at runtime. But, you can add key xyz to a collection. (With some interpreted languages being an exception.)

Practically, the primary difference is lookup strategy and efficiency: Variables hold memory offsets. Using them is fast. Keys are piped through a lookup algorithm that, comparatively speaking, eventually determines a memory offset and returns its contents.

Lots of work is done at runtime to make keys work. Variables are sort of just there.

This all assumes you're referring to keys in the context of a collection. You can certainly have key-value pairs that have nothing to do with collections or finding things in memory. But, the keys in that context are far enough removed functionally that ... well ... I'm just assuming the question isn't referring to that.


答:
Check out this Dropbox Tech Blog article.

There they describe in detail on why and how they implemented exactly the solution you proposed for retrieving the thumbnails for all your pictures. It should be said that they do measure performance to see if it's worth the trouble, and apparently it is.

Short summary:

The Dropbox website has to load hundreds of thumbnails. Due to limitations in some browsers, not all thumbnails are loaded in parallel (the requests are queued). They wanted to use SPDY, but were unable to do so because parts of their system do not support it yet. In the end they used batch requests over HTTP, which return multiple thumbnails per response in a compressed form. Overall page load time improvement was 40% according to their results.


问:
What to do about "stopping point syndrome"?
I have noticed a behavior in myself that I call "stopping point syndrome"... it means I cannot stop working until I reach a "stopping point" (or I become exhausted).  In other words, if I am in the zone working on getting a feature completed, I won't stop until I get it done.   If it's a bug I'm working on, this effect is even more pronounced... I won't stop until it's fixed, or at the very least, understood.  Even though I work from a laptop and have VPN and could easily go home and pick up on the work later that evening, that fact does not help me leave work... it's like I'm afraid I will die before I find the bug.

I have a very hard time explaining this to family members who can't figure out why I never come home from work at the same time and sometimes come home at 11 pm.  Even managers have been mystified by this, and I've noticed that most of my colleagues have no trouble working the same hours every day.

Does anyone else have this problem?  Should I be worried about this and/or try to change it?  If so how?

答:
Happens to me all the time.  You'll be in the zone coding away and notice the clock... time to go home, but then you tell yourself, "well, as soon as I get X done".  Then the next thing that happens is... "well, as soon as I get X + Y done".

To fight this, I put a note in the code that says "START HERE" and I leave myself a post-it of what I was working on and whatever key was important to getting it done.

The bottom line is that the programmer in me LOVES when this happens, but it's important to balance this and not let it get out of hand, escpecially if you have a family.


问:
Where are C variables declared
I see a lot of code with variables declared right after the function, but when I post something like that people end up mad and say it is better to declare them when they are used.

I assume this all compiles to the same executable, so it is simply a matter of style. As far as I can tell, pretty much all C code (99.9% that I've seen) declares them near the beginning and this is how it has been done for many years.

So why do people keep suggesting that they are declared closer to the block that uses them?

答:
You must be looking at very old code, code written by people that are either not up to date on their skills, or code written by people that enjoy writing Pascal in C.

Older versions of the C language spec (C89 and prior) required the declarations to be immediately following the opening brace, but since then modern compilers have eliminated that requirement.

See https://stackoverflow.com/questions/14324546/why-do-the-older-c-language-specs-require-function-local-variables-to-be-declare for more information.

Title: Where are C variables declared


答: You must be looking at old code or code written only on Windows. K&R C and C89 required variables to be declared at the beginning of a block. C99 allows variables to be declared anywhere before they are used. The GNU C compiler has supported flexible declaration as a non-standard extension for some time. Microsoft didn't have any support for the C99 standard until Visual Studio 2013</p>

Title: Where are C variables declared

Body:
I see a lot of code with variables declared right after the function, but when I post something like that people end up mad and say it is better to declare them when they are used.

I assume this all compiles to the same executable, so it is simply a matter of style. As far as I can tell, pretty much all C code (99.9% that I've seen) declares them near the beginning and this is how it has been done for many years.

So why do people keep suggesting that they are declared closer to the block that uses them?


问:
Learning but then forgetting
I am teaching myself to program in C and have been for a few months. I recently took a one month break and came back a week ago, and it's all gone. I had to look up some things that I really put effort into understanding (see: pointers) and some others just stuck with me. Now learning about malloc and dynamically allocated memory is also getting a bit tough.

What do you suggest for keeping it all retained? Will it just come with time and experience?

答: Practice, practice, practice. You'll still forget things that you haven't used for a while, but the more you practice, the faster they'll come back to you. Also, (in line with @Telastyn's comment), emphasize understanding things, not memorizing them.</p>

Title: Learning but then forgetting


问:
Quantifying the advantages of a modern version control system
I've worked as a team lead/developer in a large financial enterprise environment for the better part of three years. Our production release process is a nightmare because it revolves around Clearcase. We have a change management group who executes all releases and who will only allow code into production that was taken from it.

One of the first things I did when joining was to set my team up with Git. Everyone agreed that Clearcase was awful and was impractical for handling day-to-day source control matters. So we set up a sort of "unofficial" repository on my local machine and I wrote a script to sync our git and Clearcase repos around release time.

Word of this spread to other teams and several have adopted the same process. Using git in an "unofficial" manner for day-to-day activities and "officially" using Clearcase for releases. I've become sort of the go to guy for any issues with Git.

So I have a meeting this week with the SVP in change of infrastructure who specifically wants me to explain to her the merits of Git. Word apparently got to her of my frequent rants on Clearcase. If she accepts my arguments, I will have a real shot at helping my employer rid themselves of this abomination.

My experience with executives tells me they a) want extremely terse explanations for everything b) are only interested in facts that involve dollar figures

To a developer I can explain the merits of Git over Clearcase (or ANY other version control system over Clearcase for that matter), but I'm drawing a blank on how to do this to a technical executive without a technical background (she has an MBA and did her undergrad in geography).

I feel any argument I make to her is either going to sound like technical gibberish or that I'm evangelizing my personal preferences.

What I'm trying to find are concrete facts demonstrating developers work more effectively with Git, or ANY modern source control system.

I think that the fact the other teams have started using Git internally is a meaningful sign, but it's still not strong enough because it can still be dismissed as personal preference.

What I really need is something powerful enough to break through the "This process has worked for 20 years, why should we change it?" argument.

答:
I've been in very similar situations (in the aerospace and automotive industries). Don't expect to progress very far in this or subsequent meetings. Both of these situations outlasted my desire to continue fighting for improvement, but here is the best tactic I've seen so far...

You say "this process has worked for 20 years", but has it really? Start by outlining what you mean by "our production release process is a nightmare". Create a list of issues with the current process/tool that is as agnostic of ClearCase as possible.

Then, create a list of process/tool "solutions" that are as agnostic of Git as possible (though Git or any modern DVCS will like fit the bill exactly). Explaining why Git is better than ClearCase means nothing to non-users.

Allow the infrastructure team to confirm that the current approach has the issues you identify. This will likely lead them to seek support from IBM to "fix" these issues. Remain connected to ensure IBM doesn't side step the issues. Because ClearCase lacks the basic properties of our modern understanding of version control, most of these issues can't be fixed or will require a major infrastructure change.

Hopefully by this point, the infrastructure team will see this as a business problem, but one without an easy solution. At this point, you offer to benchmark additional solutions with estimated costs. Since many of your teams are already using Git, you should be able to remove training as an expense.

Good luck!


问:
Linked list clarification
This is a pretty simple question but I'm new to java.

The linked list found in java.util.LinkedList.

I saw elsewhere that Java does not use pointers...

When I create a new list and add new elements to it, does the list contain references to the data and to the next/previous elements or does it also contain the object itself.

答:
LinkedList uses index to store elements

Elements are point(linked) to each other

There are 3 types of linked list

1.singly linked list  = each node point the next node. (x)--->(y)--->(z)--->nothing

2.doubly linked list  = each node point to next and previous node  . (x)<-->(y)<-->(z)

3.circularly linked list. =  each node point to next node (like singly-linked lists) last node and fist node linked
                                            (x)--->(y)--->(z)--->(x)

Title: Linked list clarification


答:
Typically, the ways in which people learn are:

Read about the concepts

Read the available source code

Implement the given source code and exercises

This works very well for short-term memorization and learning. However, there are a few factors which help the transition from "memorization" to "gut-feel".

First, have a simple but clear-cut objective, for example, "I want to develop a replacement for Notepad". Everything you learn should be driven by the needs of this app. When you say, "Now how do I show this white area on the screen", look it up, learn it, implement it.

The next time you reach for the same concept, you will remember that context and trigger your memory. You'll think: "I remember that place where I had to use those pesky pointers because of {xyz}." That's how the brain learns and remembers!

Don't stop at one program, try a variety of different ones. You will eventually touch most of the common concepts of your selected language.

You'll slowly gain confidence and try more advanced programs as you go along. Keep it practical and driven by real goals. Keep it simple, and keep it fun.

This sermon brought to you by the SE network. Thank you for listening! :)

Title: Learning but then forgetting

Body:
I am teaching myself to program in C and have been for a few months. I recently took a one month break and came back a week ago, and it's all gone. I had to look up some things that I really put effort into understanding (see: pointers) and some others just stuck with me. Now learning about malloc and dynamically allocated memory is also getting a bit tough.

What do you suggest for keeping it all retained? Will it just come with time and experience?


答: Another Great way is to TEACH, I know it may seem strange,But As soon as you learn teach that stuff to some one, Because while teaching the brain works different, you have to think how the person in front of you is thinking, he will ask you many doubts and you always have to Say the same thing again and again but with different angles.This will make you understand and remember concepts permanently. </p>

Title: Learning but then forgetting


答:
It's definitely a very efficient way to work if your life revolves around work.

I've been through a time where I had the same problem.  I worked all the time and wouldn't stop until I came to a point where everything was tied up and I could sit down next time with a completely clean slate.  Unfortunately, if not controlled, it can cut into time with family, friends, and other hobbies.

Here are some tips that helped me focus my habit into something a little more manageable:

Check in early and often.  Make smaller changes so that a stopping point is closer!

Use GTD.  Working in tasks forces you to break down your work into smaller chunks, so you have more stopping points.

Use and stick to your calendar.  Pen (don't pencil) in events or sleep or food or whatever into your schedule and stick to it.  Set up reminders ahead of time so you can be aware that you need to get to a stopping point soon.


答:
Our production release process is a nightmare because it revolves
  around Clearcase. We have a change management group who executes all
  releases and who will only allow code into production that was taken
  from it.

No, your process is a "nightmare" because of your change management group and your release procedures. Go ahead and replace Clearcase for SVN or git or Fossil. You'll have the exact same problems. (I think they're doing it right TBH, strong release controls are essential).

This is what you need to focus on, not the geeky credentials of git (which are irrelevant to all but the devs), you need to focus on the business case for changing the process to mae it less onerous. Chances are you can do that using Clearcase, but it gives you an opportunity to sneak the idea of using git in anyway.

If you don't look at the "bigger picture" here, the best case you'll get it to use git with the same restrictions the release group require. IF you do consider the wider aspects of what change control is for, then you'll appreciate the restrictions you'll have to implement to make git useful in the kind of strongly-controlled release process your org needs.

Some ideas for you: Get them to see the productivity issues with the current system from a developer point of view. Do this as part 1 of 2. Part 2, go and work with them on a release so you can see the control issues that you developers need to understand. Treat it as a learning exercise for both sides to view the other side's view, and then you should be better able to come up with a solution that still solves the major requirements either side has. Note that releases are more important than dev, so you should be the one prepared to give ground more than you expect them to.

Once you have the knowledge of what's required for releases, you should agree to write up a process document detailed (with steps-to-follow kind of detail) that you can show them giving them what they need. How you can massage this so the dev side is better for you is up to you. I imagine they don't really care how dev does dev, as long as the source is properly managed and releases correctly organised - that means you'll have to show how code changes can be tied to change tickets, how to take code that made a release to patch, build and re-release it.

Title: Quantifying the advantages of a modern version control system

Body:
I've worked as a team lead/developer in a large financial enterprise environment for the better part of three years. Our production release process is a nightmare because it revolves around Clearcase. We have a change management group who executes all releases and who will only allow code into production that was taken from it.

One of the first things I did when joining was to set my team up with Git. Everyone agreed that Clearcase was awful and was impractical for handling day-to-day source control matters. So we set up a sort of "unofficial" repository on my local machine and I wrote a script to sync our git and Clearcase repos around release time.

Word of this spread to other teams and several have adopted the same process. Using git in an "unofficial" manner for day-to-day activities and "officially" using Clearcase for releases. I've become sort of the go to guy for any issues with Git.

So I have a meeting this week with the SVP in change of infrastructure who specifically wants me to explain to her the merits of Git. Word apparently got to her of my frequent rants on Clearcase. If she accepts my arguments, I will have a real shot at helping my employer rid themselves of this abomination.

My experience with executives tells me they a) want extremely terse explanations for everything b) are only interested in facts that involve dollar figures

To a developer I can explain the merits of Git over Clearcase (or ANY other version control system over Clearcase for that matter), but I'm drawing a blank on how to do this to a technical executive without a technical background (she has an MBA and did her undergrad in geography).

I feel any argument I make to her is either going to sound like technical gibberish or that I'm evangelizing my personal preferences.

What I'm trying to find are concrete facts demonstrating developers work more effectively with Git, or ANY modern source control system.

I think that the fact the other teams have started using Git internally is a meaningful sign, but it's still not strong enough because it can still be dismissed as personal preference.

What I really need is something powerful enough to break through the "This process has worked for 20 years, why should we change it?" argument.


问:
When would you want two references to the same object?
In Java specifically, but likely in other languages as well: when would it be useful to have two references to the same object?

Example:

```<code>Dog a = new Dog();
Dob b = a;
</code>```

Is there a situation where this would be useful? Why would this be a preferred solution to using a whenever you want to interact with the object represented by a?

答:
Of course, one other scenario where you might end up with:

```<code>Dog a = new Dog();
Dog b = a;
</code>```

is when you're maintaining code and b used to be a different dog, or a different class, but now is serviced by a.

Generally, in the medium term, you should rework all the code to refer to a directly, but that may not happen straight away.

Body:
Of course, one other scenario where you might end up with:

Dog a = new Dog();
Dog b = a;

is when you're maintaining code and b used to be a different dog, or a different class, but now is serviced by a.

Generally, in the medium term, you should rework all the code to refer to a directly, but that may not happen straight away.


问:
Hot swap/plug components in clojure?
I'm using OSGi for some time and I really like the ability to swap/replace components while my application is running. I simply have to build my module and push it to the OSGi container.

Is there a similar concept/framework for clojure?

I know about leiningen's dependency management which really helps modularity but I know of no built-in way to hot swap code.

答:
The notion of "hot swapping" doesn't really make sense in Clojure, at least not as something different from normal. It's always possible to change things by re-evaluating the code that you want to change.

It's worth having a look at pomegranate which allows you to dynamically add new dependencies.

Title: Hot swap/plug components in clojure?