Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

Tech Guides - Languages

34 Articles
article-image-exploring-language-improvements-c-72-and-73-0
Mark J.
28 Nov 2017
9 min read
Save for later

Exploring Language Improvements in C# 7.2 and 7.3

Mark J.
28 Nov 2017
9 min read
With the C# 7 generation, Microsoft has decided to increase the cadence of language releases, releasing minor version numbers, aka point releases, for the first time since C# 1.1. This allows new features to be used by programmers faster than ever before, but the policy poses a challenge to writers of books about C#. Introduction One of the hardest parts of writing for technology is deciding when to stop chasing the latest changes and adding new content. Back in March 2017, I was reviewing the final drafts of the second edition of my book, C# 7 and .NET Core – Modern Cross-Platform Development. In Chapter 2, Speaking C# I got to the topic of representing number literals. One of the improvements in C# 7 is the ability to use the underscore character as a digit separator. For example, when writing large numbers in decimal you can improve the readability of number literals using underscores, and you can express binary or hexadecimal number literals by prefixing the number literal with 0b or 0x, as shown in the following code: // C# 6 and earlier int decimalNotation = 2000000; // 2 million // C# 7 and 7.1 int decimalNotation = 2_000_000; // 2 million int binaryNotation = 0b0001_1110_1000_0100_1000_0000; // 2 million int hexadecimalNotation = 0x001E_8480; // 2 million But in the final draft I hadn't included code examples of using underscores in number literals. At the last minute, I decided to add the preceding examples to the book. Unfortunately, I assumed that the underscore could be used to separate the prefixes 0b and 0x from the digits, and did not check the code examples would compile until the following day, after the book had gone to print. I had to release an erratum on the book's web page before it even reached the shelves. I felt so embarrassed. In the third edition, C# 7.1 and .NET Core 2.0 – Modern Cross-Platform Development, I fixed the code examples by removing the unsupported underscores after the prefixes since they are not supported in C# 7 or C# 7.1. Ironically, just as the third edition was due to go to print, Microsoft released C# 7.2, which adds support for using an underscore after the prefixes, as shown in the following code: // C# 7.2 and later int binaryNotation = 0b_0001_1110_1000_0100_1000_0000; // 2 million int hexadecimalNotation = 0x_001E_8480; // 2 million Gah! Clearly, I wasn't the only programmer who thought it is natural to be able to use underscores after the 0b or 0x prefixes. For the third edition, I decided not to make any last-minute changes to the book. This was partly because I didn't want to risk making a mistake again, and also because the code examples do work, they just don't show the latest improvement. Maybe in the fourth edition I will finally get the whole book perfect! But, of course, in the programming world that's impossible. Since the third edition covers C# 7.1, I have written this article to cover the improvements in C# 7.2 that are available today, and to preview the improvements coming early in 2018 with C# 7.3. Enabling C# 7 point releases Developer tools like Visual Studio 2017, Visual Studio Code, and the dotnet command line interface assume that you want to use the C# 7.0 language compiler by default. To use the improvements in a C# point release like 7.1 or 7.2, you must add a configuration element to the project file, as shown in the following markup: <LangVersion>7.2</LangVersion> Potential values for the <LangVersion> markup are shown in the following table: LangVersion Description 7, 7.1, 7.2, 7.3, 8 Entering a specific version number will use that compiler if it has been installed. default Uses the highest major number without a minor number, for example, 7 in 2017 and 8 later in 2018. latest Uses the highest major and highest minor number, for example, 7.2 in 2017, 7.3 early in 2018, 8 later in 2018. To be able to use C# 7.2, either install Visual Studio 2017 version 15.5 on Windows, or install .NET Core SDK 2.1.2 on Windows, macOS, or Linux from the following link: https://www.microsoft.com/net/download/ Run the .NET Core SDK installer, as shown in the following screenshot: Setting up a project for exploring C# 7.2 improvements In Visual Studio 2017 version 15.5 or later, create a new Console App (.NET Core) project named ExploringCS72 in a solution named Bonus, as shown in the following screenshot: You can download the projects created in this article from the Packt website or from the following GitHub repository: https://github.com/PacktPublishing/CSharp-7.1-and-.NET-Core-2.0-Modern-Cross-Platform-Development-Third-Edition/tree/master/BonusSectionCode/Bonus In Visual Studio Code, create a new folder named Bonus with a subfolder named ExploringCS72. Open the ExploringCS72 folder. Navigate to View | Integrated Terminal, and enter the following command: dotnet new console In either Visual Studio 2017 or Visual Studio Code, edit the ExploringCS72.csproj file, and add the <LangVersion> element, as shown highlighted in the following markup: <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp2.0</TargetFramework> <LangVersion>7.2</LangVersion> </PropertyGroup> </Project> Edit the Program.cs file, as shown in the following code: using static System.Console; namespace ExploringCS72 { class Program { static void Main(string[] args) { int year = 0b_0000_0111_1011_0100; WriteLine($"I was born in {year}."); } } } In Visual Studio 2017, navigate to Debug | Start Without Debugging, or press Ctrl + F5. In Visual Studio Code, in Integrated Terminal, enter the following command: dotnet run You should see the following output, which confirms that you have successfully enabled C# 7.2 for this project: I was born in 1972. In Visual Studio Code, note that the C# extension version 1.13.1 (released on November 13, 2017) has not been updated to recognize the improvements in C# 7.2. You will see red squiggle compile errors in the editor even though the code will compile and run without problems, as shown in the following screenshot: Controlling access to type members with modifiers When you define a type like a class with members like fields, you control where those members can be accessed by applying modifiers like public and private. Until C# 7.2, there have been five combinations access modifier keywords. C# 7.2 adds a sixth combination, as shown in the last row of the following table: Access modifier Description private Member is accessible inside the type only. This is the default if no keyword is applied to a member. internal Member is accessible inside the type, or any type that is in the same assembly. protected Member is accessible inside the type, or any type that inherits from the type. public Member is accessible everywhere. internal protected Member is accessible inside the type, or any type that is in the same assembly, or any type that inherits from the type. Equivalent to internal_OR_protected. private protected Member is accessible inside the type, or any type that inherits from the type and is in the same assembly. Equivalent to internal_AND_protected. Setting up a .NET Standard class library to explore access modifiers In Visual Studio 2017 version 15.5 or later, add a new Class Library (.NET Standard) project named ExploringCS72Lib to the current solution, as shown in the following screenshot: In Visual Studio Code, create a new subfolder in the Bonus folder named ExploringCS72Lib. Open the ExploringCS72Lib folder. Navigate to View | Integrated Terminal, and enter the following command: dotnet new classlib Open the Bonus folder so that you can work with both projects. In either Visual Studio 2017 or Visual Studio Code, edit the ExploringCS72Lib.csproj file, and add the <LangVersion> element, as shown highlighted in the following markup: <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>7.2</LangVersion> </PropertyGroup> </Project> In the class library, rename the class file from Class1 to AccessModifiers, and edit the class, as shown in the following code: using static System.Console; namespace ExploringCS72 { public class AccessModifiers { private int InTypeOnly; internal int InSameAssembly; protected int InDerivedType; internal protected int InSameAssemblyOrDerivedType; private protected int InSameAssemblyAndDerivedType; // C# 7.2 public int Everywhere; public void ReadFields() { WriteLine("Inside the same type:"); WriteLine(InTypeOnly); WriteLine(InSameAssembly); WriteLine(InDerivedType); WriteLine(InSameAssemblyOrDerivedType); WriteLine(InSameAssemblyAndDerivedType); WriteLine(Everywhere); } } public class DerivedInSameAssembly : AccessModifiers { public void ReadFieldsInDerivedType() { WriteLine("Inside a derived type in same assembly:"); //WriteLine(InTypeOnly); // is not visible WriteLine(InSameAssembly); WriteLine(InDerivedType); WriteLine(InSameAssemblyOrDerivedType); WriteLine(InSameAssemblyAndDerivedType); WriteLine(Everywhere); } } } Edit the ExploringCS72.csproj file, and add the <ItemGroup> element to reference the class library in the console app, as shown highlighted in the following markup: <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp2.0</TargetFramework> <LangVersion>7.2</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..ExploringCS72LibExploringCS72Lib.csproj" /> </ItemGroup> </Project> Edit the Program.cs file, as shown in the following code: using static System.Console; namespace ExploringCS72 { class Program { static void Main(string[] args) { int year = 0b_0000_0111_1011_0100; WriteLine($"I was born in {year}."); } public void ReadFieldsInType() { WriteLine("Inside a type in different assembly:"); var am = new AccessModifiers(); WriteLine(am.Everywhere); } } public class DerivedInDifferentAssembly : AccessModifiers { public void ReadFieldsInDerivedType() { WriteLine("Inside a derived type in different assembly:"); WriteLine(InDerivedType); WriteLine(InSameAssemblyOrDerivedType); WriteLine(Everywhere); } } } When entering code that accesses the am variable, note that IntelliSense only shows members that are visible due to access control. Passing parameters to methods In the original C# language, parameters had to be passed in the order that they were declared in the method. In C# 4, Microsoft introduced named parameters so that values could be passed in a custom order and even made optional. But if a developer chose to name parameters, all of them had to be named. In C# 7.2, you can mix named and unnamed parameters, as long as they are passed in the correct position. In Program.cs, add a static method, as shown in the following code: public static void PassingParameters(string name, int year) { WriteLine($"{name} was born in {year}."); } In the Main method, add the following statement: PassingParameters(name: "Bob", 1945); Visual Studio Code will show an error, as shown in the following screenshot, but the code will compile and execute. Optimizing performance with value types The fourth and final feature of C# 7.2 is working with value types while using reference semantics. This can improve performance in very specialized scenarios. You are unlikely to use them much in your own code, unless like Microsoft themselves, you create frameworks for other programmers to build upon that need to do a lot of memory management. You can learn more about these features at the following link: https://docs.microsoft.com/en-gb/dotnet/csharp/reference-semantics-with-value-types Conclusion I plan to refresh this bonus article when C# 7.3 is released to update it with the new features in that point release. Good luck with all your C# adventures!
Read more
  • 0
  • 0
  • 6182

article-image-how-has-python-remained-so-popular
Antonio Cucciniello
21 Sep 2017
4 min read
Save for later

How has Python remained so popular?

Antonio Cucciniello
21 Sep 2017
4 min read
In 1991, the Python programming language was created. It is a dynamically typed object oriented language that is often used for scripting and web applications today. It is usually paired with frameworks such as Django or Flask on the backend. Since its creation, it's still extremely relevant and one of the most widely used programming languages in the world. But why is this the case? Today we will look at the reason why the Python programming language has still been extremely popular over the last couple of years. Used by bigger companies Python is widely used by bigger technology companies. When bigger tech companies (think companies such as Google) use Python, the engineers that work there also use it. If the developers use Python at their jobs, they will take it to their next job and pass the knowledge on. In addition, Python continues to be used organically when these developers use their knowledge of this language in any of their personal projects they have as well, futher spreading its usage. Plenty of styles are not used In Python, whitespace is important, but in other languages such as JavaScript and C++ it is not. The whitespace is used to dictate the scope of the statements in that indent. By making whitespace important it reduces the need for things like braces and semicolons in your code. That reduction alone can make your code look simpler and cleaner. People are always more willing to try a language that looks and feels cleaner, because it seems easier to learn psychologically. Variety of libraries and third-party support Being around as long as it has, Python has plenty of built-in functionality. It has an extremely large standard library with plenty of things that you can use in your code. On top of that, it has plenty of third-party support libraries that make things even easier. All of this gained functionality allows programmers to focus on the more important logic that is vital to their application's core functionality. This makes programmers more efficient, and who doesn't like efficiency? Object oriented As mentioned earlier, Python is an object oriented programming language. Due to it being object oriented, more people are likely to adopt it because object orient programming allows developers to model their code very similar to real world behavior. Built-in testing Python allows you to import a package called unittest. This package is a full unit testing suite with setup and teardown functions. Having this built in, it is something that is stable for developers to use to test their applications. Readability and learnability As we mentioned earlier, the whitespace is important, therefore we do not need brackets and semicolons. Also Python is dynamically typed so it is easier to create and use variables while not really having to worry about the type. All of these topics could be difficult for new programmers to learn. Python makes it easier by removing some of the difficult parts and having nicer looking code. The reduction of difficulty allows people to choose Python as their first programming language more often than others. (This was my first programming language.) Well documented Building upon the standard libraries and the vast amount of third-party packages, the code in those applications is usually well documented. They tend to have plenty of helpful comments and tons of additional documentation to explain what is happening. From a developer stand point this is crucial. Having great documentation can make or break a language's usage for me. Multiple applications To top it off, Python has many applications it can be used in. It can be used to develop games for fun, web applications to aid businesses, and data science applications. The wide variety of usage attracts more and more people to Python, because when you learn the language you now have the power of versatility. The scope of applications is vast. With all of these benefits, who wouldn't consider Python as their next language of choice? There are many options out there, but Python tends to be superior when it comes to readability, support, documentation, and its wide application usage. About the author Antonio Cucciniello is a Software Engineer with a background in C, C++ and JavaScript (Node.Js) from New Jersey. His most recent project called Edit Docs is an Amazon Echo skill that allows users to edit Google Drive files using your voice. He loves building cool things with software, reading books on self-help and improvement, finance, and entrepreneurship. Follow him on twitter @antocucciniello, and follow him on GitHub here: https://github.com/acucciniello.
Read more
  • 0
  • 0
  • 2995

article-image-oldest-programming-languages-use-today
Antonio Cucciniello
11 Jul 2017
5 min read
Save for later

The oldest programming languages in use today

Antonio Cucciniello
11 Jul 2017
5 min read
Today, we are going to be discussing some of the oldest, most established programming languages that are still in use today. Some developers may be surprised to learn that many of these languages surpass them in age, in a world where technology, especially in the world of development, is advancing at such a rapid rate. But then, old is gold, after all. So, in age order, let’s present the oldest programming languages in use today: C The C language was created in 1972 (it’s not that old, okay). C is a lower level language that was based an earlier language called B (do you see a trend here?) It is a general-purpose language, and a parent language which many future programming languages derive from, such as C#, Java, JavaScript, Perl, PHP and Python. It is used in many applications that must interface with hardware or play with memory. C++ Pronounced see-plus-plus, C++ was developed 11 years later in 1983. It is very similar to C, in fact it is often considered an extension of C. It added various concepts such as classes, virtual functions, and templates. It is more of an intermediate level language that can be used lower level or higher level, depending on the application. It is also known for being used in low latency applications. Objective-C Around the same time as C++ was being released to the public, Objective-C was created. If you took an educated guess from the name and said that it would be another extension of C, then you’d be right. This version was meant to be an object-oriented version of C (there’s a lot in a name, clearly). It is used, probably most famously, by Apple. If you are a Mac or iOS user, then your iPhone or Mac applications were most likely developed with Objective-C (until they recently moved over to Swift). Python We are going to take a quick jump ahead in time to the 90’s for this one. In 1991, the Python programming language was released, though it had been in development in the late 80’s. It is a dynamically-typed, object-oriented language that is often used for scripting and web applications. It is usually used with some of its frameworks like Django or Flask on the backend. It is one of the most popular programming languages in use today. Ruby In 1993, Ruby was released. Today, you probably heard of Ruby on Rails, which primarily is used to create the backend of web applications using Ruby. Unlike the many languages derived from C, this language was influenced by older languages such as Perl and Lisp. This language was designed for productive and fun programming. This was done by making the language closer to human needs, rather than machine needs. Java Two years later in 1995, Java was developed. This is a high level language that is derived from C. It is famously known for its use in web applications and as the language to use to develop Android applications and Android OS. It used to be the most popular language a few years ago, but its popularity and usage has definitely decreased. PHP In the same year as Java was developed, PHP was born. It is an open source programming language developed for the purpose of creating dynamic websites. It is also used for server side web development. Its usage is definitely declining, but it is still in use today. JavaScript That same year (yup, ’95 was good year for programming, not so much for fans of Full House), JavaScript was brought to the world. Its purpose was to be a high level language that helped with the functionality of a web page. Today, it is sometimes used as a scripting language, as well as being used on the backend of applications with the release of Node.js. It is one of the most popular and widely used programming languages today. Conclusion That was our brief history lesson on some in use programming languages. Even though some of them are 20, 30, even over 40 years old, they are being used by thousands of developers daily. They all have a variety of uses, from lower level to higher level, from web applications to mobile applications. Do you feel there is a need for newer languages, or are you happy with what we have? If you have any favorites, let us know which one and why! About the author Antonio Cucciniello is a Software Engineer with a background in C, C++ and JavaScript (Node.Js) from New Jersey.   His most recent project called Edit Docs is an Amazon Echo skill that allows users to edit Google Drive files using your voice.  He loves building cool things with software, reading books on self-help and improvement, finance, and entrepreneurship. Follow him on twitter @antocucciniello, and follow him on GitHub here: https://github.com/acucciniello
Read more
  • 0
  • 0
  • 12391

article-image-what-makes-programming-languages-simple-or-complex
Antonio Cucciniello
12 Jun 2017
4 min read
Save for later

What makes programming languages simple or complex?

Antonio Cucciniello
12 Jun 2017
4 min read
Have you been itching to learn a new programming language? Maybe you want to learn your first programming language and don't know what to choose. When learning a new language (especially your first language) you want to minimize the amount of unknowns that you will have. So you may want to choose a programming language that is simpler. Or maybe you are up for a challenge and want to learn something difficult! Today we are going to answer the question: What makes programming languages simple or complex? Previous experience The amount of experience you have programming or learning different programming concepts can greatly impact how well you learn a new language. If this is your tenth programming language you will have most likely seen plenty of the content before in the new language so that can greatly reduce the complexity. On the other hand, if this is your first language, you will be learning many new concepts and ideas that are natural to programming and that may make the language seem more complex than it probably is. Takeaway: The more programming experience you have, the lower the chances a programming language will be complex to you. Syntax The way you need to write code for that language can really affect the complexity. Some languages have many syntax rules that can be a nuisance when learning and will leave you confused. Other languages have fewer rules that will make it easier to understand for someone not familiar to the language. Additionally, for those with previous experience, if the new language has similar syntax to the old language it will help in the learning process. Another factor similar to syntax is how the code looks to the user. In my experience, the more the code has variable/function names that resemble the English language, the easier it is to understand it. Takeaway: The more syntax rules the more difficult a language can be to learn. Built-in functionality The next factor is how much built-in functionality a language has. If the language has been around for years and is being continuously updated, chances are it has plenty of helper functions and plenty of functionality. In the case of some newer languages, they might not have as much built-in functionality that allows you to develop easier. Takeaway: Generally, languages with more functionalitybuilt-in will make it easier to implement what you need in code. Concepts The fourth topic we are going to discuss here is concepts. That is, what programming concepts does this language use? There are plenty out there like object oriented programming, memory management, inheritance and more. Depending on what concepts are used in the language as well as your previous understanding of a concept, you could either really struggle with learning the language, or you could potentially find it easier than most. Takeaway: Your previous experience with specific concepts and the complexity of the concepts in the language could affect the complexity of the language as a whole. Frameworks & libraries Frameworks and libraries are very similar to built-in functionality. Frameworks and libraries are developed to make something in the language easier or to simplify a task that you would normally have to do yourself in code. So, with more frameworks you could make development easier than normal. Takeaway: If a language has plenty of support from libraries and frameworks, the language will decrease in complexity. Resources Our last topic here is arguably the most important. Ultimately, without high-quality documentation it can be very hard to learn a language. When looking for resources on a language, check out books, blog posts, tutorials, videos, documentation and forums for making sure there are plenty of resources on the topic. Takeaway: The more high-quality resources out there on the programming language, the easier it will be to learn.  When deciding on what programming languages are complex or simple, it truly depends on a few factors: your previous experience, the syntax of the language, built-in functionality, the concepts used, frameworks for support, and high-quality resources available. About the Author  Antonio Cucciniello is a Software Engineer with a background in C, C++ and JavaScript (Node.Js) from New Jersey.   His most recent project called Edit Docs is an Amazon Echo skill that allows users to edit Google Drive files using your voice.  He loves building cool things with software, reading books on self-help and improvement, finance, and entrepreneurship. Follow him on twitter @antocucciniello, and follow him on GitHub here: https://github.com/acucciniello
Read more
  • 0
  • 0
  • 3437

Banner background image
article-image-what-are-best-programming-languages-building-apis
Antonio Cucciniello
11 Jun 2017
4 min read
Save for later

What are the best programming languages for building APIs?

Antonio Cucciniello
11 Jun 2017
4 min read
Are you in the process of designing your first web application? Maybe you have built some in the past but are looking for a change in language to increase your skill set, or try out something new. If you fit into those categories, you are in the right place. With all of the information out there, it could be hard to decide on what programming language to select for your next product or project. Because any programming language can ultimately be used to write APIs, some can be better and more efficient to use than others. Today we will be discussing what should be taken into consideration when choosing the programming language to build out APIs for your web app. Comfort is essential when it comes to programming languages This goes out to any developer who has experience in a certain language. If you already have experience in a language, you will ultimately have an easier time developing, understanding the concepts involved, and you will be able to make more progress right out of the gate. This translates to improved code and performance as well because you can spend more time on that rather than learning a brand new programming language. For example, if I have been developing in Python for a few years, but I have the option between using PHP or Python as a programming language for the project, I simply select Python due to the time saved already spent learning Python. This is extremely important because when trying to do something new, you want to limit the amount of unknowns that you will have in the project. That will help your learning and help to achieve better results. If you are a brand new developer with zero programming experience, the following section might help you narrow your results. Libraries and frameworks that support developing APIs The next question to ask in the process of eliminating potential programming languages to build out your API is: Does the language come with plenty of different options for libraries or frameworks that aid in the developing of APIs? To continue with the Python example in the previous section, there is the Django REST framework that is specifically built on top of Django. Django is a web development framework for Python, made for creating an API in the programming language faster and easier. Did you hear faster and easier? Why yes you did, and that is why this is important. These libraries and frameworks allow you to speed up the development process by containing functions and objects that handle plenty of the repetitive or dirty work in building an API. Once you have spent some time researching what is available to you in terms of libraries and frameworks for languages, it is time to check out how active the communities are. Support and community The next question to ask yourself in this process is: Are the frameworks and libraries for this programming language still being supported? If so, how active is the community of developers? Do they have continuous or regular updates to their software and capabilities? Do the updates help improve security and usability? Given that not many people use the language, nor is it being updated for bug fixes in the future, you may not want to continue using it. Another thing to pay attention to is the community of users. Are there plenty of resources for you to learn from? How clear and available is the documentation? Are there experienced developers who have blog posts on the necessary topics to learn? Are there questions being asked and answered on Stack Overflow? Are there any hard resources such as magazines or textbooks that show you how to use these languages and frameworks? Potential languages for building APIs From my experience, there are a number of better programming languages.Here is an example framework for some of these languages, which you can use to start developing your next API: Language Framework Java Spring JavaScript(Node) Express Python Django PHP Laravel Ruby Ruby on Rails   Ultimately, the programming language you select is dependent on several factors: your experience with the language, the frameworks available for API building, and how active both the support and the community are. Do not be afraid to try something new! You can always learn, but if you are concerned about speed and ease of development, use these criteria to help select the language of use. Leave a comment down below and let us know which programming language is your favorite and how you will use it in your future applications!
Read more
  • 0
  • 0
  • 46722

article-image-how-do-web-development-frameworks-drive-changes-programming-languages
Antonio Cucciniellois
11 Apr 2017
5 min read
Save for later

How do web development frameworks drive changes in programming languages?

Antonio Cucciniellois
11 Apr 2017
5 min read
If you have been keeping up with technologies lately through various news sites like Hacker News and in the open source community on GitHub, you've probably noticed it seems as if there have been web development frameworks popping up left and right. It can be overwhelming to follow them all and understand how they are causing things to change in the technology world. As developers, we want to be able to catch a web development trend early and improve our skills with the technology that will be used in the future. Let's discuss the effects of web development frameworks and how they drive change in languages. What is a web development framework? Before we continue, let's make sure that everyone is on the same page regarding what exactly a web development framework is. It is defined as software made to aid in the creation and development of web applications. These framewoeks are usually made to help out with speeding up common tasks that a web developer runs into. There are client-side frameworks, which help with speeding up front-end work, along with helping us create dynamic web pages. Some examples would be React.js and Angular.js. There are also server-side web development frameworks that help with creating a server, handling routes, and much more. A few examples of this kind of framework are Express.js, Django, and Rails. Now we know what exactly web development frameworks are, but how do they affect languages? Effects on languages Quantity StackOverflow recently came out with a new Developer Survey for 2017, in which they interviewed 64,000 developers and asked them a wide variety of questions. One question was about their usage of various languages. Here is a graph of their findings:   Changes_Languages_Image If you look at this graph, it shows you the percentage of developers using a language in the year 2013, and compares it to 2017. Four years may not be a long period of time for other fields, but for software engineers, that is a century. We can see that the usage of languages such as C#, C, and C++ has been decreasing over these years. Meanwhile, Node.js and Python have increased in usage. After doing some research on the number of prominent web development frameworks that have come out for these languages in the past few years, I noticed a couple of things: C had one framework that came out in 2015. C++ had four web development frameworks over those years. On the other hand, Python had 17 frameworks aiding its development, and Node.js had nine frameworks in the past 3 years alone. What does this all mean? Well, it seems as if the languages that received more web development frameworks in order to make development easier for engineers saw an increase in the number of users, while the others, which did not receive as many web development frameworks, ended up being used less and less. Verdict: There must be a correlation at least between the number of web development frameworks and the corresponding language's usage. Ease of use and quality Not all of these frameworks are created equal. Some web development frameworks are extremely easy to use when starting out, and for others, it can take longer to create your first web application. Time is a factor when learning a new framework (or migrating existing software to it), and if it is not easy to pick up that framework, it can be a barrier to its usage. Another factor is having previous experience with the language. A reason why Node.js has an increasing user base is because it is written in JavaScript. If you have done any basic front-end development, you must have used some JavaScript to make your application. When learning a new web framework, if you have to learn a new obscure language that does not have many other uses, it does not make it easier for you, hence slowing down transition time. Lastly, if the framework itself does not actually make web development tasks for the engineer any easier, or not much easier, then that language will end up being used less. Verdict: If the framework is easy to use and speeds up development time, more people will use it and move toward it. Conclusion Overall, there are two clear factors of web development frameworks that drive changes in languages. If there are plenty of frameworks, people will be more likely to use the language that the framework was created for. If the frameworks are simple and really speed up development time, that also will increase the language's usage. If you enjoyed this post, share it on Twitter! Leave a comment down below and let me know your thoughts on the subject.  About the author Antonio Cucciniellois a software engineer with a background in C, C++, and JavaScript (Node.Js) from New Jersey. His most recent project, Edit Docs, is an Amazon Echo skill that allows users to edit Google Drive files using voice. He loves building cool things with software and reading books on self-help and improvement, finance, and entrepreneurship. You can follow him on Twitter (@antocucciniello) and on GitHub. 
Read more
  • 0
  • 0
  • 1342
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-how-are-container-technologies-changing-programming-languages
Xavier Bruhiere
11 Apr 2017
7 min read
Save for later

How are container technologies changing programming languages?

Xavier Bruhiere
11 Apr 2017
7 min read
In March 2013, Solomon Hykes presented Docker, which democratized access to Linux containers. The underlying technology, control groups, was already incubating for a few years at Google. However, Docker abstracts away the complexity of containers' lifecycle and adoption skyrocketed among developers. In June 2016, Datadog published some compelling statistics about Docker adoption: the industry as a whole increasingly adopted containers for production. Since everybody is talking about how to containarize everything, I would like to take a step back and study how it is influencing the development of our most fundamental medium: programming languages. The rise of Golang, the Java8 release, Python 3.6 improvements--how do language development and containerization marketsplay together in 2017? Scope of Container Technologies Let's define the scope of what we call container technologies. Way back in 2006, two Google engineers started to work on a new technology for the partition hierarchical group of tasks. They called it cgroups and submitted the code to the Linux Kernel. This lightweight approach of virtualization (sorry Mike) was an opportunity for infrastructure-heavy companies and Heroku and Google, among others, took advantage of it to orchestrate so-called containers. Put simply, they were now able to think of application deployment as the dynamic manipulation of theses determinist runtimes. Whatever the code or the business logic, it was encapsulated into a uniform execution format. Cgroups are very low level though, and tooling around the original primitives quickly emerged, like LXC backed by Canonical. Then, Solomon Hykes came in and made the technology widely accessible with Docker. The possibilities were endless and, indeed, developers and startups alike rushed in all directions. Lately, however, the hype seems to have cooled down. Docker market share is being questioned while the company sorts its business strategy. At the end of the day, developers forgetabout vendors/technology and just want simple tooling for more efficient coding. Docker-compose, Red Hat Container Development Kit, GC Container Builder, or local Kubernetes are very sophisticated pieces of technologies that hide the details of the underlying container mechanics. What they give to engineers are powerful primitives for advanced development practices: development/production environment parity, transparent services replication, and predictable runtime configuration. However,this is not just about development correctness or convenience, considering how containers are eating the IaaS landscape. It is also about deployment optimizations and resilience. Tech giants who operate crazy large infrastructures developed incredible frameworks, often in the open, to push how fast they could deploy auto-scalable, self-healing, zero-downtime fleets. Apache Mesos backed by Microsoft, or Kubernetes by Google, make at least two promises: Safe and agile deployments at the (micro-)service level Reliable orchestration with elegant service discovery, load-balancing, and failure management (because you have to accept that production always goes wrong at some point) Containers enabled us to manage complexity with infrastructure design patterns like micro-services or serverless. Behind the hype of these buzzwords, engineers try to improve team collaboration, safe and agile deployments, large project maintenance, and monitoring. However,we quickly came to realize it was sold with a DevOps tax. Fortunately, the software industry has a hard-won experience of such balance, and we start to see it converging toward the most robust approaches. This container landscape overview hopefully provides the requirements to now study how it has impacted the development of programming languages. We will take a look first at their ecosystems, and then we will dive into language designs themselves. Language Ecosystems and Usages Most developers are now aware of how invasive container technologies can be. It makes its way into your development toolbox or how your company manages its servers. Some will argue that the fundamentals of coding did not evolve much, but the trend is hard to ignore anyway. While we are free, of course, to stay away from Silicon Valley’s latest fashions, I think containers tackle a problem most languages struggle with: dependencies and packaging. Go, for example, got packaging right, but it’s still trying to figure out how to handle dependencies versioning and vendoring. JavaScript, on the other hand, has npm to manage fine-grained third-party code, but build tools are scattered all over Github. Containers won't spare you the pain of setting things up (they target runtimes, not build steps), but it can lower the bar of language adoption. Official images can run most standard language projects and one can both give a try and deploy a basic hello world in no time. When you realize that Go1.5+ needs Go1.4 to be compiled, it can be a relief to just docker run your five-lines-long main.go. Growing a language community is a sure way to develop its tooling and libraries, but containers also influence how we design those components. They are the cloud counterparts of the current functional trend. We tend to embrace a world where both functions and servers are immutable and single-purpose. We want predictable, pure primitives (in the mathematical sense). All of that to match increasingly distributed and intensive workloads. I hope those approaches come from a product’s need but, obviously, having the right technology at hand drives the innovation. As software engineers in 2017, we also design libraries and tools with containers in mind: high performance networking, distributed process management, Data pipelines, and so on. Language Design What about languages? To get things straight, I don't think containers influence how Guido Van Rossum designs Python. And that is the point of containers. They abstract the runtime to let you focus on your code™  (it is literally on every Docker-based PaaS landing page). You should be able to design whatever logic implementation you need, and containers will come in handy to help you run it when needed. I do believe, however, that both languages last evolutions and the rise of containers serve the same maturation of ideas in the tech community. Correctness at compile time: Both Python 3.6, ELM, and JavaScript ES7 are bringing back typing to their language (see type hints or Typescripts). An application running locally will launch just the same in production. You can even run tests against multiple runtimes without complex scripts or heavy setup. Simplicity: Go won a lot of its market share thanks to its initial simplicity, taking a lot of decisions for you. Containers try their best to offer one unified way to run code, whatever the stack. Functional: Scala, JavaScript, and Elixir, all enforce immutable states, function compositions with support for lambda expressions, and function purity. It echoes the serverless trend that promotes function as a service. Most of the providers leverage some kind of container technology to bring the required agility to their platforms. There is something elegant about having language features, programmatical design patterns, and infrastructure operations going hand in hand. While I don't think one of them influences the other, I certainly believe that their development smoothen other’s innovations. Conclusion Container technologies and the fame around them are finally starting to converge toward fewer and more robust usages. At the same time, infrastructure designs, new languages, and evolutions of existing ones seem to promote the same underlying patterns: simple, functional, decoupled components. I think this coincidence comes from industry maturity and openness, more than, as I said, one technology influencing the other. Containers, however, are shaking how we collaborate and design tools for the languages we love. It changes the way we on-board developers learning a new language. It changes how we setup local development environments with micro-replicates of production topology. It changes the way we package and deploy code. And, most importantly, it enables architectures like micro-services or lambdas that influence how we design our programs. In my opinion, programming language design should continue to evolve decoupled from containers. They serve different purposes, and given the pace of the tech industry, major languages should never depend on new shining tools. That being said, the evolution of languages now comes with the activity of its community—what they build, how they use it, and how they spread it in companies. Coping with containers is an opportunity to bring new developers, improve production robustness, and accelerate both technical and human growth. About the author Xavier Bruhiere is a lead developer at AppTurbo in Paris, where he develops innovative prototypes to support company growth. He is addicted to learning, hacking on intriguing hot techs (both soft and hard), and practicing high-intensity sports.
Read more
  • 0
  • 0
  • 3213

article-image-where-he-develops-innovative-prototypes-to-support-company-growth-he-is-addicted-to-learning
Xavier Bruhiere
26 Sep 2016
1 min read
Save for later

where he develops innovative prototypes to support company growth. He is addicted to learning

Xavier Bruhiere
26 Sep 2016
1 min read
and practicing high-intensity sports. "
Read more
  • 0
  • 0
  • 1114

article-image-7-tips-python-performance
Gabriel Marcondes
24 Jun 2016
7 min read
Save for later

7 Tips For Python Performance

Gabriel Marcondes
24 Jun 2016
7 min read
When you begin using Python after using other languages, it's easy to bring a lot of idioms with you. Though they may work, they are not the best, most beautiful, or fastest ways to get things done with Python—they're not pythonic. I've put together some tips on basic things that can provide big performance improvements, and I hope they'll serve as a starting point for you as you develop with Python. Use comprehensions Comprehensions are great. Python knows how to make lists, tuples, sets, and dicts from single statements, so you don't need to declare, initialize, and append things to your sequences as you do in Java. It helps not only in readability but also on performance; if you delegate something to the interpreter, it will make it faster. def do_something_with(value): return value * 2 # this is an anti-pattern my_list = [] for value in range(10): my_list.append(do_something_with(value)) # this is beautiful and faster my_list = [do_something_with(value) for value in range(10)] # and you can even plug some validation def some_validation(value): return value % 2 my_list = [do_something_with(value) for value in range(10) if some_validation(value)] my_list [2, 6, 10, 14, 18] And it looks the same for other types. You just need to change the appropriate surrounding symbols to get what you want. my_tuple = tuple(do_something_with(value) for value in range(10)) my_tuple (0, 2, 4, 6, 8, 10, 12, 14, 16, 18) my_set = {do_something_with(value) for value in range(10)} my_set {0, 2, 4, 6, 8, 10, 12, 14, 16, 18} my_dict = {value: do_something_with(value) for value in range(10)} my_dict {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18} Use Generators Generators are objects that generate sequences one item at a time. This provides a great gain in performance when working with large data, because it won't generate the whole sequence unless needed, and it’s also a memory saver. A simple way to use generators is very similar to the comprehensions we saw above, but you encase the sentence with () instead of [] for example: my_generator = (do_something_with(value) for value in range(10)) my_generator <generator object <genexpr> at 0x7f0d31c207e0> The range function itself returns a generator (unless you're using legacy Python 2, in which case you need to use xrange). Once you have a generator, call next to iterate over its items, or use it as a parameter to a sequence constructor if you really need all the values: next(my_generator) 0 next(my_generator) 2 To create your own generators, use the yield keyword inside a loop instead of a regular return at the end of a function or method. Each time you call next on it, your code will run until it reaches a yield statement, and it saves the state for the next time you ask for a value. # this is a generator that infinitely returns a sequence of numbers, adding 1 to the previous def my_generator_creator(start_value): while True: yield start_value start_value += 1 my_integer_generator = my_generator_creator(0) my_integer_generator <generator object my_generator_creator at 0x7f0d31c20708> next(my_integer_generator) 0 next(my_integer_generator) 1 The benefits of generators in this case are obvious—you would never end up generating numbers if you were to create the whole sequence before using it. A great use of this, for example, is for reading a file stream. Use sets for membership checks It's wonderful how we can use the in keyword to check for membership on any type of sequence. But sets are special. They're of a mapping kind, an unordered set of values where an item's positions are calculated rather than searched. When you search for a value inside a list, the interpreter searches the entire list to see whether the value is there. If you are lucky, the value is the first of the sequence; on the other hand, it could even be the last in a long list. When working with sets, the membership check always takes the same time because the positions are calculated and the interpreter knows where to search for the value. If you're using long sets or loops, the performance gain is sensible. You can create a set from any iterable object as long as the values are hashable. my_list_of_fruits = ['apple', 'banana', 'coconut', 'damascus'] my_set_of_fruits = set(my_list_of_fruits) my_set_of_fruits {'apple', 'banana', 'coconut', 'damascus'} 'apple' in my_set_of_fruits True 'watermelon' in my_set_of_fruits False Deal with strings the right way You've probably done or read something like this before: # this is an anti-pattern "some string, " + "some other string, " + "and yet another one" 'some string, some other string, and yet another one' It might look easy and fast to write, but it's terrible for your performance. str objects are immutable, so each time you add strings, trying to append them, you're actually creating new strings. There are a handful of methods to deal with strings in a faster and optimal way. To join strings, use the join method on a separator with a sequence of strings. The separator can be an empty string if you just want to concatenate. # join a sequence of strings, based on the separator you want ", ".join(["some string", "some other string", "and yet another one"]) 'some string, some other string, and yet another one' ''.join(["just", "concatenate"]) 'justconcatenate' To merge strings, for example, to insert information in templates, we have a classical way; it resembles the C language: # the classical way "hello %s, my name is %s" % ("everyone", "Gabriel") 'hello everyone, my name is Gabriel' And then there is the modern way, with the format method. It is quite flexible: # formatting with sequencial strings "hello {}, my name is {}".format("everyone", "Gabriel") 'hello everyone, my name is Gabriel' # formatting with indexed strings "hello {1}, my name is {2} and we all love {0}".format("Python", "everyone", "Gabriel") 'hello everyone, my name is Gabriel and we all love Python' Avoid intermediate outputs Every programmer in this world has used print statements for debugging or progress checking purposes at least once. If you don't know pdb for debugging yet, you should check it out immediately. But I'll agree that it's really easy to write print statements inside your loops to keep track of where your program is. I'll just tell you to avoid them because they're synchronous and will significantly raise the execution time. You can think of alternative ways to check progress, such as watching via the filesystem the files that you have to generate anyway. Asynchronous programming is a huge topic that you should take a look at if you're dealing with a lot of I/O operations. Cache the most requested results Caching is one of the greatest performance tunning tweaks you'll ever find. Python gives us a handy way of caching function calls with a simple decorator, functools.lru_cache. Each time you call a function that is decorated with lru_cache, the interpreter checks whether that call was made recently, on a cache that is a dictionary of parameters-result pairs. dict checks are as fast as those of set, and if we have repetitive calls, it's worth looking at this cache before running the code again. from functools import lru_cache @lru_cache(maxsize=16) def my_repetitive_function(value): # pretend this is an extensive calculation return value * 2 for value in range(100): my_repetitive_function(value % 8) The decorator gives the method cache_info, where we can find the statistics about the cache. We can see the eight misses (for the eight times the function was really called), and 92 hits. As we only have eight different inputs (because of the % 8 thing), the cache size was never fully filled. my_repetitive_function.cache_info() CacheInfo(hits=92, misses=8, maxsize=16, currsize=8) Read In addition to these six tips, read a lot, every day. Read books and other people's code. Make code and talk about code. Time, practice, and exchanging experiences will make you a great programmer, and you'll naturally write better Python code. About the author Gabriel Marcondes is a computer engineer working on Django and Python in São Paulo, Brazil. When he is not coding, you can find him at @ggzes, talking about rock n' roll, football, and his attempts to send manned missions to fictional moons.
Read more
  • 0
  • 0
  • 3601

article-image-eight-things-you-need-learn-python
Oli Huggins
02 Jun 2016
4 min read
Save for later

Eight Things You Need To Learn with Python

Oli Huggins
02 Jun 2016
4 min read
We say it a lot, but Python really is a versatile language that can be applied to many different purposes. Web developers, data analysts, security pros - there's an impressive range of challenges that can be solved by Python. So, what exactly should you be learning to do with this great language to really get the most out of it?   Writing Python What's the most important thing to learn with Python? How to write it. As Python becomes the popular language of choice for most developers, there is an increasing need to learn and adopt it on different environments for different purposes. The Beginning Python video course focuses on just that. Aimed at a complete novice with no previous programming experience in Python, this course will guide the readers every step of the way. Starting with the absolute basics like understanding of variables, arrays, and strings, the course goes on teach the intricacies of Python. It teaches how you can build your own functions making use of the existing functions in Python. By the end, the course ensures that you have a strong foundation of the programming concepts in Python. Design Patterns As Python matures from being used just as a scripting language and into enterprise development and data science, the need for clean, reusable code becomes ever more vital. The modern Python developer cannot go astray with tried and true design patterns for Python when they want to write efficient, reliable Python code. The second edition of Learning Python Design Patterns is stuffed with rich examples of design pattern implementation. From OOP to more complex concepts, you'll find everything you need to improve your Python within. Machine Learning Design We all know how powerful Python is for machine learning - so why are your results proving sub-par and inaccurate? The issue is probably not your implementation, but rather with your system design. Just knowing the relevant algorithms and tools is not enough for a really effective system - you need the right design. Designing Machine Learning Systems with Python covers various machine learning designing aspects with the help of real-world data sets and examples and will enable you to evaluate and decide the right design for your needs. Python for the Next Generation Python was built to be simple, and it's the perfect language to get kids coding. With programmers getting younger and younger these days, get them learning with a language that will serve them well for life. In Python for Kids, kids will create two interesting game projects that they can play and show off to their friends and teachers, as well as learn Python syntax, and how to do basic logic building. Distributed Computing What do you do when your Python application takes forever to give the output? Very heavy computing results in delayed response or, sometimes, even failure. For special systems that deal with a lot of data and are mission critical, the response time becomes an important factor. In order to write highly available, reliable, and fault tolerant programs, one needs to take aid of distributed computing. Distributed Computing with Python will teach you how to manage your data intensive and resource hungry Python applications with the aid of parallel programming, synchronous and asynchronous programming, and many more effective techniques. Deep Learning Python is at the forefront of the deep learning revolution - the next stage of machine learning, and maybe even a step towards AI. As machine learning becomes a mainstream practice, deep learning has taken a front seat among data scientists. The Deep Learning with Python video course is a great stepping stone in entering the world of deep learning with Python -- learn the basics, clear your concepts, and start implementing efficient deep learning for making better sense of data. Get all that it takes to understand and implement Python deep learning libraries from this insightful tutorial. Predictive Analytics With the power of Python and predictive analytics, you can turn your data into amazing predictions of the future. It's not sorcery, just good data science. Written by Ashish Kumar, a data scientist at Tiger Analytics, Learning Predictive Analytics with Python is a comprehensive, intermediate-level book on Predictive Analytics and Python for aspiring data scientists. Internet of Things Python's rich libraries of data analytics, combined with its popularity for scripting microcontroller units such as the Raspberry Pi and Arduino, make it an exceptional choice for building IoT. Internet of Things with Python offers an exciting view of IoT from many angles, whether you're a newbie or a pro. Leverage your existing Python knowledge to build awesome IoT project and enhance your IoT skills with this book.  
Read more
  • 0
  • 0
  • 10239
article-image-python-oop-python-object-oriented-programming
Liz Tom
25 Apr 2016
5 min read
Save for later

Python - OOP! (Python: Object-Oriented Programming)

Liz Tom
25 Apr 2016
5 min read
Or Currency Conversion using Python I love to travel and one of my favorite programming languages is Python. Sometimes when I travel I like to make things a bit more difficult and instead of just asking Google to convert currency for me, I like to have a script on my computer that requires me to know the conversion rate and then calculate my needs. But seriously, let's use a currency converter to help explain some neat reasons why Object Oriented Programming is awesome. Money Money Money First let's build a currency class. class Currency(object): def __init__(self, country, value): self.country = country self.value = float(value) OK, neato. Here's a currency class. Let's break this down. In Python every class has an __init__ method. This is how we build an instance of a class. If I call Currency(), it's going to break because our class also happens to require two arguments. self is not required to be passed. In order to create an instance of currency we just use Currency('Canada', 1.41) and we've now got a Canadian instance of our currency class. Now let's add some helpful methods onto the Currency class. def from_usd(self, dollars): """If you provide USD it will convert to foreign currency """ return self.value * int(dollars)def to_usd(self, dollars): """If you provide foreign currency it will convert to USD """ return int(dollars) / self.value Again, self isn't needed by us to use the methods but needs to be passed to every method in our class. self is our instance. In some cases self will refer to our Canadian instance but if we were to create a new instance Currency('Mexico', 18.45) self can now also refer to our Mexican instance. Fun. We've got some awesome methods that help me do math without me having to think. How does this help us? Well, we don't have to write new methods for each country. This way, as currency rates change, we can update the changes rather quickly and also deal with many countries at once. Conversion between USD and foreign currency is all done the same way. We don't need to change the math based on the country we're planning on visiting, we only need to change the value of the currency relative to USD. I'm an American so I used USD because that's the currency I'd be converting to and from most often. But if I wanted, I could have named them from_home_country and to_home_country. Now how does this work? Well, if I wanted to run this script I'd just do this: again = True while again: country = raw_input('What country are you going to?n') value = float(raw_input('How many of their dollars equal 1 US dollarn')) foreign_country = Currency(country, value) convert = raw_input('What would you like to convert?n1. To USDn2. To %s dollarsn' % country) dollars = raw_input('How many dollars would you like to convert?n') if( convert == '1' ): print dollars + ' ' + country + ' dollars are worth ' + str(foreign_country.to_usd(dollars)) + ' US dollarsn' elif( convert == '2' ): print dollars + ' US dollars are worth ' + str(foreign_country.from_usd(dollars)) + dollars + ' ' + country again = raw_input('nnnWant to go again? (Y/N)n') if( again == 'y' or again == 'Y' ): again = True elif( again == 'n' or again == 'N' ): again = False **I'm still using Python 2 so if you're using Python 3 you'll want to change those raw_inputs to just input. This way we can convert as much currency as we want between USD and any country! I can now travel the world feeling comfortable that if I can't access the Internet and I happen to have my computer nearby and I am at a bank or the hotel lobby staring at the exchange rate board, I'll be able to convert currency with ease without having to remember which way converts my money to USD and which way converts USD to Canadian dollars. Object-oriented programming allows us to create objects that all behave in the same way but store different values, like a blue car, red car, or green car. The cars all behave the same way but they are all described differently. They might all have different MPG but the way we calculate their MPG is the same. They all have four wheels and an engine. While it can be harder to build your program with object oriented design in mind, it definitely helps with maintainability in the long run. About the Author Liz Tom is a Software Developer at Pop Art, Inc in Portland, OR.  Liz’s passion for full stack development and digital media makes her a natural fit at Pop Art.  When she’s not in the office, you can find Liz attempting parkour and going to check out interactive displays at museums.
Read more
  • 0
  • 0
  • 3470

article-image-essential-tools-for-go-programming
Nicholas Maccharoli
14 Jan 2016
5 min read
Save for later

Essential Tools for Go Programming

Nicholas Maccharoli
14 Jan 2016
5 min read
Golang as a programming language is a pleasure to work with, but the reason for this also comes largely in part from the great community around the language and its modern tool set, both from standard distribution and third-party tools. The go command On a system with go installed, type go with no arguments to see its quick help menu. Here, you will see the basic go commands, such as build, run, get, install, fmt, and so on. Go ahead and take a minute to run go help on some verbs that look interesting; I promise I'll be here when you get back. Basic Side options The go build and go run commands do what you think they do, as is also the case with go test, which runs any test files in the directory it is passed. The go clean command wipe out all the compiled and executable files from the directory in which it is run. Run this command when you want to force a build to be made entirely from source again. The go version command prints out the version and build info, as you might expect. The go env command is very useful when you want to see exactly how your environment is set up. Running it will show where all your environment variables point and will also make you aware of which ones are still not properly set. go doc: Which arguments did this take again? Whenever in doubt, just give go doc a call. Just running go doc [Package Name] will give you a high-level readout of the types, interfaces, and behavior defined in this package; that is, go doc net/http will give you all the function stubs and types defined. If you just need to check the order or types of arguments that a function takes, run go doc on the package and use a tool like grep to grab the relevant line, such as go doc net/http | grep -i servecontent This will produce just what we need! func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker) If you need more detail on the function or type, just run the go doc command with the package and function name, and you will get a quick description of this function or type. gofmt This little tool is quite a time-saver. I mainly use it to ensure that my source files are stylistically correct, and I also use the -s flag to let gofmt simplify my code. Just run gofmt -w on a file or an entire directory to fix up the files in place. After running this command, you should see the proper use of white space and indentation corrected to eight space tabs. Here is a diff of a file with poor formatting that I ran through gofmt: Original package main import "fmt" func main() { hello_to := []string{"Dust", "Trees", "Plants", "Carnivorous plants"} for _, value := range hello_to { fmt.Printf("Hello %v!n",value) } } After running gofmt -w Hello.go package main import "fmt" func main() { hello_to := []string{"Dust", "Trees", "Plants", "Carnivorous plants"} for _, value := range hello_to { fmt.Printf("Hello %v!n", value) } } As you can see, the indentation looks much better and reads way easier! The magic of gofmt -s The -s flag to gofmt helps clean up unnecessary code; so, the intentionally ignored values in the following code: hello_to := []int{1, 2, 3, 4, 5, 6} for count, _ := range hello_to { fmt.Printf("%v: Hello!n", count) } Would get converted to the following after running –s: hello_to := []int{1, 2, 3, 4, 5, 6} for count, _ := range hello_to { fmt.Printf("%v: Hello!n", count) } The awesomeness of go get One of the really cool features of the go command is that go get it works seamlessly with code hosted on GitHub as well as repositories hosted elsewhere. A note of warning Make sure that $GOPATH is properly set (this is usually exported as a variable in your shell). You may have a line such as “export GOPATH=$HOME” in your shell's profile file. Nabbing a library off of GitHub Say, we see this really neat library we want to use called fastHttp. Using only the go tool, we can fetch the library and get it ready for use all with just: go get github.com/valyala/fasthttp Now, all we have to do is import it with the exact same path, and we can start using the library right away! Just type this and it should do the trick: import "github.com/valyala/fasthttp" In the event that you want to have a look around in the library you just downloaded with go get, just type cd into $GOPATH/src/[Path that was provided to get command]—in this case, $GOPATH/src/github.com/valyala/fasthttp—and feel free to inspect the source files. I am also happy to inform you that you can also use go doc with the libraries you download in the exact same way as you use go doc when interacting with the standard library! Try it: type go doc fasthttp (you might want to tack on less since its a little bit long to type go doc fasthttp | less). Those are only stock features and options! The go tool is great and gets the job done, but there are also other great alternatives to some of the go tool's features, such as the godep package manager. If you have some time, I think it’s worth the time investment to learn! About the author Nick Maccharoli is an iOS/backend developer and an open source enthusiast working at a start-up in Tokyo and enjoying the current development scene. You can see what he is up to at @din0sr or github.com/nirma.
Read more
  • 0
  • 0
  • 3527

article-image-year-python
Sam Wood
04 Jan 2016
4 min read
Save for later

The Year of the Python

Sam Wood
04 Jan 2016
4 min read
When we asked developers for our $5 Skill Up report what the most valuable skill was in 2015, do you know what they said? Considering the title of this blog and the big snake image, you can probably guess. Python. Python was the most valuable skill they learned in 2015. But 2015 is over - so what did developers say they're hoping to learn from scratch, or increase their skills in in 2016? Correct guess again! It's Python. Despite turning 26 this Christmas (it's the same age as Taylor Swift, you know), the language is thriving. Set to be the most widely adopted new language for two years running is impressive. So why are people flocking to it? Why are we living in the years of the Python? There are three main reasons. 1. It's being learned by non-developers In the Skill Up survey, the people who were most likely to mention Python as a valuable skill that they learned also did not tend to describe themselves as traditional software developers. The job role most likely to be learning Python were 'Academics', followed by analysts, engineers, and people in a non-IT related role. These aren't the people who live to code - but they are the people who are likely finding the ability to program an increasingly useful professional skill. Rather than working with software every day, they are using Python to perform specific and sophisticated tasks. Much like knowledge of working in Microsoft became the essential office skill of the Nineties/Noughties, it looks like Python is becoming the language of choice for those who know they need to be able to code but don't necessarily define themselves as solely working in dev or IT. 2. It's easy to pick up I don't code. When I talked to my friends who did code, mumbling about maybe learning and looking for suggestions, they told me to learn Python. One of their principal reasons was because it was so bloody easy! This also ties in heavily to why we see Python being adopted by non-developers. Often being learned as a first programming language, the speed and ease with which you can pick up Python is a boon - even with minimal prior exposure to programming concepts. With much less of an emphasis on syntax, there's less chance of tripping up with missing parentheses or semicolons than with more complex languages. Originally designed (and still widely used) as a scripting language, Python has become extremely effective for writing standalone programs. The shorter learning curve means that new users will find themselves creating functioning and meaningful programs in a much shorter period of time than with, say, C or Java. 3. It's a good all-rounder Python can do a ton. From app development, to building games, to its dominance of data analysis, to its continued colonization of JavaScript's sovereign territory of web development through frameworks like Django and Flask, it's a great language for anyone who wants to learn something non-specialized. This isn't to say it's a Jack of All Trades, Master of None, however. Python is one of the key languages of scientific computing, aided by fast (and C-based) libraries like NumPy. Indeed, the strength of Python's versatility is the power of its many libraries to allow it to specialize so effectively. Welcoming Our New Python Overlords Python is the double threat - used across the programming world by experienced and dedicated developers, and extensively and heartily recommended as the first language for people to pick up when they start working with software and coding. By combining ease-of-entry with effectiveness, it's come to stand as the most valuable tech skill to learn for the middle of the decade. How many years of the Python do you think lie ahead?
Read more
  • 0
  • 0
  • 1593
article-image-python-web-development-frameworks-django-flask
Owen Roberts
22 Dec 2015
5 min read
Save for later

Python Web Development Frameworks: Django or Flask?

Owen Roberts
22 Dec 2015
5 min read
I love Python, I’ve been using it close to three years now after a friend gave me a Raspberry Pi they had grown bored with. In the last year I’ve also started to seriously get into web development for my own personal projects but juggling all these different languages can sometimes get a bit too much for me; so this New Year I’ve promised myself I’m going to get into the world of Python web development. Python web dev has exploded in the last year. Django has been around for a decade now, but with long term support and the wealth of improvements that we’ve seen to the framework in just the last year it’s really reaching new heights of popularity. Not only Django, but Flask’s rise to fame has meant that writing a web page doesn’t have to involve reams and reams of code too! Both these frameworks are about cutting down on time spent coding without sacrificing quality, but which one do you go for? In this blog I’m going to show you the best bundles you need to get started with taking Python to the world of the web with titles I've been recommended - and at only $5 per eBook, hopefully this little hamper list inspires you to give something new a try for 2016! So, first of all which do you start with, Django or Flask? Let’s have a look at each and see what they can do for you. Route #1: Django So the first route to enter the world of Python web dev is Django, also touted as “the web framework for perfectionists with deadlines”. Django is all about clean, pragmatic design and getting to your finished app in as little time as possible. Having been around the longest it's also got a great amount of support meaning it's perfect for larger, more professional projects. The best way to get started is with our Django By Example or Learning Django Web Development titles. Both have everything you need to take the first steps in the world of web development in Python; taking what you already know and applying it in new ways. The By Example title is great as it works through 4 different applications to see how Django works in different situations, while the Learning title is a great supplement to learning the key features that need to be used in every application. Now that the groundwork has been laid, we need to build upon that. With Django we've got to catch up with 10 years of experience and community secrets fast! Django Design Patterns and Best Practices is filled with some of the community's best hacks and cheats to get the most out of developing Django, so if you're a developer who likes to save time and avoid mistakes (and who doesn't?!) then this book is the perfect desk companion for any Django lover. Finally, to top everything off and prepare us for the next steps in the world of Django why not try a new paradigm with Test-Driven Development with Django? I'm honestly one of those developers that hates having to test right at the end, so being able to peel down a complex critical task into layers throughout just makes more sense to me. Route #2: Flask Flask has exploded in popularity in the last year and it's not hard to see why – with the focus on as much minimal code as possible, Python is perfect for developers who are looking to get a quick web page up, as well as those who just hate having to write mountains of code when a single line can do. As an added bonus the creators of the framework looked at Django and took on board feedback from that community as well, so you get the combined force of two different frameworks at your fingertips. Flask is easy to pick up, but difficult to master, so having a good selection of titles to help you along is the best way to get involved in this new world of Python web dev. Learning Flask Framework is the logical first step for getting into Flask. Released last month it's come heartily recommended as the all-in-one first stop to getting the most out of Flask. Want to try a different way to learn though? Well, Learning Flask video is a great supplement to the learning title, it shows us everything we need to start building our first Flask titles in just under 2 hours – almost as quick as it takes the average Flask developer to build their own sites. The Flask Framework Cookbook is the next logical step as a desktop companion for someone just starting their own projects. Having over 80 different recipes to get the most out of the framework is essential for those dipping their feet into this new world without worrying about losing everything. Finally, Flask Blueprints is something a little different, and is especially good for getting the most out of Flask. Now, if you're serious about learning Flask you're likely to get everything you need quickly, but the great thing about the framework is how you apply it. The different projects inside this title make sure you can make the most out of Flask's best features for every project you might come across! Want to explore more Python? Take a look at our dedicated Python page. You'll find our latest titles, as well as even more free content.
Read more
  • 0
  • 0
  • 3602

article-image-modern-go-development
Xavier Bruhiere
06 Nov 2015
8 min read
Save for later

Modern Go Development

Xavier Bruhiere
06 Nov 2015
8 min read
  The Go language indisputably generates lot of discussions. Bjarne Stroustrup famously said: There are only two kinds of languages: the ones people complain about and the ones nobody uses. Many developers indeed share their usage retrospectives and the flaws they came to hate. No generics, no official tool for vendoring, built-in methods break the rules Go creators want us to endorse. The language ships with a bunch of principals and a strong philosophy. Yet, The Go Gopher is making its way through companies. AWS is releasing its Go SDK, Hashicorp's tools are written in Go, and so are serious databases like InfluxDB or Cockroach. The language doesn't fit everywhere, but its concurrency model, its cross-platform binary format, or its lightning speed are powerful features. For the curious reader, Texlution digs deeper on Why Golang is doomed to succeed. It is also intended to be simple. However, one should gain a clear understanding of the language's conventions and data structures before producing efficient code. In this post, we will carefully setup a Go project to introduce a robust starting point for further development. Tooling Let's kickoff the work with some standard Go project layout. New toys in town try to rethink the way they are organized, but I like to keep things simple as long as it just works. Assuming familiarity with the Go installation and GOPATH mess, we can focus on the code's root directory. ➜ code tree -L 2 . ├── CONTRIBUTING.md ├── CHANGELOG.md ├── Gomfile ├── LICENCE ├── main.go ├── main_test.go ├── Makefile ├── shippable.yml ├── README.md ├── _bin │   ├── gocov │   ├── golint │   ├── gom │   └── gopm └── _vendor    ├── bin    ├── pkg    └── src To begin with, README.md, LICENCE and CONTRIBUTING.md are usual important documents for any code expected to be shared or used. Especially with open source, we should care about and clearly state what the project does, how it works and how one can (and cannot) use it. Writing a Changelog is also a smart step in that direction. Package manager The package manager is certainly a huge matter of discussion among developers. The community was left to build upon the go get tool and many solutions arisen to bring deterministic builds to Go code. While most of them are good enough tools, Godep is the most widely used, but Gom is my personal favorite: Simplicity with explicit declaration and tags # Gomfile gom 'github.com/gin-gonic/gin', :commit => '1a7ab6e4d5fdc72d6df30ef562102ae6e0d18518' gom 'github.com/ogier/pflag', :commit => '2e6f5f3f0c40ab9cb459742296f6a2aaab1fd5dc' Dependency groups # Gomfile (continuation) group :test do # testing libraries gom 'github.com/franela/goblin', :commit => 'd65fe1fe6c54572d261d9a4758b6a18d054c0a2b' gom 'github.com/onsi/gomega', :commit => 'd6c945f9fdbf6cad99e85b0feff591caa268e0db' gom 'github.com/drewolson/testflight', :commit => '20e3ff4aa0f667e16847af315343faa39194274a' # testing tools gom 'golang.org/x/tools/cmd/cover' gom 'github.com/axw/gocov', :commit => '3b045e0eb61013ff134e6752184febc47d119f3a' gom 'github.com/mattn/goveralls', :commit => '263d30e59af990c5f3316aa3befde265d0d43070' gom 'github.com/golang/lint/golint', :commit => '22a5e1f457a119ccb8fdca5bf521fe41529ed005' gom 'golang.org/x/tools/cmd/vet' end Self-contained project # install gom binary go get github.com/mattn/gom # ... write Gomfile ... # install production and development dependencies in `./_vendor` gom -test install We just declared and bundled full requirements under its root directory. This approach plays nicely with trendy containers. # we don't even need Go to be installed # install tooling in ./_bin mkdir _bin && export PATH=$PATH:$PWD/_bin docker run --rm -it --volume $PWD/_bin:/go/bin golang go get -u -t github.com/mattn/gom # asssuming the same Gomfile as above docker run --rm -it --volume $PWD/_bin:/go/bin --volume $PWD:/app -w /app golang gom -test install An application can quickly rely on a significant number of external resources. Dependency managers like Gom offers a simple workflow to avoid breaking-change pitfalls - a widespread curse in our fast paced industry. Helpers The ambitious developer in love with productivity can complete its toolbox with powerful editor settings, an automatic fix, a Go repl, a debugger, and so on. Despite being young, the language comes with a growing set of tools helping developers to produce healthy codebase. Code With basic foundations in place, let's develop a micro server powered by Gin, an impressive web framework I had great experience with. The code below highlights commonly best practices one can use as a starter. // {{ Licence informations }} // {{ build tags }} // Package {{ pkg }} does ... // // More specifically it ... package main import ( // built-in packages "log" "net/http" // third-party packages "github.com/gin-gonic/gin" flag "github.com/ogier/pflag" // project packages placeholder ) // Options stores cli flags type Options struct { // Addr is the server's binding address Addr string } // Hello greets incoming requests // Because exported identifiers appear in godoc, they should be documented correctly func Hello(c *gin.Context) { // follow HTTP REST good practices with an adequate http code and json-formatted response c.JSON(http.StatusOK, gin.H{ "hello": "world" }) } // Handler maps endpoints with callbacks func Handler() *gin.Engine { // gin default instance provides logging and crashing recovery middlewares router := gin.Default() router.GET("/greeting", Hello) return router } func main() { // parse command line flags opts := Options{} flag.StringVar(&opts.Addr, "addr", ":8000", "server address") flag.Parse() if err := Handler().Run(opts.Addr); err != nil { // exit with a message and a code status 1 on errors log.Fatalf("error running server: %vn", err) } } We're going to take a closer look at two important parts this snippet is missing : error handling and interfaces' benefits. Errors One tool we could have mentioned above is errcheck, which checks that you checked errors. While it sometimes produces cluttered code, Go error handling strategy enforces rigorous development : When justified, use errors.New("message") to provide a helpful output. If one needs custom arguments to produce a sophisticated message, use fmt.Errorf("math: square root of negative number %g", f) For even more specific errors, let's create new ones: type CustomError struct { arg int prob string } // Usage: return -1, &CustomError{arg, "can't work with it"} func (e *CustomError) Error() string { return fmt.Sprintf("%d - %s", e.arg, e.prob) } Interfaces Interfaces in Go unlock many patterns. In the gold age of components, we can leverage them for API composition and proper testing. The following example defines a Project structure with a Database attribute. type Database interface { Write(string, string) error Read(string) (string, error) } type Project Structure { db Database } func main() { db := backend.MySQL() project := &Project{ db: db } } Project doesn't care of the underlying implementation of the db object it receives, as long as this object implements Database interface (i.e. implements read and write signatures). Meaning, given a clear contract between components, one can switch Mysql and Postgre backends without modifying the parent object. Apart from this separation of concern, we can mock a Database and inject it to avoid heavy integration tests. Hopefully this tiny, carefully written snippet should not hide too much horrors and we're going to build it with confidence. Build We didn't join a Test Driven Development style but let's catch up with some unit tests. Go provides a full-featured testing package but we are going to level up the game thanks to a complementary combo. Goblin is a thin framework featuring Behavior-driven development close to the awesome Mocha for node.js. It also features an integration with Gomega, which brings us fluent assertions. Finally testflight takes care of managing the HTTP server for pseudo-integration tests. // main_test.go package main import ( "testing" . "github.com/franela/goblin" . "github.com/onsi/gomega" "github.com/drewolson/testflight" ) func TestServer(t *testing.T) { g := Goblin(t) //special hook for gomega RegisterFailHandler(func(m string, _ ...int) { g.Fail(m) }) g.Describe("ping handler", func() { g.It("should return ok status", func() { testflight.WithServer(Handler(), func( r*testflight.Requester) { res := r.Get("/greeting") Expect(res.StatusCode).To(Equal(200)) }) }) }) } This combination allows readable tests to produce readable output. Given the crowd of developers who scan tests to understand new code, we added an interesting value to the project. It would certainly attract even more kudos with a green test-suite. The following pipeline of commands try to validate a clean, bug-free, code smell-free, future-proof and coffee-maker code. # lint the whole project package golint ./... # run tests and produce a cover report gom test -covermode=count -coverprofile=c.out # make this report human-readable gocov convert c.out | gocov report # push the reslut to https://coveralls.io/ goveralls -coverprofile=c.out -repotoken=$TOKEN Conclusion Countless posts conclude this way, but I'm excited to state that we merely scratched the surface of proper Go coding. The language exposes flexible primitives and unique characteristics one will learn the hard way one experimentation after another. Being able to trade a single binary against a package repository address is such an example, like JavaScript support. This article introduced methods to kick-start Go projects, manage dependencies, organize code, offered guidelines and testing suite. Tweak this opinionated guide to your personal taste, and remember to write simple, testable code. About the author Xavier Bruhiere is the CEO of Hive Tech. He contributes to many community projects, including Occulus Rift, Myo, Docker and Leap Motion. In his spare time he enjoys playing tennis, the violin and the guitar. You can reach him at @XavierBruhiere.
Read more
  • 0
  • 0
  • 2947