#and it can do the immutable section concurrently
Explore tagged Tumblr posts
ceausescue · 2 years ago
Text
been consumed with the idea for the worst programming language in the world. a lisp 2 with clojure syntax, bytecode interpreted. with goroutines. like janet written by a moron, like common lisp written by someone who hates themselves. hand rolled garbage collector that has to deal with all the intermediate objects from immutable types. im tagging like 11 bits out of every pointer, 3 on the small end and 8 suspended in the middle of the top 16, which is a violation of the geneva convention. none of those bits encode the type and im still boxing floats. pretty sure i worked out how to support special environments that compile to totally untypechecked machine code for fast math. came up with an inline assembly thing for it i might just expose to the user. i don't expect ill ever bother with networking
0 notes
siva3155 · 5 years ago
Text
300+ FRESHERS JAVA Interview Questions and Answers
java Interview Questions for freshers :-
1. What is Java? Java is a object-oriented programming language originally developed by Sun Micro systems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. 2. What is serialization? Serialization converts an object to a stream of bytes for safety purposes. We can save it as a file, store in DB or send it by the network. We can also recreate the state of an item when needed. 3. What is a Java virtual machine? JVM helps the computer to run the Java program or other languages. It acts as a run-time engine. Java code is compiled into bytecode to run on any computer. 4. What is constructor? It is an instant and special method having the same name as the class. A constructor can be overloaded and a section of code to load newly created objects. If a constructor is created with a parameter then another constructor can be created without a parameter. 5. Describe variables? Name them A name for a memory location is variable. And it is called a basic unit of storage in a program. You can change the stored value during the program execution. Local variables Instant variables Static variables 6. What is the classloader? Classloader is a Java runtime environment to load Java classes into Java virtual machine. It loads class files from the network, file system, and other sources. In java, there is 3 built-in classloader. Extension System/application Bootstrap 7. What are the wrapper class? A wrapper class wraps or contains primitive data types. The Java primitives change into the reference types. It contains a field when we create an object. Primitive data types are stored in this field. Thus a primitive value is also be wrapped. 8. Define a package and its advantages? The collection of classes, sub-packages, and interfaces are bundled together is called packages. We can modularize the code and optimize its reuse. The code can also be imported by other classes and reused. It helps to remove name clashes. Provide access protection to manage the code. The classes and interfaces are easily maintained because of proper structure. It contains hidden classes to use within the packages. 9. What is the JIT compiler? JIT is a program to help in changing the Java bytecode into instructions. It improves the performance of Java applications at the run time and known as the integral parts of the Java Runtime Environment. 10. What are the special keywords in Java? Name them The special keywords in Java are access modifiers. Constructor, variable, scope of a class, data member or method is restricted. Default, private, protected and the public are four types of access modifiers.
Tumblr media
java Interview Questions for freshers 11. What are garbage collectors? and types. It implicit memory management and destroy the unused objects to relieve the memory. It automatically removes the unreferenced objects to make the memory efficient. There are 4 types of garbage collectors. Serial garbage G1 garbage CMS garbage Parallel garbage 12. Tell the smallest piece of programmed instructions? How does it create? A thread, A scheduler executes independently. All programs having one thread is called the main thread. JVM creates the main thread when the program starts its execution. The main ( ) of the program is invoked by the main thread. Thread is created – By implementing the Runnable interface and extending the thread. 13. What executes a set of statements? Finally block always executes a set of statements. It is with a try block of any exception occurs or not. It does not execute the program by calling System.exit( ) or by a fatal error. 14. What refers to Multi-threading? Synchronization, it keeps all concurrent threads in execution. Memory consistency errors are avoided by synchronization. Execution of multiple threads accesses the same objects and fields. The thread holds the monitor when the method is considered as synchronized. 15. Tell the purpose of final, finally and finalize? Final cannot be overridden, inherited or change. For restrict the class, variable and method. Finally, is used for putting important code and executed the exception is handled or not. Finalize is for cleaning up processing before the object is collected in the garbage. 16. Where we use a different signature? In method overloading signature must be different. The same class method shares the same name. Every single method should be the indifferent number of parameters or different orders or types of parameters. For “adding” or “extending” and known as a compile-time polymorphism. 17. What is Run-time polymorphism? Method Overriding is run-time polymorphism having the same signature. Inheritance is required in Method Overriding. It is used to change existing behavior. The subclass has the same method od same number, name, parameters, return type. 18. Name the method that belongs to the class? In Java, the static method belongs to the class and access only static data. It calls only other static methods and directly accessed by the class name. To define variables, static is used. 19. Describe Object-oriented paradigm? The programming paradigm based on data and methods is called object-oriented programming. Paradigm incorporates the advantages of reusability and modularity. Objects are instances of classes to interact with one another. It designs programs and applications. 20. In Java, what is an object? A real-time entity of some behavior and state is called an object. It is an instance of a class with instance variables. The new keyword is for creating the object of the class. 21. What is an object-based programming language? JavaScript, VBScript is an object-based language and has in-built objects. All the concepts of OOPs such as polymorphism and inheritance are not followed by object-based languages. 22. Name the constructor used in Java? Default constructor – It is used to perform the task on object creation and to initialize the instance variable with default values. The constructor does not accept any value. If no constructor is defined in the class, then a default constructor is invoked implicitly by the compiler. Parameterized constructor – This constructor accepts the arguments. It initializes the instance variables with the given values. 23. How to copy the values of the item to others in Java? We can print the values by using the constructor, to allow the values of one object to other and the design of clone. In Java, there is no copy constructor. 24. Explain the Java method? The Java method is invoked explicitly and is to disclose the nature of an item, it has an entry. Its name is not the same as the class name. It is not given by the finder. 25. Describe the static variables? The static variable belongs to the class and makes the memory-efficient of the program. It refers to the common property of all objects. At the moment when class is loading, it gets the memory in the department field. 26. What is aggregation? Aggregation is described as a has-a relationship and has an entity reference. And having a relationship between two classes. The weak relationship is represented by aggregation. 27. What is a super keyword? Mention its uses. The Super keyword is a hint variable is to mention at once parent class item with the concept of inheritance, the keyword comes into the picture. It appeals soon the parent class technique and constructor. Refers directly parent class instance variable. It is used to initialize the base class variables. 28. What is method overriding? Name the rules and use them. In Java method overriding is when a subclass has the specific implementation or the same method as in the parent class. Rules : It should have the same name and signature as in the parent class. IS-A relationship should be in between two classes. Uses : For runtime polymorphism To give the specific implementation already provided by its superclass. 29. What are polymorphism and its types? Polymorphism is used in a different context and define the situations. When a single object refers to the super or sub-class depends on the reference type is polymorphism. Many forms are considered as polymorphism. 30. Explain the OOPs concepts in Java? For programmers to create the components for re-using in different ways. OOPs is known as programming style. The four concepts are Abstraction Inheritance Polymorphism Encapsulation Interface 31. What is stored in a heap memory? Java String pool is a collection of Strings are stored. If you create a new object, the string pool confirms the object is in the pool or not. The same reference is returned to the variable if it is already in the pool. 32. How to call one constructor to another to the current object? By constructor chaining. It is occurred by inheritance. The task of a subclass constructor is to call the superclass constructor. There are two ways to do constructor chaining. Within the same class using the keyword “this” ( ) From base class using the keyword “super” ( ) 33. Tell the nature of Java strings? The nature of string objects are immutable which is cached in the string pool. The state of string object cannot be modified after the creation. Java creates a new string object if you update the value of the particular object. 34. What is the interface of the Util package? It’s characteristics. Map in Java is the interface of the Util package. It is used to map a key and a value. It is different from other collection types. And it is not the subset of the main collection interface. Duplicate keys are not contained The order of a map is depending upon the specific implementation 35. Describe Java Stack memory? Stack memory is in the Last-In-First-Out order to free memory. It is used for the execution of a thread. It contains local primitives and reference to other objects. To define the stack memory, we use –Xss. The memory of the stack is considered short-lived. 36. Why Runnable Interface is used in Java? Runnable interface is used in java for implementing multi threaded applications. Java.Lang.Runnable interface is implemented by a class to support multi threading. 37. What are the two ways of implementing multi-threading in Java? Multi threaded applications can be developed in Java by using any of the following two methodologies: By using Java.Lang.Runnable Interface. Classes implement this interface to enable multi threading. There is a Run() method in this interface which is implemented. By writing a class that extend Java.Lang.Thread class. 38. When a lot of changes are required in data, which one should be a preference to be used? String or StringBuffer? Since StringBuffers are dynamic in nature and we can change the values of StringBuffer objects unlike String which is immutable, it's always a good choice to use StringBuffer when data is being changed too much. If we use String in such a case, for every data change a new String object will be created which will be an extra overhead. 39. What's the purpose of using Break in each case of Switch Statement? Break is used after each case (except the last one) in a switch so that code breaks after the valid case and doesn't flow in the proceeding cases too. If break isn't used after each case, all cases after the valid case also get executed resulting in wrong results. 40. How garbage collection is done in Java? In java, when an object is not referenced any more, garbage collection takes place and the object is destroyed automatically. For automatic garbage collection java calls either System.gc() method or Runtime.gc() method. 41. How we can execute any code even before main method? If we want to execute any statements before even creation of objects at load time of class, we can use a static block of code in the class. Any statements inside this static block of code will get executed once at the time of loading the class even before creation of objects in the main method. 42. Can a class be a super class and a sub-class at the same time? Give example. If there is a hierarchy of inheritance used, a class can be a super class for another class and a sub-class for another one at the same time. In the example below, continent class is sub-class of world class and it's super class of country class. public class world { .......... } public class continenet extends world { ............ } public class country extends continent { ...................... } 43. How objects of a class are created if no constructor is defined in the class? Even if no explicit constructor is defined in a java class, objects get created successfully as a default constructor is implicitly used for object creation. This constructor has no parameters. 44. In multi-threading how can we ensure that a resource isn't used by multiple threads simultaneously? In multi-threading, access to the resources which are shared among multiple threads can be controlled by using the concept of synchronization. Using synchronized keyword, we can ensure that only one thread can use shared resource at a time and others can get control of the resource only once it has become free from the other one using it. 45. Can we call the constructor of a class more than once for an object? Constructor is called automatically when we create an object using new keyword. It's called only once for an object at the time of object creation and hence, we can't invoke the constructor again for an object after its creation. 46. There are two classes named classA and classB. Both classes are in the same package. Can a private member of classA can be accessed by an object of classB? Private members of a class aren't accessible outside the scope of that class and any other class even in the same package can't access them. 47. Can we have two methods in a class with the same name? We can define two methods in a class with the same name but with different number/type of parameters. Which method is to get invoked will depend upon the parameters passed. For example in the class below we have two print methods with same name but different parameters. Depending upon the parameters, appropriate one will be called: public class methodExample { public void print() { system.out.println("Print method without parameters."); } public void print(String name) { system.out.println("Print method with parameter"); } public static void main(String args) { methodExample obj1 = new methodExample(); obj1.print(); obj1.print("xx"); } } 48. How can we make copy of a java object? We can use the concept of cloning to create copy of an object. Using clone, we create copies with the actual state of an object. Clone() is a method of Cloneable interface and hence, Cloneable interface needs to be implemented for making object copies. 49. What's the benefit of using inheritance? Key benefit of using inheritance is reusability of code as inheritance enables sub-classes to reuse the code of its super class. Polymorphism (Extensibility ) is another great benefit which allow new functionality to be introduced without effecting existing derived classes. 50. What's the default access specifier for variables and methods of a class? Default access specifier for variables and method is package protected i.e variables and class is available to any other class but in the same package,not outside the package. 51. Give an example of use of Pointers in Java class. There are no pointers in Java. So we can't use concept of pointers in Java. 52. How can we restrict inheritance for a class so that no class can be inherited from it? If we want a class not to be extended further by any class, we can use the keyword Final with the class name. In the following example, Stone class is Final and can't be extend public Final Class Stone { // Class methods and Variables } 53. What is Java? and how does Java enables high performance? Java is a platform-independent, object-oriented, portable, multi-thread, high-level programming language. The collection of objects is considering as Java. We use Java for developing lots of websites, games and mobile applications. For high performance, Java uses Just in time compiler. java Interview Questions and Answers for freshers Pdf free Download Read the full article
0 notes
a-coda · 8 years ago
Text
Bravely Truthy
"Lisp is worth learning for the profound enlightenment experience you will have when you finally get it; that experience will make you a better programmer for the rest of your days, even if you never actually use Lisp itself a lot." -- Eric Raymond, "How to Become a Hacker"
We've had a lunchtime group at Linguamatics reading "Clojure for the Brave and True" by Daniel Higginbotham. It seemed like a fun and light-hearted way to introduce ourselves to some Clojure. Previously we had had some dedicated individuals working their way through SICP.
"Clojure for the Brave and True" is a basic introduction to functional programming and immutable data structures with details about macros, multimethods, protocols, records, and concurrency. It was the latter I was particularly interested in after reading Paul Butcher's book on concurrency models. I had subsequently flirted with ClojureScript, but now it was time for some Clojure.
Our process was fairly lightweight. We assigned ourselves a chapter or two to read per week and then we discussed the highlights while projecting the relevant sections. The book is free online, but at least one of us did buy the physical book. We also skipped the environment configuration chapters and left individuals to sort it out in their own time. And we weren't too dedicated in doing the end-of-chapter exercises, but we did talk through them if anyone had had a go. (I know this is a failure from the point of Pragmatic Thinking and Learning!)
One aspect of the book that stands out is its very quirky style. The author is clearly a fan of Dungeons and Dragons and it pervades the book, including the illustrations. At times the style felt a bit puerile, but it was light and easy to read.
Anyway, on to the concurrency. Clojure's overall approach is to avoid having to control shared access to modifiable state via locking and mutual exclusion. The book covered atoms, refs, vars, and core.async. Clojure has immutable data structures but can share changes between threads via atoms, which can have their state (compared and) swapped atomically. It can also share them via refs where Clojure uses a Software Transactional Memory mechanism. This rolls back and retries in the event of conflicting updates (like a database transaction). Finally, the core.async chapter covers processes, channels, and events. With these you can build concurrent processes communicating solely via messages on channels.
Overall, it was a nice light introduction. The style might not suit everyone and there were some glitches: like the threading macros -> and ->> being used in examples in a chapter before being introduced. However, one big issue for us was the book didn't cover all of Clojure's concurrency mechanisms. In particular, we didn't get an introduction to reducers or agents.
I haven't found an introduction to Clojure agents yet. Do we just have to read the reference manual? Fortunately the author has written a book on reducers called "Parallel Programming in Clojure with Reducers". The first chapter is free online so we can sample before deciding whether to tackle the topic.
Actually, the word "tackle" reminds me. I know a much more sinister definition of reducer. Hopefully, Clojure reducers aren't going to be such a painful deterrent:
reducer: football term, by where a player (usually of lesser ability) will attempt to tackle an opposition player (usually of superior ability) in a grossly unfair and extremely violent manner, so as to let the opposition player know that if he values his family jewels then today might be a good day to have an "off day". The reducer is often aimed at knee height of the opposition player (or in extreme cases, the testicles), and will usually take place in the first few minutes of the game. -- Urban Dictionary
1 note · View note
simonconsultancypage · 6 years ago
Text
A Critique of the Delaware Chancery Court Decision on Federal Forum Provisions
After the U.S. Supreme Court’s March 2018 decision in the Cyan case that state courts retain concurrent jurisdiction for ’33 Act liability actions, one idea that circulated was that companies could avoid securities class action lawsuits in state court by adopting a charter provision designating a federal forum for these kinds of suits. Unfortunately, in December 2018, Delaware Chancery Court Vice Chancellor Travis Laster held in Sciabacucchi v. Salzburg that under Delaware law federal forum provisions are invalid and ineffective, as discussed here. The Sciabacucchi decision, which is now on appeal, is the subject of a comprehensive critique in a recent article by Stanford Law Professor Joseph Grundfest, entitled “The Limits of Delaware Corporate Law: Internal Affairs, Federal Forum Provisions, and Sciabacucchi” (here). Professor Grundfest argues that Sciabacucchi was wrongly decided and that a under a “straightforward” application of applicable Delaware statutory law, federal forum provisions are valid and permitted.
  It is important to note at the outset, as Professor Grundfest acknowledges in footnote one in his paper, that Grundfest himself developed the concept of the federal forum provision and drafted the federal forum provision language that was in dispute in the Sciabacucchi case. Indeed, in the parties’ pleadings in Sciabacucchi, the use of federal forum provisions was referred to as the “Grundfest solution,” and so Grundfest’s interest in these issues is, as he acknowledges in the footnote, “paternal.”
  Background on State Class Action Securities Litigation
Professor Grundfest opens the substantive portion of his paper with a review of the problems that state court securities actions create. First, as his paper statistically demonstrates, state court securities class action litigation, which actually began to accumulate even before Cyan, has grown significantly since the case was decided, to the point that now 76 percent of Section 11 cases are brought either in state court alone or in parallel state and federal actions.
  Plaintiffs, Professor Grundfest notes, have significant incentives to “migrate” their cases to state court, as state court pleading standards are more plaintiff-friendly; as state courts do not uniformly apply the discovery stay in federal court; and as there is no process in state court for consolidating duplicate proceedings.
  Plaintiffs’ attraction to state court arguably is statistically justified, as between 2011 and 2018, the dismissal rate for state court Section 11 actions was only 19 percent, while the dismissal rate in federal court was 45 percent. Increased likelihood of surviving dismissal and increased uncertainty has meant that state court securities suits at higher values than do comparable federal court actions. Among other things as a result of these considerations, the cost of D&O insurance for IPO companies has risen materially in the wake of Cyan, as Professor Grundfest’s paper details statistically. Readers of this blog will find the paper’s discussion of the D&O insurance issues particularly interesting.
  Background on Litigation Management Bylaws
The idea for companies to adopt bylaw provisions specifying a federal forum arose out of the larger discussion in recent years for companies to manage their litigation risks by adopting litigation management bylaws. In 2013, then-Chancellor Leo Strine Jr. held (as discussed here) in the Chevron case that corporations can adopt bylaws designating a preferred forum for litigation “relating to the internal affairs of the corporation.”  A 2014 Delaware Supreme Court decision in the ATP Tour case (discussed here) also upheld the validity of a bylaw provision shifting fees to an unsuccessful litigant in a shareholder claim. However, in 2015, the Delaware legislature enacted a provision barring fee-shifting bylaws, while codifying the right of Delaware corporations to designate Delaware as the preferred forum for shareholder disputes.
  The Sciabacucchi Case
With the idea circulating that companies should adopt federal forum provisions, a number of IPO companies adopted bylaws designating a federal forum “for the resolution of any complaint asserting a cause of action under the Securities Act of 1933.” Among the IPO companies adopting these kinds of provisions were Blue Apron, Stitch Fix and Roku. Matthew Sciabacucchi bought shares in all three companies. He then filed an action in Delaware Chancery Court seeking a judicial declaration that the companies’ federal forum provisions are invalid.
  In December 2018, Vice-Chancellor Laster granted Sciabacucchi’s motion for summary judgment, holding under Delaware law the provisions are invalid and unenforceable. In reaching this ruling, Vice-Chancellor Laster said that while Delaware law permits companies to adopt a forum selection clause for “internal affairs” claims, owing to what Laster describes as “first principles” Delaware law “does not authorize a Delaware corporation to regulate external relationships.” A ’33 Act liability action, Vice-Chancellor Laster said, “is external to the corporation,” as “Federal law creates the claim, defines the elements of the claim, and specifies who can be a plaintiff or a defendant.”
  While Delaware law has certain authority on internal matters related to the company’s organization, that authority “does not extend to its creation’s external relationships.” The state’s authority, Laster said, does not extend, for example, to tort claims asserted against the company.” A state’s corporate charter “cannot bind a plaintiff to a particular forum when the claim does not involve right or relationships that were established under Delaware law.” Since that is what the federal forum provisions do, they are therefore “ineffective and invalid.”
  Professor Grundfest’s Critique
Professor Grundfest’s paper presents a multi-part attack on Vice-Chancellor Laster’s ruling in Sciabacucchi. As an initial matter, Grundfest challenges Laster’s reliance on sweeping “first principles” to invalidate the federal forum provision. Under these “first principles,” Laster said, when “the claim exists outside the corporate contract, it is beyond the power of corporate law to regulate.” The implications of this suggestion, Grundfest says, “reach far beyond the four corners of Federal Forum Provisions and articulate a novel principle that would constrain all of the past and future Delaware corporate law.”
  The further problem with the “first principles” analysis is the suggestion that without these constraints, Delaware might interpret its own laws to allow regulation, say, of tort or contract claims. The “easy answer to these concerns is that none of them could arise in the context of federal forum provisions, and other forum provisions are not at issue. Delaware, Grundfest says, “can address those concerns if and when those provisions arise in a real case or controversy.”
  The Sciabacucchi decision, Grundfest contends, is “highly contestable.” Among other things, Grundfest argues that the decision is against controlling U.S. and Supreme Court precedent. Laster concluded that that the federal forum provision is “contrary to the federal regime,” while disregarding the U.S. Supreme Court’s 1989 decision in Rodriguez de Quijas v. Shearson/American Express, Inc., which, Grundfest asserts, the Court “conclusively establishes that plaintiffs have no immutable right to litigate Securities Claims in state court and enforces a contract of adhesion prohibiting state court litigation of Securities Act claims.” Yet, Grundfest notes, Sciabacucchi nowhere mention the Rodriguez claim. Moreover, Grundfest notes, by invalidating a federal practice governing a federal claim that is consistent with federal law, Sciabacucchi “imposes a restraint on federal practice that appears nowhere in federal law,” and “creates an unprecedented intrusion by Delaware law into the federal space.”
  A further “problem” with Sciabacucchi is that it assumes that Securities Act plaintiffs are never existing stockholders to whom fiduciary duties are owed – a proposition, Grundfest notes, for which the Sciabacucchi opinion offers no factual support. In fact, Professor Grundfest notes, numerous SEC filings show that existing holders purchase additional shares in both IPOs and follow-on offerings, and these purchasers are owed fiduciary duties in connection with the statements made in the registration statements.
  Sciabacucchi’s “internal affairs” analysis is also “problematic” as it “diverges from precedent” to “invent a materially narrow definition” of the term “internal affairs.” Both U.S. Supreme Court and Delaware’s definition of internal affairs are broader and more encompassing, yet Sciabacucchi “offers no rationale for its divergence from controlling precedent.”
  The decision’s application of its “divergent definition” of “internal affairs” is “additionally problematic” in its conclusion that Securities Act claims are “always external.” However, Delaware precedent establishes that an act can simultaneously be an internal violation of Delaware law or violate a federal law. Indeed, Grundfest argues, the “due diligence” defense to Section 11 claims necessarily entails a close inquiry into the actions and awareness of board members, all matters that are “entirely internal.”
  The court’s decision is also “problematic” from a policy perspective. If the board processes that caused the filing of a defective registration statement are external, then “a host of boardroom functions” previously considered internal become “amenable to regulation by sister states.” This “trajectory” is “inimical to Delaware’s interest in regulating the internal functioning of Delaware-chartered entities.” Moreover, Sciabacucchi’s “first principles” analysis, and its implied constraints on legislative action “veers Delaware’s judiciary into the Legislature’s lane, as well as into the federal lane.”
  All of these problems, Grundfest suggests, can be avoided by a “straightforward” interpretation and application of Delaware’s statutory law. A textualist reading of the statutes avoids “all of the concerns that inspire the invention of a divergent ‘internal affairs’ definition.” Sections 102(b)(1), 115, and 202 of the DGCL “unambiguously support the validity of Federal Forum Provisions and nothing in Sciabacucchi suggests Federal Forum Provisions are inconsistent with the plain text.” The statutory text also answers the concern about the possibility of charter provisions seeking to address, for example, tort or contract law. Sections 102 and 115 both refer to provisions relating to directors, officers, and shareholders “in their capacities as such,” which would take out the concern about charter provisions spilling into a host of other matters.
  Discussion
Grundfest’s paper is massive and detailed. It is always a challenge attempting to summarize anything as vast and sweeping as this paper and it is a particular challenge to do so within the constraints of the blogging format. I hope my summary here does justice to Grundfest’s extensive effort.
  While Grundfest’s arguments are numerous and extensive, several basic things stand out. The first is that he thinks that Vice-Chancellor Laster really got it wrong in Sciabacucchi. In Grundfest’s view, the decision disregards important federal and Delaware precedent and relies on assumptions of fact that are “demonstrably incorrect.”
  The other thing that is clear is that Grunfest continues to believe that federal forum provisions are a good idea and are permissible under Delaware statutory law. I should note here that in the interests of brevity, I telescoped Grundfest’s affirmative case that the text of the relevant Delaware statutes supports companies’ adoption of federal forum provisions. It is in the nature of his paper that his critique of Sciabacucchi predominates the presentation.
  There is no mystery about the timing of Professor Grundfest’s paper. As I noted at the outset, Sciabacucchi is on appeal to the Delaware Supreme Court, and the parties have just entered the briefing phase of the appeal. Having originated and propagated the idea of federal forum provisions, Grundfest clearly has an interest in seeing his intellection creation survive legal scrutiny. His paper clearly bespeaks the fervor of his commitment to his project. The paper is a legal missile aimed at the Delaware Supreme Court.
  It will of course be very interesting to see how the appeal turns out. The larger problem for everyone is that the possibility of state court securities litigation has created a huge mess, adding complexity, confusion, and cost for companies and for their D&O insurers. We can also certainly hope that the Delaware Supreme Court concludes that federal forum provisions are permissible.
  However, unless and until that happens, the problems arising from the possibility of state court securities litigation will continue, causing all of the problems and concerns that Grundfest’s paper notes. For that reason, I continue to believe that the best approach would be for Congress to act and address this situation. SLUSA was clearly intended to force all securities litigation into federal court. However, Congress made a hash of things when it modified the jurisdictional provisions of the ’33 Act, and that is how the U.S. Supreme Court wound up concluding in Cyan, notwithstanding SLUSA, that state courts retain concurrent jurisdiction for Section 11 claims. While federal forum provisions are a good idea, the best thing would be for Congress to go back and clean things up.
  One final note. Grundfest’s paper is massive and could even be daunting for some. Just in case readers of this blog don’t manage to make their way through the text to see it, the insurance practitioners who read this blog will be particularly interested in the statistical analysis in Section II of Grundfest’s paper. The paper not only sets out interesting statistical information about state court securities litigation filings and resolutions, but it also lays out interesting and detailed information about how Cyan has affected the D&O insurance market for IPO companies. I am sure that many readers will find it well worth their time to work their way through both the litigation statistics and the insurance pricing information.
  Special thanks to the several readers who sent me a link to Professor Grundfest’s paper.
    The post A Critique of the Delaware Chancery Court Decision on Federal Forum Provisions appeared first on The D&O Diary.
A Critique of the Delaware Chancery Court Decision on Federal Forum Provisions published first on http://simonconsultancypage.tumblr.com/
0 notes
golicit · 6 years ago
Text
A Critique of the Delaware Chancery Court Decision on Federal Forum Provisions
After the U.S. Supreme Court’s March 2018 decision in the Cyan case that state courts retain concurrent jurisdiction for ’33 Act liability actions, one idea that circulated was that companies could avoid securities class action lawsuits in state court by adopting a charter provision designating a federal forum for these kinds of suits. Unfortunately, in December 2018, Delaware Chancery Court Vice Chancellor Travis Laster held in Sciabacucchi v. Salzburg that under Delaware law federal forum provisions are invalid and ineffective, as discussed here. The Sciabacucchi decision, which is now on appeal, is the subject of a comprehensive critique in a recent article by Stanford Law Professor Joseph Grundfest, entitled “The Limits of Delaware Corporate Law: Internal Affairs, Federal Forum Provisions, and Sciabacucchi” (here). Professor Grundfest argues that Sciabacucchi was wrongly decided and that a under a “straightforward” application of applicable Delaware statutory law, federal forum provisions are valid and permitted.
  It is important to note at the outset, as Professor Grundfest acknowledges in footnote one in his paper, that Grundfest himself developed the concept of the federal forum provision and drafted the federal forum provision language that was in dispute in the Sciabacucchi case. Indeed, in the parties’ pleadings in Sciabacucchi, the use of federal forum provisions was referred to as the “Grundfest solution,” and so Grundfest’s interest in these issues is, as he acknowledges in the footnote, “paternal.”
  Background on State Class Action Securities Litigation
Professor Grundfest opens the substantive portion of his paper with a review of the problems that state court securities actions create. First, as his paper statistically demonstrates, state court securities class action litigation, which actually began to accumulate even before Cyan, has grown significantly since the case was decided, to the point that now 76 percent of Section 11 cases are brought either in state court alone or in parallel state and federal actions.
  Plaintiffs, Professor Grundfest notes, have significant incentives to “migrate” their cases to state court, as state court pleading standards are more plaintiff-friendly; as state courts do not uniformly apply the discovery stay in federal court; and as there is no process in state court for consolidating duplicate proceedings.
  Plaintiffs’ attraction to state court arguably is statistically justified, as between 2011 and 2018, the dismissal rate for state court Section 11 actions was only 19 percent, while the dismissal rate in federal court was 45 percent. Increased likelihood of surviving dismissal and increased uncertainty has meant that state court securities suits at higher values than do comparable federal court actions. Among other things as a result of these considerations, the cost of D&O insurance for IPO companies has risen materially in the wake of Cyan, as Professor Grundfest’s paper details statistically. Readers of this blog will find the paper’s discussion of the D&O insurance issues particularly interesting.
  Background on Litigation Management Bylaws
The idea for companies to adopt bylaw provisions specifying a federal forum arose out of the larger discussion in recent years for companies to manage their litigation risks by adopting litigation management bylaws. In 2013, then-Chancellor Leo Strine Jr. held (as discussed here) in the Chevron case that corporations can adopt bylaws designating a preferred forum for litigation “relating to the internal affairs of the corporation.”  A 2014 Delaware Supreme Court decision in the ATP Tour case (discussed here) also upheld the validity of a bylaw provision shifting fees to an unsuccessful litigant in a shareholder claim. However, in 2015, the Delaware legislature enacted a provision barring fee-shifting bylaws, while codifying the right of Delaware corporations to designate Delaware as the preferred forum for shareholder disputes.
  The Sciabacucchi Case
With the idea circulating that companies should adopt federal forum provisions, a number of IPO companies adopted bylaws designating a federal forum “for the resolution of any complaint asserting a cause of action under the Securities Act of 1933.” Among the IPO companies adopting these kinds of provisions were Blue Apron, Stitch Fix and Roku. Matthew Sciabacucchi bought shares in all three companies. He then filed an action in Delaware Chancery Court seeking a judicial declaration that the companies’ federal forum provisions are invalid.
  In December 2018, Vice-Chancellor Laster granted Sciabacucchi’s motion for summary judgment, holding under Delaware law the provisions are invalid and unenforceable. In reaching this ruling, Vice-Chancellor Laster said that while Delaware law permits companies to adopt a forum selection clause for “internal affairs” claims, owing to what Laster describes as “first principles” Delaware law “does not authorize a Delaware corporation to regulate external relationships.” A ’33 Act liability action, Vice-Chancellor Laster said, “is external to the corporation,” as “Federal law creates the claim, defines the elements of the claim, and specifies who can be a plaintiff or a defendant.”
  While Delaware law has certain authority on internal matters related to the company’s organization, that authority “does not extend to its creation’s external relationships.” The state’s authority, Laster said, does not extend, for example, to tort claims asserted against the company.” A state’s corporate charter “cannot bind a plaintiff to a particular forum when the claim does not involve right or relationships that were established under Delaware law.” Since that is what the federal forum provisions do, they are therefore “ineffective and invalid.”
  Professor Grundfest’s Critique
Professor Grundfest’s paper presents a multi-part attack on Vice-Chancellor Laster’s ruling in Sciabacucchi. As an initial matter, Grundfest challenges Laster’s reliance on sweeping “first principles” to invalidate the federal forum provision. Under these “first principles,” Laster said, when “the claim exists outside the corporate contract, it is beyond the power of corporate law to regulate.” The implications of this suggestion, Grundfest says, “reach far beyond the four corners of Federal Forum Provisions and articulate a novel principle that would constrain all of the past and future Delaware corporate law.”
  The further problem with the “first principles” analysis is the suggestion that without these constraints, Delaware might interpret its own laws to allow regulation, say, of tort or contract claims. The “easy answer to these concerns is that none of them could arise in the context of federal forum provisions, and other forum provisions are not at issue. Delaware, Grundfest says, “can address those concerns if and when those provisions arise in a real case or controversy.”
  The Sciabacucchi decision, Grundfest contends, is “highly contestable.” Among other things, Grundfest argues that the decision is against controlling U.S. and Supreme Court precedent. Laster concluded that that the federal forum provision is “contrary to the federal regime,” while disregarding the U.S. Supreme Court’s 1989 decision in Rodriguez de Quijas v. Shearson/American Express, Inc., which, Grundfest asserts, the Court “conclusively establishes that plaintiffs have no immutable right to litigate Securities Claims in state court and enforces a contract of adhesion prohibiting state court litigation of Securities Act claims.” Yet, Grundfest notes, Sciabacucchi nowhere mention the Rodriguez claim. Moreover, Grundfest notes, by invalidating a federal practice governing a federal claim that is consistent with federal law, Sciabacucchi “imposes a restraint on federal practice that appears nowhere in federal law,” and “creates an unprecedented intrusion by Delaware law into the federal space.”
  A further “problem” with Sciabacucchi is that it assumes that Securities Act plaintiffs are never existing stockholders to whom fiduciary duties are owed – a proposition, Grundfest notes, for which the Sciabacucchi opinion offers no factual support. In fact, Professor Grundfest notes, numerous SEC filings show that existing holders purchase additional shares in both IPOs and follow-on offerings, and these purchasers are owed fiduciary duties in connection with the statements made in the registration statements.
  Sciabacucchi’s “internal affairs” analysis is also “problematic” as it “diverges from precedent” to “invent a materially narrow definition” of the term “internal affairs.” Both U.S. Supreme Court and Delaware’s definition of internal affairs are broader and more encompassing, yet Sciabacucchi “offers no rationale for its divergence from controlling precedent.”
  The decision’s application of its “divergent definition” of “internal affairs” is “additionally problematic” in its conclusion that Securities Act claims are “always external.” However, Delaware precedent establishes that an act can simultaneously be an internal violation of Delaware law or violate a federal law. Indeed, Grundfest argues, the “due diligence” defense to Section 11 claims necessarily entails a close inquiry into the actions and awareness of board members, all matters that are “entirely internal.”
  The court’s decision is also “problematic” from a policy perspective. If the board processes that caused the filing of a defective registration statement are external, then “a host of boardroom functions” previously considered internal become “amenable to regulation by sister states.” This “trajectory” is “inimical to Delaware’s interest in regulating the internal functioning of Delaware-chartered entities.” Moreover, Sciabacucchi’s “first principles” analysis, and its implied constraints on legislative action “veers Delaware’s judiciary into the Legislature’s lane, as well as into the federal lane.”
  All of these problems, Grundfest suggests, can be avoided by a “straightforward” interpretation and application of Delaware’s statutory law. A textualist reading of the statutes avoids “all of the concerns that inspire the invention of a divergent ‘internal affairs’ definition.” Sections 102(b)(1), 115, and 202 of the DGCL “unambiguously support the validity of Federal Forum Provisions and nothing in Sciabacucchi suggests Federal Forum Provisions are inconsistent with the plain text.” The statutory text also answers the concern about the possibility of charter provisions seeking to address, for example, tort or contract law. Sections 102 and 115 both refer to provisions relating to directors, officers, and shareholders “in their capacities as such,” which would take out the concern about charter provisions spilling into a host of other matters.
  Discussion
Grundfest’s paper is massive and detailed. It is always a challenge attempting to summarize anything as vast and sweeping as this paper and it is a particular challenge to do so within the constraints of the blogging format. I hope my summary here does justice to Grundfest’s extensive effort.
  While Grundfest’s arguments are numerous and extensive, several basic things stand out. The first is that he thinks that Vice-Chancellor Laster really got it wrong in Sciabacucchi. In Grundfest’s view, the decision disregards important federal and Delaware precedent and relies on assumptions of fact that are “demonstrably incorrect.”
  The other thing that is clear is that Grunfest continues to believe that federal forum provisions are a good idea and are permissible under Delaware statutory law. I should note here that in the interests of brevity, I telescoped Grundfest’s affirmative case that the text of the relevant Delaware statutes supports companies’ adoption of federal forum provisions. It is in the nature of his paper that his critique of Sciabacucchi predominates the presentation.
  There is no mystery about the timing of Professor Grundfest’s paper. As I noted at the outset, Sciabacucchi is on appeal to the Delaware Supreme Court, and the parties have just entered the briefing phase of the appeal. Having originated and propagated the idea of federal forum provisions, Grundfest clearly has an interest in seeing his intellection creation survive legal scrutiny. His paper clearly bespeaks the fervor of his commitment to his project. The paper is a legal missile aimed at the Delaware Supreme Court.
  It will of course be very interesting to see how the appeal turns out. The larger problem for everyone is that the possibility of state court securities litigation has created a huge mess, adding complexity, confusion, and cost for companies and for their D&O insurers. We can also certainly hope that the Delaware Supreme Court concludes that federal forum provisions are permissible.
  However, unless and until that happens, the problems arising from the possibility of state court securities litigation will continue, causing all of the problems and concerns that Grundfest’s paper notes. For that reason, I continue to believe that the best approach would be for Congress to act and address this situation. SLUSA was clearly intended to force all securities litigation into federal court. However, Congress made a hash of things when it modified the jurisdictional provisions of the ’33 Act, and that is how the U.S. Supreme Court wound up concluding in Cyan, notwithstanding SLUSA, that state courts retain concurrent jurisdiction for Section 11 claims. While federal forum provisions are a good idea, the best thing would be for Congress to go back and clean things up.
  One final note. Grundfest’s paper is massive and could even be daunting for some. Just in case readers of this blog don’t manage to make their way through the text to see it, the insurance practitioners who read this blog will be particularly interested in the statistical analysis in Section II of Grundfest’s paper. The paper not only sets out interesting statistical information about state court securities litigation filings and resolutions, but it also lays out interesting and detailed information about how Cyan has affected the D&O insurance market for IPO companies. I am sure that many readers will find it well worth their time to work their way through both the litigation statistics and the insurance pricing information.
  Special thanks to the several readers who sent me a link to Professor Grundfest’s paper.
    The post A Critique of the Delaware Chancery Court Decision on Federal Forum Provisions appeared first on The D&O Diary.
A Critique of the Delaware Chancery Court Decision on Federal Forum Provisions published first on
0 notes
lawfultruth · 6 years ago
Text
A Critique of the Delaware Chancery Court Decision on Federal Forum Provisions
After the U.S. Supreme Court’s March 2018 decision in the Cyan case that state courts retain concurrent jurisdiction for ’33 Act liability actions, one idea that circulated was that companies could avoid securities class action lawsuits in state court by adopting a charter provision designating a federal forum for these kinds of suits. Unfortunately, in December 2018, Delaware Chancery Court Vice Chancellor Travis Laster held in Sciabacucchi v. Salzburg that under Delaware law federal forum provisions are invalid and ineffective, as discussed here. The Sciabacucchi decision, which is now on appeal, is the subject of a comprehensive critique in a recent article by Stanford Law Professor Joseph Grundfest, entitled “The Limits of Delaware Corporate Law: Internal Affairs, Federal Forum Provisions, and Sciabacucchi” (here). Professor Grundfest argues that Sciabacucchi was wrongly decided and that a under a “straightforward” application of applicable Delaware statutory law, federal forum provisions are valid and permitted.
  It is important to note at the outset, as Professor Grundfest acknowledges in footnote one in his paper, that Grundfest himself developed the concept of the federal forum provision and drafted the federal forum provision language that was in dispute in the Sciabacucchi case. Indeed, in the parties’ pleadings in Sciabacucchi, the use of federal forum provisions was referred to as the “Grundfest solution,” and so Grundfest’s interest in these issues is, as he acknowledges in the footnote, “paternal.”
  Background on State Class Action Securities Litigation
Professor Grundfest opens the substantive portion of his paper with a review of the problems that state court securities actions create. First, as his paper statistically demonstrates, state court securities class action litigation, which actually began to accumulate even before Cyan, has grown significantly since the case was decided, to the point that now 76 percent of Section 11 cases are brought either in state court alone or in parallel state and federal actions.
  Plaintiffs, Professor Grundfest notes, have significant incentives to “migrate” their cases to state court, as state court pleading standards are more plaintiff-friendly; as state courts do not uniformly apply the discovery stay in federal court; and as there is no process in state court for consolidating duplicate proceedings.
  Plaintiffs’ attraction to state court arguably is statistically justified, as between 2011 and 2018, the dismissal rate for state court Section 11 actions was only 19 percent, while the dismissal rate in federal court was 45 percent. Increased likelihood of surviving dismissal and increased uncertainty has meant that state court securities suits at higher values than do comparable federal court actions. Among other things as a result of these considerations, the cost of D&O insurance for IPO companies has risen materially in the wake of Cyan, as Professor Grundfest’s paper details statistically. Readers of this blog will find the paper’s discussion of the D&O insurance issues particularly interesting.
  Background on Litigation Management Bylaws
The idea for companies to adopt bylaw provisions specifying a federal forum arose out of the larger discussion in recent years for companies to manage their litigation risks by adopting litigation management bylaws. In 2013, then-Chancellor Leo Strine Jr. held (as discussed here) in the Chevron case that corporations can adopt bylaws designating a preferred forum for litigation “relating to the internal affairs of the corporation.”  A 2014 Delaware Supreme Court decision in the ATP Tour case (discussed here) also upheld the validity of a bylaw provision shifting fees to an unsuccessful litigant in a shareholder claim. However, in 2015, the Delaware legislature enacted a provision barring fee-shifting bylaws, while codifying the right of Delaware corporations to designate Delaware as the preferred forum for shareholder disputes.
  The Sciabacucchi Case
With the idea circulating that companies should adopt federal forum provisions, a number of IPO companies adopted bylaws designating a federal forum “for the resolution of any complaint asserting a cause of action under the Securities Act of 1933.” Among the IPO companies adopting these kinds of provisions were Blue Apron, Stitch Fix and Roku. Matthew Sciabacucchi bought shares in all three companies. He then filed an action in Delaware Chancery Court seeking a judicial declaration that the companies’ federal forum provisions are invalid.
  In December 2018, Vice-Chancellor Laster granted Sciabacucchi’s motion for summary judgment, holding under Delaware law the provisions are invalid and unenforceable. In reaching this ruling, Vice-Chancellor Laster said that while Delaware law permits companies to adopt a forum selection clause for “internal affairs” claims, owing to what Laster describes as “first principles” Delaware law “does not authorize a Delaware corporation to regulate external relationships.” A ’33 Act liability action, Vice-Chancellor Laster said, “is external to the corporation,” as “Federal law creates the claim, defines the elements of the claim, and specifies who can be a plaintiff or a defendant.”
  While Delaware law has certain authority on internal matters related to the company’s organization, that authority “does not extend to its creation’s external relationships.” The state’s authority, Laster said, does not extend, for example, to tort claims asserted against the company.” A state’s corporate charter “cannot bind a plaintiff to a particular forum when the claim does not involve right or relationships that were established under Delaware law.” Since that is what the federal forum provisions do, they are therefore “ineffective and invalid.”
  Professor Grundfest’s Critique
Professor Grundfest’s paper presents a multi-part attack on Vice-Chancellor Laster’s ruling in Sciabacucchi. As an initial matter, Grundfest challenges Laster’s reliance on sweeping “first principles” to invalidate the federal forum provision. Under these “first principles,” Laster said, when “the claim exists outside the corporate contract, it is beyond the power of corporate law to regulate.” The implications of this suggestion, Grundfest says, “reach far beyond the four corners of Federal Forum Provisions and articulate a novel principle that would constrain all of the past and future Delaware corporate law.”
  The further problem with the “first principles” analysis is the suggestion that without these constraints, Delaware might interpret its own laws to allow regulation, say, of tort or contract claims. The “easy answer to these concerns is that none of them could arise in the context of federal forum provisions, and other forum provisions are not at issue. Delaware, Grundfest says, “can address those concerns if and when those provisions arise in a real case or controversy.”
  The Sciabacucchi decision, Grundfest contends, is “highly contestable.” Among other things, Grundfest argues that the decision is against controlling U.S. and Supreme Court precedent. Laster concluded that that the federal forum provision is “contrary to the federal regime,” while disregarding the U.S. Supreme Court’s 1989 decision in Rodriguez de Quijas v. Shearson/American Express, Inc., which, Grundfest asserts, the Court “conclusively establishes that plaintiffs have no immutable right to litigate Securities Claims in state court and enforces a contract of adhesion prohibiting state court litigation of Securities Act claims.” Yet, Grundfest notes, Sciabacucchi nowhere mention the Rodriguez claim. Moreover, Grundfest notes, by invalidating a federal practice governing a federal claim that is consistent with federal law, Sciabacucchi “imposes a restraint on federal practice that appears nowhere in federal law,” and “creates an unprecedented intrusion by Delaware law into the federal space.”
  A further “problem” with Sciabacucchi is that it assumes that Securities Act plaintiffs are never existing stockholders to whom fiduciary duties are owed – a proposition, Grundfest notes, for which the Sciabacucchi opinion offers no factual support. In fact, Professor Grundfest notes, numerous SEC filings show that existing holders purchase additional shares in both IPOs and follow-on offerings, and these purchasers are owed fiduciary duties in connection with the statements made in the registration statements.
  Sciabacucchi’s “internal affairs” analysis is also “problematic” as it “diverges from precedent” to “invent a materially narrow definition” of the term “internal affairs.” Both U.S. Supreme Court and Delaware’s definition of internal affairs are broader and more encompassing, yet Sciabacucchi “offers no rationale for its divergence from controlling precedent.”
  The decision’s application of its “divergent definition” of “internal affairs” is “additionally problematic” in its conclusion that Securities Act claims are “always external.” However, Delaware precedent establishes that an act can simultaneously be an internal violation of Delaware law or violate a federal law. Indeed, Grundfest argues, the “due diligence” defense to Section 11 claims necessarily entails a close inquiry into the actions and awareness of board members, all matters that are “entirely internal.”
  The court’s decision is also “problematic” from a policy perspective. If the board processes that caused the filing of a defective registration statement are external, then “a host of boardroom functions” previously considered internal become “amenable to regulation by sister states.” This “trajectory” is “inimical to Delaware’s interest in regulating the internal functioning of Delaware-chartered entities.” Moreover, Sciabacucchi’s “first principles” analysis, and its implied constraints on legislative action “veers Delaware’s judiciary into the Legislature’s lane, as well as into the federal lane.”
  All of these problems, Grundfest suggests, can be avoided by a “straightforward” interpretation and application of Delaware’s statutory law. A textualist reading of the statutes avoids “all of the concerns that inspire the invention of a divergent ‘internal affairs’ definition.” Sections 102(b)(1), 115, and 202 of the DGCL “unambiguously support the validity of Federal Forum Provisions and nothing in Sciabacucchi suggests Federal Forum Provisions are inconsistent with the plain text.” The statutory text also answers the concern about the possibility of charter provisions seeking to address, for example, tort or contract law. Sections 102 and 115 both refer to provisions relating to directors, officers, and shareholders “in their capacities as such,” which would take out the concern about charter provisions spilling into a host of other matters.
  Discussion
Grundfest’s paper is massive and detailed. It is always a challenge attempting to summarize anything as vast and sweeping as this paper and it is a particular challenge to do so within the constraints of the blogging format. I hope my summary here does justice to Grundfest’s extensive effort.
  While Grundfest’s arguments are numerous and extensive, several basic things stand out. The first is that he thinks that Vice-Chancellor Laster really got it wrong in Sciabacucchi. In Grundfest’s view, the decision disregards important federal and Delaware precedent and relies on assumptions of fact that are “demonstrably incorrect.”
  The other thing that is clear is that Grunfest continues to believe that federal forum provisions are a good idea and are permissible under Delaware statutory law. I should note here that in the interests of brevity, I telescoped Grundfest’s affirmative case that the text of the relevant Delaware statutes supports companies’ adoption of federal forum provisions. It is in the nature of his paper that his critique of Sciabacucchi predominates the presentation.
  There is no mystery about the timing of Professor Grundfest’s paper. As I noted at the outset, Sciabacucchi is on appeal to the Delaware Supreme Court, and the parties have just entered the briefing phase of the appeal. Having originated and propagated the idea of federal forum provisions, Grundfest clearly has an interest in seeing his intellection creation survive legal scrutiny. His paper clearly bespeaks the fervor of his commitment to his project. The paper is a legal missile aimed at the Delaware Supreme Court.
  It will of course be very interesting to see how the appeal turns out. The larger problem for everyone is that the possibility of state court securities litigation has created a huge mess, adding complexity, confusion, and cost for companies and for their D&O insurers. We can also certainly hope that the Delaware Supreme Court concludes that federal forum provisions are permissible.
  However, unless and until that happens, the problems arising from the possibility of state court securities litigation will continue, causing all of the problems and concerns that Grundfest’s paper notes. For that reason, I continue to believe that the best approach would be for Congress to act and address this situation. SLUSA was clearly intended to force all securities litigation into federal court. However, Congress made a hash of things when it modified the jurisdictional provisions of the ’33 Act, and that is how the U.S. Supreme Court wound up concluding in Cyan, notwithstanding SLUSA, that state courts retain concurrent jurisdiction for Section 11 claims. While federal forum provisions are a good idea, the best thing would be for Congress to go back and clean things up.
  One final note. Grundfest’s paper is massive and could even be daunting for some. Just in case readers of this blog don’t manage to make their way through the text to see it, the insurance practitioners who read this blog will be particularly interested in the statistical analysis in Section II of Grundfest’s paper. The paper not only sets out interesting statistical information about state court securities litigation filings and resolutions, but it also lays out interesting and detailed information about how Cyan has affected the D&O insurance market for IPO companies. I am sure that many readers will find it well worth their time to work their way through both the litigation statistics and the insurance pricing information.
  Special thanks to the several readers who sent me a link to Professor Grundfest’s paper.
    The post A Critique of the Delaware Chancery Court Decision on Federal Forum Provisions appeared first on The D&O Diary.
A Critique of the Delaware Chancery Court Decision on Federal Forum Provisions syndicated from https://ronenkurzfeldweb.wordpress.com/
0 notes
premayogan · 7 years ago
Text
The 10 Most Common Mistakes iOS Developers Don't Know They're Making
What’s the only thing worse than having a buggy app rejected by the App Store? Having it accepted. Once the one-star reviews start rolling in, it’s almost impossible to recover. This costs companies money and developers their jobs. iOS is now the second-largest mobile operating system in the world. It also has a very high adoption rate, with more than 85% of users on the latest version. As you might expect, highly engaged users have high expectations—if your app or update isn’t flawless, you’ll hear about it. With the demand for iOS developers continuing to skyrocket, many engineers have switched to mobile development (more than 1,000 new apps are submitted to Apple every day). But true iOS expertise extends far beyond basic coding. Below are 10 common mistakes that iOS developers fall prey to, and how you can avoid them.
Tumblr media
85% of iOS users use the latest OS version. That means they expect your app or update to be flawless.
Common Mistake #1: Not Understanding Asynchronous Processes
A very common type of mistake among new programmers is handling asynchronous code improperly. Let’s consider a typical scenario: User opens a screen with the table view, some data is fetched from the server and displayed in a table view. We can write it more formally: @property (nonatomic, strong) NSArray *dataFromServer; - (void)viewDidLoad { __weak __typeof(self) weakSelf = self; latestDataWithCompletionBlock:^(NSArray *newData, NSError *error){ weakSelf.dataFromServer = newData; // 1 }]; ; // 2 } // and other data source delegate methods - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.dataFromServer.count; } At first glance, everything looks right: We fetch data from the server and then update the UI. However, the problem is fetching data is an asynchronous process, and won’t return new data immediately, which means reloadData will be called before receiving the new data. To fix this mistake, we should move line #2 right after line #1 inside the block. @property (nonatomic, strong) NSArray *dataFromServer; - (void)viewDidLoad { __weak __typeof(self) weakSelf = self; latestDataWithCompletionBlock:^(NSArray *newData, NSError *error){ weakSelf.dataFromServer = newData; // 1 ; // 2 }]; } // and other data source delegate methods - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.dataFromServer.count; } However, there may be situations where this code still does not behave as expected, which brings us to …
Common Mistake #2: Running UI-Related Code on a Thread Other than the Main Queue
Let’s imagine we used corrected code example from the previous common mistake, but our table view is still not updated with the new data even after the asynchronous process has successfully completed. What might be wrong with such simple code? To understand it, we can set a breakpoint inside the block and find out on which queue this block is called. There is a high chance the described behavior is happening because our call is not in the main queue, where all UI-related code should be performed. Most popular libraries—such as Alamofire, AFNetworking, and Haneke—are designed to call completionBlockon the main queue after performing an asynchronous task. However, you can’t always rely on this and it is easy to forget to dispatch your code to the right queue. To make sure all your UI-related code is on the main queue, don’t forget to dispatch it to that queue: dispatch_async(dispatch_get_main_queue(), ^{ ; });
Common Mistake #3: Misunderstanding Concurrency & Multithreading
Concurrency could be compared to a really sharp knife: You can easily cut yourself if you’re not careful or experienced enough, but it’s extremely useful and efficient once you know how to use it properly and safely. You can try to avoid using concurrency, but no matter what kind of apps you’re building, there is really high chance you can’t do without it. Concurrency can have significant benefits for your application. Notably: Almost every application has calls to web services (for example, to perform some heavy calculations or read data from a database). If these tasks are performed on the main queue, the application will freeze for some time, making it non-responsive. Moreover, if this takes too long, iOS will shut down the app completely. Moving these tasks to another queue allows the user to continue use the application while the operation is being performed without the app appearing to freeze. Modern iOS devices have more than one core, so why should the user wait for tasks to finish sequentially when they can be performed in parallel? But the advantages of concurrency don’t come without complexity and the potential for introducing gnarly bugs, such as race conditions that are really hard to reproduce. Let’s consider some real-world examples (note that some code is omitted for simplicity). Case 1 final class SpinLock { private var lock = OS_SPINLOCK_INIT func withLock(@noescape body: () -> Return) -> Return { OSSpinLockLock(&lock) defer { OSSpinLockUnlock(&lock) } return body() } } class ThreadSafeVar { private let lock: ReadWriteLock private var _value: Value var value: Value { get { return lock.withReadLock { return _value } } set { lock.withWriteLock { _value = newValue } } } } The multithreaded code: let counter = ThreadSafeVar(value: 0) // this code might be called from several threads counter.value += 1 if (counter.value == someValue) { // do something } At first glance, everything is synced and appears as if it should work as expected, since ThreadSaveVar wraps counter and makes it thread safe. Unfortunately, this is not true, as two threads might reach the increment line simultaneously and counter.value == someValue will never become true as a result. As a workaround, we can make ThreadSafeCounter which returns its value after incrementing: class ThreadSafeCounter { private var value: Int32 = 0 func increment() -> Int { return Int(OSAtomicIncrement32(&value)) } } Case 2 struct SynchronizedDataArray { private let synchronizationQueue = dispatch_queue_create("queue_name", nil) private var _data = () var data: { var dataInternal = () dispatch_sync(self.synchronizationQueue) { dataInternal = self._data } return dataInternal } mutating func append(item: DataType) { appendItems() } mutating func appendItems(items: ) { dispatch_barrier_sync(synchronizationQueue) { self._data += items } } } In this case, dispatch_barrier_sync was used to sync access to the array. This is a favorite pattern to ensure access synchronization. Unfortunately, this code doesn’t take into account that struct makes a copy each time we append an item to it, thus having a new synchronization queue each time. Here, even if it looks correct at first sight, it might not work as expected. It also requires a lot of work to test and debug it, but in the end, you can improve your app speed and responsiveness.
Common Mistake #4: Not Knowing Pitfalls of Mutable Objects
Swift is very helpful in avoiding mistakes with value types, but there are still a lot of developers who use Objective-C. Mutable objects are very dangerous and can lead to hidden problems. It is a well-known rule that immutable objects should be returned from functions, but most developers don’t know why. Let’s consider the following code: // Box.h @interface Box: NSObject @property (nonatomic, readonly, strong) NSArray *boxes; @end // Box.m @interface Box() @property (nonatomic, strong) NSMutableArray *m_boxes; - (void)addBox:(Box *)box; @end @implementation Box - (instancetype)init { self = ; if (self) { _m_boxes = ; } return self; } - (void)addBox:(Box *)box { ; } - (NSArray *)boxes { return self.m_boxes; } @end The code above is correct, because NSMutableArray is a subclass of NSArray. So what can go wrong with this code? The first and the most obvious thing is that another developer might come along and do the following: NSArray *childBoxes = ; if (]) { // add more boxes to childBoxes } This code will mess up your class. But in that case, it’s a code smell, and it’s left up to that developer to pick up the pieces. Here is the case, though, that is much worse and demonstrates an unexpected behavior: Box *box = init]; NSArray *childBoxes = ; init]]; NSArray *newChildBoxes = ; The expectation here is that  > , but what if it is not? Then the class is not well designed because it mutates a value that was already returned. If you believe that inequality should not be true, try experimenting with UIView and . Luckily, we can easily fix our code, by rewriting the getter from the first example: - (NSArray *)boxes { return ; }
Common Mistake #5: Not Understanding How iOS NSDictionary Works Internally
If you ever worked with a custom class and NSDictionary, you might realize you cannot use your class if it doesn’t conform to NSCopying as a dictionary key. Most developers have never asked themselves why Apple added that restriction. Why does Apple copy the key and use that copy instead of the original object? The key to understanding this is figuring out how NSDictionary works internally. Technically, it’s just a hash table. Let’s quickly recap how it works on a high level while adding an Object for a Key (table resizing and performance optimization is omitted here for simplicity): Step 1: It calculates hash(Key). Step 2: Based on the hash, it looks for a place to put the object. Usually, this is done by taking the modulus of the hash value with the dictionary length. The resulting index is then used to store the Key/Value pair. Step 3: If there is no object in that location, it creates a linked list and stores our Record (Object and Key). Otherwise, it appends Record to the end of the list. Now, let’s describe how a record is fetched from the dictionary: Step 1: It calculates hash(Key). Step 2: It searches a Key by hash. If there is no data, nil is returned. Step 3: If there is a linked list, it iterates through the Object until . With this understanding of what is occurring under the hood, two conclusions can be drawn: If the Key’s hash changes, Record should be moved to another linked list. Keys should be unique. Let’s examine this on a simple class: @interface Person @property NSMutableString *name; @end @implementation Person - (BOOL)isEqual:(id)object { if (self == object) { return YES; } if (!]) { return NO; } return ; } - (NSUInteger)hash { return ; } @end Now imagine NSDictionary doesn’t copy Keys: NSMutableDictionary *gotCharactersRating = init]; Person *p = init]; p.name = @"Job Snow"; gotCharactersRating = @10; Oh! We have a typo there! Let’s fix it! p.name = @"Jon Snow"; What should happen with our dictionary? As the name was mutated, we now have a different hash. Now our Object lies in the wrong place (it still has the old hash value, as the Dictionary doesn’t know about the data change), and it’s not really clear what hash we should use to lookup data in the dictionary. There could be an even worse case. Imagine if we already had “Jon Snow” in our dictionary with a rating of 5. The dictionary would end up with two different values for the same Key. As you can see, there are many problems that can arise from having mutable keys in NSDictionary. The best practice to avoid such issues is to copy the object before storing it, and to mark properties as copy. This practice will also help you to keep your class consistent.
Common Mistake #6: Using Storyboards Instead of XIBs
Most new iOS developers follow Apple’s suggestion and use Storyboards by default for the UI. However, there are a lot of drawbacks and only a few (debatable) advantages in using Storyboards. Storyboard drawbacks include: It’s really hard to modify a Storyboard for several team members. Technically, you can use many Storyboards, but the only advantage, in that case, is making it possible to have segues between controllers on the Storyboard. Controllers and segues names from Storyboards are Strings, so you have to either re-enter all those Strings throughout your code (and one day you will break it), or maintain a huge list of Storyboard constants. You could use SBConstants, but renaming on the Storyboard is still not an easy task. Storyboards force you into a non-modular design. While working with a Storyboard, there is very little incentive to make your views reusable. This may be acceptable for the minimum viable product (MVP) or quick UI prototyping, but in real applications you might need to use the same view several times across your app. Storyboard (debatable) advantages: The whole app navigation can be seen at a glance. However, real applications can have more than ten controllers, connected in different directions. Storyboards with such connections look like a ball of yarn and don’t give any high-level understanding of data flows. Static tables. This is the only real advantage I can think of. The problem is that 90 percent of static tables tends to turn into dynamic tables during app evolution and a dynamic table can be more easily handled by XIBs.
Common Mistake #7: Confusing Object & Pointer Comparison
While comparing two objects, we can consider two equality: pointer and object equality. Pointer equality is a situation when both pointers point to the same object. In Objective-C, we use ==operator for comparing two pointers. Object equality is a situation when two objects represent two logically identical objects, like the same user from a database. In Objective-C, we use isEqual, or even better, type specific isEqualToString, isEqualToDate, etc. operators for comparing two objects. Consider the following code: NSString *a = @"a"; // 1 NSString *b = @"a"; // 2 if (a == b) { // 3 NSLog(@"%@ is equal to %@", a, b); } else { NSLog(@"%@ is NOT equal to %@", a, b); } What will be printed out to the console when we run that code? We will get a is equal to b, as both objects a and b are pointing to the same object in memory. But now let’s change line #2 to: NSString *b = copy]; Now we get a is NOT equal to b since these pointers are now pointing to different objects even though those objects have the same values. This problem can be avoided by relying on isEqual, or type specific functions. In our code example, we should replace line #3 with following code for it to always work properly: if () {
Common Mistake #8: Using Hardcoded Values
There are two primary problems with hardcoded values: It’s often not clear what they represent. They need to be re-entered (or copied and pasted) when they need to be used in multiple places in the code. Consider the following example: if ( timeIntervalSinceDate:self.lastAppLaunch] // do something } or ; ... ; What does 172800 represent? Why is it being used? It is probably not obvious that this corresponds to the number of seconds in 2 days (there are 24 x 60 x 60, or 86,400, seconds in a day). Rather than using hardcoded values, you could define a value using the #define statement. For example: #define SECONDS_PER_DAY 86400 #define SIMPLE_CELL_IDENTIFIER @"SimpleCell" #define is a preprocessor macro that replaces the named definition with its value in the code. So, if you have #define in a header file and import it somewhere, all occurrences of the defined value in that file will be replaced too. This works well, except for one issue. To illustrate the remaining problem, consider the following code: #define X = 3 ... CGFloat y = X / 2; What would you expect the value of y to be after this code executes? If you said 1.5, you are incorrect. y will be equal to 1 (not 1.5) after this code executes. Why? The answer is that #define has no information about the type. So, in our case, we have a division of two Int values (3 and 2), which results in an Int (i.e., 1) which is then cast to a Float. This can be avoided by using constants instead which are, by definition, typed: static const CGFloat X = 3; ... CGFloat y = X / 2; // y will now equal 1.5, as expected
Common Mistake #9: Using Default Keyword in a Switch Statement
Using the default keyword in a switch statement can lead to bugs and unexpected behavior. Consider the following code in Objective-C: typedef NS_ENUM(NSUInteger, UserType) { UserTypeAdmin, UserTypeRegular }; - (BOOL)canEditUserWithType:(UserType)userType { switch (userType) { case UserTypeAdmin: return YES; default: return NO; } } The same code written in Swift: enum UserType { case Admin, Regular } func canEditUserWithType(type: UserType) -> Bool { switch(type) { case .Admin: return true default: return false } } This code works as intended, allowing only Admin users to be able to change other records. However, what might happen we add another user type Manager that should be able to edit records as well? If we forget to update this switch statement, the code will compile, but it will not work as expected. However, if the developer used enum values instead of the default keyword from the very beginning, the oversight will be identified at compile time, and could be fixed before going to test or production. Here is the good way to handle this in Objective-C: typedef NS_ENUM(NSUInteger, UserType) { UserTypeAdmin, UserTypeRegular, UserTypeManager }; - (BOOL)canEditUserWithType:(UserType)userType { switch (userType) { case UserTypeAdmin: case UserTypeManager: return YES; case UserTypeRegular: return NO; } } The same code written in Swift: enum UserType { case Admin, Regular, Manager } func canEditUserWithType(type: UserType) -> Bool { switch(type) { case .Manager: fallthrough case .Admin: return true case .Regular: return false } }
Common Mistake #10: Using NSLog for Logging
Many iOS developers use NSLog in their apps for logging, but most of the time this is a terrible mistake. If we check the Apple documentation for the NSLog function description, we will see it is very simple: void NSLog(NSString *format, ...); What could possibly go wrong with it? In fact, nothing. However, if you connect your device to the XCode Organizer, you’ll see all your debug messages there. For this reason alone, you should never use NSLog for logging: it’s easy to show some unwanted internal data, plus it looks unprofessional. Better approach is to replace NSLogs with configurable CocoaLumberjack or some other logging framework.
Wrap Up
iOS is a very powerful and rapidly evolving platform. Apple makes a massive ongoing effort to introduce new hardware and features for iOS itself, while also continually expanding the Swift language. Improving your Objective-C and Swift skills will make you a great iOS developer and offer opportunities to work on challenging projects using cutting-edge technologies. Source: https://www.toptal.com/ios/top-ios-development-mistakes Read the full article
0 notes
vishers · 7 years ago
Text
Getting Clojure by Olsen (2018): A Pre-Read
★★★★★
Let's get this out of the way up front: Getting Clojure by Russ Olsen is my new favorite 'Intro to Clojure' book and I'll be recommending it exclusively to newcomers until something better comes along. I have rarely seen a book that's as clearly organized, engagingly written, and comprehensive in its coverage. I say this primarily regarding the 'Intro to Clojure' side of the book. The subtitle suggests that it is also a text that is ideal for learning Functional Programming, and it certainly serves that purpose, but only in that it teaches Clojure and Clojure is such an amazing Functional Language.
If you are looking to use Clojure to see more of the joys of LISP I wouldn't start here. Instead, I'd go for The Joy of Clojure by Fogus and Houser instead. That book does a better job of covering Clojure as a LISP (while also doing an exemplary job of covering it as a Functional Language).
But if you want to cover what makes Clojure Clojure, from the far-reaching sequence abstraction, to the immutable data structures, to the invisible and idiomatic Java interop, and the native access to LISP idioms and techniques, all while wasting no time on fluff and reading prose that's actually surprisingly enjoyable, this is the book for you.
Title, Subtitle, and Preface ★★★★☆
Getting Clojure: Build Your Functional Skills One Idea at a Time
The Preface is excellent. It is unspeakably refreshing to read a book that tells you, in summary, everything that it's about to tell you. The one ding here is that it isn't tied directly to chapters. At least the ordering is right.
Table of Contents ★★★★☆
3 Parts:
A Language Tour
Core Abstractions and Testing
Special Topics
While we do get sectional titles they are written in the fashion of today so they are not super informative. At least they're there and I certainly have seen far worse. Once you've read the chapter also, you'd be able to use the Table of Contents to easily find the section you're looking to refer to later on because some of the meaning would've been filled in for you.
Each chapter follows a basic pattern.
Cover the subject
See some real world usage
Identify some common anti-patterns
Point 2 is something I've rarely seen in a technical book, actually reaching out to commonly used libraries to identify actual usage of the subject matter of the chapter. I wish more books did this.
At the end of Part 1, you should be able to express most essential algorithms in Clojure and understand how to navigate a Clojure system, having seen all of the basic Clojure constructs like conditionals, vars, data literals, functional style, namespaces, etc.
By the end of Part 2, you should understand more about why Clojure code reads the way it does, why sequences of one sort or another are used relentlessly in idiomatic Clojure, what laziness is and why it's so useful, and how to exercise your code both explicitly and via property-based statements.
At the end of Part 3, you'll have seen most of the rest of what makes Clojure special. Java interop, state management (in true SICP fashion, mutable state is relegated to the back end of the book in the 'Advanced' section), easy concurrency, and the mighty LISP REPL and Macros.
Are there parts of Clojure not covered here? Sure. Is there anything that makes Clojure distinct or that you'll have trouble understanding once you digest this stuff? Nope. And it's only 250 pages.
The Index ★★★★☆
functions
tests
values
symbols
maps
sequences
collections
lazy sequences
threads
Symbols section
data
arguments
records
performance
arity
exceptions
immutability
keys
Java
keywords
lists
logic
macros
namespaces
multimethods
names
require
state
strings
vectors
I love that there's a section on Symbols here. It's reminiscent of the 'Hard to Google For' clojure.org guide.
Pivotal Chapters
If you've never seen Clojure before than Chapter 1 is the introduction you've been looking for.
Chapters 2 and 3 are introductions to the essential data literals that you'll find an almost all idiomatic Clojure code.
Chapter 6 covers Functional Programming and how it's accomplished in Clojure.
Chapter 9 covers how Clojure systems are organized in Namespaces and how you can navigate around them.
Chapters 10 and 11 cover the sequence abstraction.
Chapter 16 covers Java Interop.
Chapters 19 and 20 cover LISP topics from Clojure's perspective.
Once you've looked at those chapters you should have a good sense of whether Clojure is something you think is interesting or not. I hope you find it to be.
0 notes
jatothrim · 8 years ago
Text
Going nukes with concurrency.
I always wondered how read-copy-update, shortly RCU, programming technique worked in practice. Well not any more. KiloEngine has had very intresting concurrecy API feature for quite long time. The idea is good and very useful, but implementation was a nightmare. Keyword and/or problem was scalability. You can’t use std::mutexes. It’s the devil impersonating as unscalable code. The API is designed so that you can schedule millions of small tasks that are executed then asynchronously and concurrently in thread-pool. Unfortunately doing lots of small tasks multiplies the overhead times number of worker-threads manyfold. I had few times no scaling at all, and all workers just sat in std::mutex::lock() most of the time. The cure for this witchcrafted curse is RCU + CAS. Or better explained duplicating immutable shared data-structure, updating the local copy of it and then publishing the local copy globally using std::atomic and CAS-loop. The old data structure is not touched nor modified, but it is replaced as whole. Pseudo code of updating std::string data:
std::atomic<std::string*> data; const std::string * old = data.load(); std::string * newstr = new std::string(old->begin(), old->end()); updatestringpostfix(newstr); while(!data.compare_exchange_weak(old, newstr)) {     newstr->assing(old->begin(), old->end());     updatestringpostfix(newstr); }
All this without ever taking a mutex. If you followed you might wonder what happens to the old data? The outdated data is not deleted immediately, because other threads may be still accessing it. Because we used no mutexes we didn’t exclude access to the old data structure. We actually intentionally allow thread to access the outdated data. The other threads have no idea yet that data was modified and continue read the old string object. They’ll get the updated data when they really want to reload the pointer from the global data. The above pseudo code scales almost linearly to amount of cpu cores available. But heyy.. doesn’t that code leak memory? Yes. It does leak memory. If that was written in garbace collected language it would work as is, because the garbace collector would eventually detect no one is using the abandoned string objects. But in C++ we must free the memory or our string updater will eat the whole universe of free memory.
We’ll need machinery that detects when the old string data is possible to be deleted safely. This is done with “Quiescent State-Based Reclamation” or shortly QSBR. Basically it stores the old std::string objects from above code after the CAS-loop in a list. This is called logical deletion. This logical reclaimation list manipulation must be thread-safe.
Threads whill then need to check if they have declared “Quiescent State“ in onQuiescentState(). If not, they’ll set the quescent state and check if it they were the last thread enabling it. If thread was the last one it enters the magic code section where magic happens. Other threads are forbidden to enter this magic code before the Quiescent State is zeroed.
Or at least when you call onQuiescentState() at correct place. onQuiescentState() can only be called when it is impossible for the thread to reference anything that it put into that logical reclaimation list. E.g. when thread is not holding any mutexes or locks? If all good the thread in onQuiescentState() swaps the logical reclaimation list with null and swaps the physical reclaimation list with the logical one. Now the thread proceeds to brutally kill anything that was on the previous physical reclaimation list having no consequences or sigsegvs. It then zeroes the global quiescent state and the killing cycle repeats. :D
0 notes
mbaljeetsingh · 8 years ago
Text
Why Elm? (And How To Get Started With It)
If any discussion of the biggest problems in web development, there is no doubt complexity comes up. Between the use of dozens of tools, dependencies, and complexities inherent in the languages themselves, complexity is part of the job.
Modern web applications require new ways to think about how we handle processes. The problem of executing functions without a strict order or in unexpected moments — like the click of a button or an incoming network message — forces us to use different techniques, from callbacks and promises to more sophisticated tools like Reactive Extensions.
It is not surprising to have systems composed of several thousands of lines of code, and things can easily get out of control at that scale. Even the slightest of changes could have unintended consequences.
Runtime errors are extremely common with JavaScript, and if we are not careful we can find ourselves trying to make impossible computations, like calling something that doesn’t exist or trying to process something that no longer is what you thought.
(Some of) The Advantages of Functional Programming
Controlled State
In a language like JavaScript, we can do almost whatever we want with the state of our programs. The lack of control with state is a common precursor to bugs. For example, trying to work with a value that has changed in unexpected ways.
Although state can't disappear, it can be controlled; Functional languages seek to provide tools to work with it in more organized ways. Some of them, like Clojure, provide features like immutable data structures, but others go to the extreme and become pure functional languages, like Haskell, where every single detail about state has to be carefully thought.
Predictability
Pure functions are a core concept of functional programming, and they are incredibly useful. We say that a function is pure when it always returns the same result given the same input and it doesn’t cause side-effects.
Because a function can't do anything more than taking a value, processing that value, and returning the result — we can get more predictable programs.
Write What, Not How
Functional languages are declarative languages, it means that we can describe a process without having to worry about all the details of how the process is done. The consequences of having a clear view of the purpose of our code can be very positive because you can understand more easily what the program does without the implementation noise of how it is done.
Modularity and Composability
The principle of "Divide and conquer" is a common practice in functional programming. We split complex problems into several straightforward ones, creating a solution for each one and then combine them to solve the entire problem; By dividing our programs into small functions, we can increase reusability and maintainability.
Discipline
Pure functional languages motivate programmers to think better about the programs they are building. From simple type annotations and mechanisms to control side-effects to complete architectures, like in Elm.
Although the initial development time can increase with such restrictions, the advantages in maintainability can compensate the effort.
Elm: A Functional Programming Language for the web
Elm is a relatively new programming language to build web applications created by Evan Czaplicki in 2012 as part of his thesis about Concurrent FRP for Functional GUIs.
Because it's targeted to the web—and browsers only understand a limited set of languages—the code that you write in Elm is compiled to HTML, CSS, and JS.
Immutable by design
All values on Elm are immutable, which means that once you have something, it will stay the same unless you create a new something as a copy.
The simplest advantage—because we don’t have to keep mutations in our head—reading code becomes a lot easier; when we see a value we can be sure it will stay the same. Also, you don't have to worry about runtime errors related to unexpected values because of mutation.
Static Types
Static types are an excellent way to document systems. You can know quickly what a function does and its domain just by looking at the type definition. Type systems allow us to define exactly the kind of value that a function takes and returns.
But types are not only useful when they are read by developers, they also allow for better tools (like debuggers and testers) that increase the soundness of our code. Also, they prevent us from doing impossible computations, and by consequence, keeping us away from a lot of potential runtime errors.
Elm has an inferred type system. Which means that you don’t have to write types from the beginning and the compiler will try to infer the appropriate type for your functions, so you don’t get any productivity penalties like in other mainstream languages with types.
-- Function with its type annotation square : Int -> Int square n = n^2 -- This also works, because types are inferred square n = n^2
Pure functions
Pure functions are the core concept of functional programming and produce a huge advantage building reliable and easy-to-maintain systems. Elm functions are pure and they receive inputs and produce new values as output, also, they always return the same result for each input without producing side-effects.
Subscriptions
Asynchronous systems require a different approach to programming and Elm handles this by using Subscriptions. Because there are certain things that we don’t know when they are going to happen — like user interactions or network responses — we can subscribe to those events allowing us to act as soon as they occur without having to worry about implementation details.
Controlled side-effects
Pure functions are good, and we can try to have pure functions everywhere, but at one point or another, we have to handle interactions of our program with the external world, and we can do this in a controlled way using Commands.
Because input and output are also side-effects, if we use strictly pure functions everywhere, we won’t be able to do anything at all. Instead, we identify side-effects, and we make them explicit so that Elm can handle them in the right way for us.
Compatible with Your Existing Project
You don't have to build or port a complete project to Elm — though that would be nice — you can include certain components made with Elm in an existing project.
Also, is possible to use existing Javascript inside your Elm applications, while keeping all the nice things and guarantees of the language.
Easy to Test
What do we get with static types? Awesome tools, including random test generators, where functions can be tested against random inputs depending on the domain of the function (defined by the types).
But probably one of the most exciting Elm features in this area is the fact that we can export the complete state of a program, and with it, we can do things like:
Send it to a library developer to reproduce a bug.
Load it in another browser or device to see how things behave.
And all this is done in a secure way, including network calls, thanks to the controlled side-effects using Commands.
A Better Architecture from the Beginning
When people started to build projects with Elm, they noticed that a pattern was emerging every time. That was the beginning of the Elm Architecture, the de facto way to build Elm applications.
Having a solid architecture to build our projects will assure us that we will have things under control even if our program increases in complexity. Also, we have the advantage that every time we take a new existing project, we won’t have a big problem understanding how the code is organized.
A sane package manager
Have you ever updated a JavaScript package and after starting your application you notice that something is not working as expected or is not working at all? Well, that’s an inexistent problem in Elm; the package manager automatically handles version numbers depending on the changes made, so you will never get breaking changes in a minor version anymore.
Beginner-friendly Compiler
We all know that compilers usually produce unreadable messages, but that is not the case with Elm. Every time you make a mistake, it will point out where the problem is, and an explanation of how to fix it.
Elm Compiler message
You can see more examples in the official Elm blog:
Compilers as assistants
Compiler error for humans
Setting Up our Development Environment
Installing the Elm Platform
Installing Elm is a quick process. After installing NodeJS, you can install Elm with NPM directly as other NodeJS packages:
npm install -g elm
Optionally, you can also install Elm using the installers for Mac or Windows. The links are available on the Install section in the An Introduction to Elm website.
Getting a Text Editor
Although Elm is a relatively new language, great tools to work with it already exist, especially for Atom using the Elmjutsu package.
But Atom is not the only one, the following editors are also supported:
Brackets
Emacs
IntelliJ
Light Table
Sublime Text
Vim
VS Code
You can pick the one you like the most. The installation process for those editors is outside of the scope of this article; I would recommend to check out their respective website.
Introduction to the Elm Platform
The Elm Platform: four tools that will be essential for the development of our Elm projects. A REPL to test small fragments of code. Reactor, a server that will allow us to see immediately our projects in the browser. Make, a tool to build our projects and the package manager that will provide us access to modules written by other people. Let’s take a look at these tools to see what we can do with them.
The Read–Eval–Print Loop
The Elm REPL is a tool to evaluate simple Elm code within a command line without having to create a file. As the name indicates, it first reads the input, then evaluates it and finally prints the result. This tool can be very useful to explore the language or to quickly execute a small piece of code.
To start using the REPL just open a terminal and execute the following command:
elm-repl
You should get something similar to this:
---- elm-repl 0.18.0 ----------------------------------------------------------- :help for help, :exit to exit, more at <http://ift.tt/2krAWDt> -------------------------------------------------------------------------------- >
We can write Elm code next to the > symbol. As a simple test, let’s try to build a square function to get the result of multiplying a number by itself. We can do this by writing the following and pressing Enter.
square n = n * n
Now we have a square function available in the current environment that we can use in future evaluations, for example, try typing:
square 5
And it should return 25 : number. The first part is our result and the rest is the type of the result which is a number.
You can also write more complex code. Let’s write a simple factorial function:
factorial number = \ | if number = 0 then 1 \ | else number * factorial(number-1)
To write multiple lines you have to add a \ at the end of each one to tell the interpreter that you want to write more.
After typing the first line and pressing enter, a | character will appear, then you can write the next line of your code. Be careful with the indentation, it will return an error if you don’t add it; you have to add at least one space.
There are four commands that you can use directly when the REPL is active:
:help Will show all the available commands.
:flags You can modify options for the Elm compiler.
:reset Restarts your current session without having to close and open the REPL again.
:exit Closes the REPL without having to close the command line window.
Elm Reactor
Elm-reactor is an interactive development tool that makes it easier to develop Elm programs. It will create a server that will compile your elm code on the fly, and you will be able to see the result directly on the browser.
Let’s see how we would use Reactor with a sample project. For this, you can clone the Elm Architecture Tutorial with Git and once you are in the project directory, execute the following command:
elm-reactor
A server will be created, and you will be able to access to it at http://localhost:8000 in your web browser.
You will see a navigation page that will contain the files in the directory of the project. Go to examples/01-button.elm and wait a moment while the file is compiled. Once if finished, you will be able to see a little widget to increase and reduce a number with two buttons.
That's how we can see our project without producing the final files, very useful for the development process.
Two useful flags can be used with the elm-reactor command, to see the complete list you can run elm-reactor --help.
-a Sets a custom address for the server.
-p Sets a different port for the server (:8000 by default).
For example:
elm-reactor -a 0.0.0.0 -p 3000
Although Reactor is a very useful tool for the development of Elm applications, eventually you will get to the point where you will want to put your project in production, there is a tool for this job included in the Elm Platform: Make.
Elm Make
Once your project is ready for the world, you will have to translate the Elm code to something web browsers understand, HTML, CSS and JavaScript. We use a tool called elm-make for this task, it will take Elm files and will produce native files for the web.
For example, let’s try to compile the example we used in the previous section. Go to the examples directory in the Elm Architecture Tutorial project and execute the following command:
elm-make 01-button.elm --output=01-button.html
When you execute this command, it will ask you to approve the installation of some packages, write Y and hit Enter, now let’s wait until the compilation is completed.
This will build our 01-button.elm file into a 01-button.html that can be open directly in the browser. If you go to the directory where 01-button.elm file is located, you will also find the new HTML file. You can open that file with your browser, and you will see the same result as in the previous section, but this time, we can see it without having to use any Elm tool; it’s plain HTML and Javascript.
Now we can distribute that file in the way we want, and any web browser will be able to open it.
The Elm Package Manager
When you start building non-trivial applications, you will soon find that writing everything by yourself is impractical. Usually, for the most common tasks, you will find packages already written by other people that you can use in your projects. For this, we use the Elm package manager, a tool to install and publish Elm packages.
As we saw in the previous section when we tried to compile our Elm file, the compiler asks us if we wanted to install the missing packages, that’s the job of the package manager in practice.
This tool is available as elm-package in your command line, and to install a package you can execute the following:
elm-package install <package-name>
Other commands include:
publish: Adds the package to the central catalog.
bump: Updates de version number of the package depending on changes.
diff: A utility to view the differences between package versions.
Getting a Taste of Elm
Create a new folder somewhere on your computer and open it with your IDE or text editor. We will create a first-application.elm file, where we are going to include the following code:
import Html exposing (Html, button, div, text) import Html.App as App import Html.Events exposing (onClick) main = App.beginnerProgram { model = model, view = view, update = update } -- MODEL type alias Model = Int model : Model model = 0 -- UPDATE type Msg = Increment | Decrement update : Msg -> Model -> Model update msg model = case msg of Increment -> model + 1 Decrement -> model - 1 -- VIEW view : Model -> Html Msg view model = div [] [ button [ onClick Decrement ] [ text "-" ] , div [] [ text (toString model) ] , button [ onClick Increment ] [ text "+" ] ]
Don't worry about the meaning of that code just yet; we will use it just to test our setup.
The first thing we should check is that we are getting the syntax highlighting in our editor, if you just see plain text, check the corresponding section of this article again.
Next, we are going to test the compilation of Elm code using Reactor. In the terminal, go to the project directory and execute the following command:
elm reactor
A message should appear with something like this:
elm-reactor 0.18.0 Listening on http://localhost:8000/
That means that it is working and we have a web server listening on the port 8000 in localhost. If we open that address in our web browser we should see a file navigator, click in the first-application.elm file and it will build our project. Once it is ready, we will see a page with a little widget with a number and two buttons. That's the result of our code.
Elm example: Number counter
Conclusion
We have explored some of the advantages of functional programming and the Elm language, and we are now more familiar with the platform that we will use to build our projects.
To get more detailed information about Elm, you can check out the book An Introduction to Elm by Evan Czaplicki.
Why Elm? (And How To Get Started With It) is a post from CSS-Tricks
via CSS-Tricks http://ift.tt/2krDphr
0 notes