Application Programming Archives - Stackify Wed, 27 Mar 2024 10:07:47 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.4 https://stackify.com/wp-content/uploads/2023/02/favicon.png Application Programming Archives - Stackify 32 32 Picking The Right Programming Language for Your Application https://stackify.com/picking-the-right-programming-language-for-your-application/ Tue, 06 Dec 2022 13:01:29 +0000 https://stackify.com/?p=36089 Programming languages are a critical aspect of the application development process. The language is what allows you to instruct the technology in a way the computer understands. However, choosing the right programming language for your application is often a big dilemma. 

There are a lot of programming languages to choose from, like JavaScript, C++ and PHP, to name just a few. There are several other factors as well, such as security and maintainability, which must be considered.

As a result, the choice is difficult, especially for those who have little coding experience. With that in mind, let’s go through some tips to help you choose the right programming language for your application. 

Think of these steps as the SMART approach to choosing the right programming language for your application

1. Type of Application

The first thing to consider is the type of application you are creating. Are you creating a web app or a mobile application? Is it a desktop application or a business application? These are the questions to answer first, because some programming languages work best with certain types of apps.

For example, the C++ programming language is critical for embedded firmware, while Java is essential for an Android mobile app. Researching the programming language best suited to your specific app type will get you started in the right direction.

You should also consider the size and complexity of your app. PHP and C# can be used for small app projects like simple web apps. Java is a general-purpose programming language suitable for more complex, medium-sized apps that include layers, such as e-commerce functions.

For larger projects with multiple, complex layers, the best course of action is to break the project down into smaller components. These apps are too complex to be built with one technology stack. Using a specific programming language for each part of the project ensures that each individual component is built with the programming language best suited to that component.

2. Identify Your Platform

The platform your app will be running on is another important consideration in choosing the right programming language for your application. It’s always best to establish your platform as early as possible during the initial planning process for creating your app.

You can think of this piece like you’re choosing a platform for a social media campaign. When choosing Instagram, you must create content specifically for that platform to engage your audience and attract more Instagram followers.

Similarly, the chosen platform for your app has a big impact on your choice of programming language. This is because different platforms are more compatible with specific programming languages.

Let’s look closely at the platforms and what coding works best for each. For web apps, JavaScript and PHP are the most compatible programming languages. The chart below from a 2021 Stack Overflow survey shows that JavaScript is the most popular programming language among developers. This is because it is particularly effective for web apps, as it is already embedded in all web browsers.

Java or C++ are the preferred languages for Android apps on mobile devices. Java is one of the core languages of Android app development, and all apps on the platform require some knowledge of Java, so it is probably the best choice.

Finally, for Apple applications, the most popular language is Objective-C. Although this language is limited to Apple products, it is still considered the best option in the developer community. A more versatile option will be required if you want to develop your app to function across multiple platforms. Languages like Python, C++ and Java are more dynamic languages as they can be used effectively for cross-platform apps.

3. Maintainability

When choosing a programming language, it is also essential to consider the long-term maintainability of your app. The language you pick must be up to date with current programming technology. You’ll also want your app to stay current for a long time, so you shouldn’t pick any language that is falling out of favor for any reason.

Technology and coding are constantly evolving, so long-term maintainability is key when choosing a language. No matter how much you plan for the future, apps will always need to be updated. So, you’ll want to choose a programming language that can handle updates well.

Using outdated languages can lead to high maintenance costs, as you will struggle to keep up with new developments in coding. In some cases, you may have to start from scratch a second time if your chosen language becomes completely outdated. 

Of course, this is unlikely to happen unless you completely disregard maintainability and technological developments. However, it does highlight the importance of long-term planning in app development.

For example, if you are creating a web app, you should consider the possibility that you may want to create a mobile app in the future. In that case, you should consider using a flexible language like Python that is compatible across multiple platforms. Long-term planning like this can save you a lot of money in the long run.

Moreover, you may want to consider the need to hire other developers in the future. Will you be able to get developers for the specific language you used to build the application 10 years from now? How much is that going to cost?

If you build an application using a popular language, you’ll likely spend less now, and on long-term maintainability in the future.

4. Scalability, Performance and Security

Similarly, you must also consider scalability. As with any project, the plan with an app is to grow and become more popular. So, if all goes as planned, your app will attract more and more users over time. As this happens, your app and chosen programming language will have to handle increasing amounts of data.

Choosing a language with great scalability will prepare your app for success. Ruby on Rails and Java Spring are the two stacks that perform best in terms of scalability.

As well as scalability, general app performance should also be a primary consideration. A poor choice of programming can lead to problems with image processing or page loading, which can be very frustrating for users.

To avoid this, use real-time code profiling to reduce troubleshooting and optimize app performance. This software provides instant feedback on your code quality in a clean interface, as shown below, allowing you to solve issues quickly.

Finally, you must protect your app and users from cyber threats. While the measures you take to secure your app vary by industry, a single security breach can kill your app. In addition, many industries have very strict security requirements. Healthcare applications, for example, must comply with HIPAA, while a financial application must have PCI compliance.

Security is of significant importance whatever kind of app you create, and the programming language you use plays a vital role in protecting user data. So always keep an eye out for security updates for your chosen programming language.

In Closing

Choosing the right programming language for your application is essential for any successful app. A poor choice  can lead to general performance, poor loading speeds or worse – problems with data security.

To avoid such problems, start by considering the type of app you are creating and match it with an appropriate programming language. Identifying your platform is critical; Objective-C is better suited to Apple apps, while Android apps work better with JavaScript or C++.

You should also consider the ability of your programming language to maintain performance as your app grows and becomes more complex. Finally, prioritize performance in areas such as loading speed and security. Start by following these steps, and you’ll arrive at the right choice of programming language for your application.

]]>
Top 7 In-Demand Programming Languages https://stackify.com/top-7-in-demand-programming-languages/ Tue, 27 Sep 2022 14:20:42 +0000 https://stackify.com/?p=35893 Hundreds of programming languages exist, each with its applications and capabilities. Whether their first language or a skill expansion, programmers must be strategic and discerning when deciding which ones to learn. Today, we plan to guide you in the right direction by sharing the seven most in-demand programming languages to learn.

What Is a Programming Language?

In a nutshell, a programming language is an artificial language that can be used to instruct digital devices to behave a certain way. Like human languages, each programming language has its vocabulary, syntax and other linguistic rules.

We can associate programming with both hardware and software. However, the rise in popularity of programming languages is due mainly to their applications in web or mobile platforms and data science. Experts predict that this meteoric rise will continue as our world further digitizes.

Top 7 at a Glance

It is never too late to get into a promising programming career. Seven of the most popular programming languages below have been handpicked for their growing number of their users and application support.

The Best In-Demand Programming Languages

1. JavaScript

If you’re looking for a popular language to learn, JavaScript should probably come first. JavaScript remains one of the most-used programming languages, even  30 years after its first development. In fact, according to Web Technology Surveys, as many as 98% of all websites currently utilize a form of JavaScript-based client-side web application development.

Another statistical report found that JavaScript skills are highly sought by hiring managers in the U.S. and worldwide. Better still, the average yearly salary of a Javascript developer is around $100,000 in the U.S.

Aside from salary and job opportunities, JavaScript is considered fairly easy to learn. Its various applications give you a solid background in programming languages in general, even without prior coding knowledge. The language has widely accessible on-line communities and learning resources with some available for free!

JavaScript is commonly used for websites, web servers, dynamic web applications, mobile applications and games. While not always considered among the top, most powerful programming languages, JavaScript continues to evolve and provide additional programming functionality.

The biggest weaknesses coders face with JavaScript is that its source code can be viewable to its users. This can put client-side security at risk. Another pain point is that JavaScript only supports single and not multiple inheritances. Older browsers can also find it challenging to support the language’s latest features or functions.

Pros:

  • Ideal for websites, web servers, interactive and dynamic web applications, mobile apps and games
  • Easy to learn even with no previous coding experience
  • Packs a lot of features and versatility
  • Used by premium platforms, apps and games such as Facebook, Netflix and Angry Birds

Cons:

  • Needs extra attention when it comes to ensuring client-side security

2. Python

Python also sits atop of the list of most popular programming languages. In fact, according to the Popularity of Programming Language Index, Python occupies the top spot. The list is based on how many programming language tutorials are searched on Google. By comparison, JavaScript ranks third on the list.

Python also has a rich history, having been developed in 1991. Amidst hundreds of more modern languages, Python remains in high demand, elegantly combining simplicity with incredibly complex capabilities.

An open-source, higher-level language, Python has a syntax that closely mimics English. Thus, it is easy to understand even for beginners with no previous background in programming languages. But do not underestimate Python’s functions and capabilities. It can be used for leveraging artificial intelligence and machine learning, particularly in developing deep-learning applications.

Various Python GUI frameworks help mobile application developers make it work natively on iOS and Android.  Hence, even if it’s an interpreter-type language with many object-oriented and interactive qualities that digital devices don’t usually run, you’ll still be able to integrate it seamlessly.

In terms of salary, an entry-level Python programmer makes around $80,000 annually. Meanwhile, a yearly salary for a more experienced programmer can go up to $172,500.

As for its flaws, there are usually two main concerns. First, Python is notably slower compared to other programming languages. Second, it is known to consume a lot of memory. Hence, memory management can be a concern if you’re developing something that requires memory optimization.

Pros:

  • Ideal for website development, AI, machine learning and big data
  • Relatively easy to learn
  • Open-source with a very supportive community
  • Used by premium platforms such as Reddit, Pinterest and Instagram

Cons:

  • Requires a GUI framework for mobile application development
  • Has less speed compared to others
  • Takes up a lot of memory

3.  HTML

There’s an ongoing debate on whether HyperText Markup Language, or HTML, is a programming language or not. The same applies to Cascading Style Sheets, or CSS. Many point out that its label as a “markup language” proves it’s not a programming language. On the other hand, sources like UC Berkeley recognize it as one.

For this line-up, we define HTML as a general-purpose programming language typically used to format how information is displayed on a website. Indeed, it differs from the more powerful programming languages that most budding software developers expect. It’s a bit feature-anemic. Still, it’s one of the most beloved and popular languages that even non-coders often use.

HTML is not a very demanding language to learn, but it can still give HTML developers annual average salaries ranging from $65,000 to $100,000.

Pros:

  • Great for website development, website maintenance and mobile apps
  • Not a demanding language to learn
  • Used as a building block for 90% of all websites

Con:

  • A bit feature anemic

4. Ruby

Ruby was originally released to the public in 1995, but it didn’t turn into a much-loved programming language until 2006. Today, it is one of the most in-demand languages around the world. An open-source language, Ruby is constantly growing and developing and supported by a vibrant community of dedicated coders.

This programming language is highly portable, versatile and widely used for back-end development – web server creation, web scraping, automation and data processing. However, Ruby can be used for front-end development, much like the other mainstream programming languages. For instance, the language is commonly used for web and mobile app development.

In terms of salary, Ruby programmers get decent pay. Their average yearly salary can range between $35,000 and $138,000. Meanwhile, the annual salaries of more experienced coders can go as high as $175,000. No wonder so many budding coders choose it as their primary programming language.

You should be aware of a few cons to using Ruby.

First, it’s not suitable for deep learning. It might not prove helpful for those looking for a machine language learning solution, either. Finally, its flexibility can make it difficult to debug.

Pros:

  • Useful for both back-end and front-end development
  • Often used for websites and mobile app development
  • Open-source with a very supportive community
  • Used by premium platforms such as Airbnb, Basecamp, GitHub and SoundCloud

Cons:

  • Can’t be used to code AI and machine learning apps
  • Can be difficult to debug

5. SQL

SQL – Structured Query Language – is our next language on the list. It’s a powerful, higher-level language designed to access, use and manipulate databases. With SQL, you can address every aspect of database operations, from retrieving new data, creating and updating records, and even setting permissions. However, SQL will require a translator to make it functional for a low-level operating system.

Those planning to start a career in programming with SQL as their primary programming language can expect a salary between $30,000 and $120,000.

Be warned, though. It’s a complicated programming language to navigate through. Since it’s not an open-source language, some of its versions can be quite costly too.

Pros:

  • Mainly used for accessing, using and manipulating databases
  • Useful for business intelligence and business management tools
  • Easily handles large volumes of data
  • Used by companies such as Accenture, Microsoft and LinkedIn for data analysis and management

Cons:

  • Will require a translator for low-level operating systems
  • A more complicated programming language compared to others
  • Can be a bit expensive

6. PHP

PHP, which stands for Hypertext Preprocessor, is an open-source language much like other mainstream programming languages featured in this line-up. It has an extensive library of assets and resources courtesy of a supportive online community of developers.

PHP is typically used to develop web servers and embedded systems within HTML. Aside from that, this language can be used for deep learning and machine learning, web and mobile app development and other complex projects … as long as you use the right libraries!

Some programmers prefer PHP over JavaScript due to its added data encryption. PHP can execute applications on a server, generate HTML and deliver its functions to the client without the need to reveal its underlying code.

Unfortunately, despite its varied functions and applications, PHP is sometimes regarded as the lowest-paid fully-fledged programming language. That’s reflected in the low, average salary of experienced PHP programmers, which may not exceed $40,000.

Pros:

  • Great for web server development, web and mobile application development, machine learning and data encryption
  • Open-source with a very supportive community
  • Can run on various platforms and operating systems
  • Used by premium platforms such as Wikipedia, Slack, Flickr and Lyft

Con:

  • Annual salaries of experienced programmers are disproportionately low

7. C

Finally, we simply can’t end the list without featuring the king of hyped languages. Having been developed in 1972, C has the longest history and staying power among the mainstream programming languages in our list. This is because C is a powerful and excellent language you can use for almost anything. It can create operating systems, dynamic web applications, mobile platforms and various types of applications. 

While it’s not necessarily a machine language, C can still be used to implement machine learning algorithms. With its support of business applications, it’s no surprise how in-demand C continues to be.

The yearly salary of a C programmer is pretty impressive as well, ranging from a low $17,000 to a staggering $400,000 (sometimes even more!).

However, even C isn’t perfect. It still has a couple of disadvantages. First, it can be a complicated language to learn. However, a background in coding will help with the learning curve. Second, debugging in C can be a pain, since there’s no way to check for errors for each line of code. In addition, it lacks exception handling, which further complicates catching anomalies within your code.

Pros:

  • Ideal for developing operating systems, web and mobile applications and different types of applications
  • Considered one of the highest-paying programming languages
  • Has an expansive range of functionalities
  • Used by the biggest tech companies, such as Microsoft, Mac and Linux

Cons:

  • Challenging to learn, especially for beginners
  • Weak error management features

Which Programming Language Will be in High Demand in the Future?

There are several reasons any budding programmer should consider learning JavaScript. However, don’t neglect to consider other factors. There is a considerable possibility we didn’t feature the programming language that best suits the apps you want to develop.

Erlang, for instance, is an excellent language for developing communication apps. Meanwhile, Flowgorithm is a free language for anyone who wants to code a flowchart maker. The fact is, you’ll never see every language featured on a “top list” because there are simply too many!

Staying On Top of Your Programming Game

It’s never too late nor too early to jumpstart your career as a programmer. By learning any programming languages listed above, you’ll prepare yourself to land one of those high-paying programmer positions you’re shooting for. Good luck!

]]>
When a .NET Core Azure App Service won’t start: 502.5 Process Failure https://stackify.com/net-core-azure-app-service-wont-start/ Tue, 15 Nov 2016 12:02:47 +0000 https://stackify.com/?p=6489 In the process of testing Retrace with .NET Core I decided to use the example MusicStore app as a test application. Pulling down the source from GitHub and deploying it to Azure App Services is easy right? Correct, and totally wrong both as it turns out. After hours of headaches… I figured I needed to share how I finally solved my issue with the dreaded HTTP Error 502.5 – Process Failure.

So what exactly was my problem?

I deployed my app as an Azure App Service targeting the full .NET framework and immediately got hit with this error:

HTTP Error 502.5 – Process Failure

At first glance this error pretty much doesn’t make any sense. Why in the world would my web app not start up? I tested it locally and it worked perfectly. I deploy to Azure and I get a bizarre “HTTP Error 502.5 – Process Failure” error.

OK, so I decided to switch my target framework from full framework .NET 451 to netcoreapp. Now I get this instead…

azure-core-500

At this point I started wonder if Azure doesn’t support the version of .NET Core I am using, or if I need to upgrade to 1.0.1 or something. I tried changing all my dependencies around and lots of other things. Nothing worked.

Let’s stop and remember how .NET Core works

It is important to remember that .NET Core works completely differently than previous versions of .NET. Normally we expect that if IIS is running, our app will work, or at least try to work and throw a 500 error, weird config error messages, or something.

.NET Core doesn’t work like that. We are still using IIS, but it starts our application up as a child process that is running Kestrel. IIS is now a reverse proxy and it tries to ensure our app is running.

child-process

It looks at our web.config which now just tells it how to start our app. It also uses a special AspNetCoreModule to pass the traffic through. Your web.config looks something like this:

<system.webServer>
	<handlers>
		<add name=”aspNetCore” path=”*” verb=”*” modules=”AspNetCoreModule” resourceType=”Unspecified” />
	</handlers>
	<aspNetCore processPath=”%LAUNCHER_PATH%” arguments=”%LAUNCHER_ARGS%” stdoutLogEnabled=”false” 
	    stdoutLogFile=”.\logs\stdout” forwardWindowsAuthToken=”false” />
</system.webServer>

So when IIS tries to start your app as a child process and it throws an error… your app literally is not running. That is what is happening on Azure and the 502.5 Process Failure app is absolutely correct.

OK, So how do we figure out why my app will not start?

This is what took me forever to figure out because Azure doesn’t tell you anything and you have no idea where to start even troubleshooting. The answer is actually really simple once you find the config setting needle in the haystack. In the example web.config above I posted what the default config is. What you need to do is enable “stdoutLogEnabled” so it will essentially log to a text file what is being displayed in the console window.

BTW, the default path for stdoutLogFile is “.\logs\stdout”, but when I did my deployment to Azure, the publish process changed it to “\\?\%home%\LogFiles\stdout” which does work in Azure and maps to D:\Home\LogFiles.

So all you need to do is redeploy your app with stdoutLogEnabled=true or go edit it your web.config via KUDU and restart your app. Then you will see files created in KUDU and this will help you find any exceptions that may be happening when the app starts up. For me, It ended up being a bad database connection string. 🙁

kudu-view

Good luck and I hope this helps save some people from the headaches I had trying to figure this out! I wish Azure somehow automatically collected part of stdout much like it does for WebJob logs. Also check out this blog post: Where to Find Azure App Service Logs for your App, IIS, FRT, etc

 

]]>
Alleviate Rush Hour Traffic in your Browser https://stackify.com/alleviate-rush-hour-traffic-in-your-browser/ Mon, 27 Jun 2016 13:02:16 +0000 https://stackify.com/how-to-partition-tables-in-azure-sql-2/ Every morning I get up early, get on the highway and drive into work. There may be a little snag through the Grandview triangle (it’s kind of like KC’s version of the Bermuda Triangle), but it’s usually just a 20 minute drive if I leave at 7:00 a.m. After 7:30 a.m., that drive turns into an hour as fours times the commuters enter the triangle. Now, if there is an accident? Well, I’ll hope to see the office around lunch.

I shouldn’t complain. I have it EASY compared to other commuters (LA, Atlanta, Chicago—I don’t even want to know)!

Every browser is kind of like the Grandview triangle. It works well until something creates a snag. The higher the volume, the worse the bottleneck.

Stackify is a data company. We have lots of it, and all that data changes at a rapid pace. The nature of what we offer demands both large amounts of aggregate data and detail data available at your fingertips, often in the same “page” of information. If you combine lots of data with high rate of data change, guess what…you’ve just turned your browser into rush hour on the Grandview triangle.

How do you keep things flowing and reduce snags? How do you keep performance up?

Like the highway, some of our data flows in haphazardly and in large, fast bursts of information. Our monitoring pages show lists of monitors whose statuses and values can change quickly. These monitors, when updated cause animations and DOM manipulation. The browser has no control over when these updates are transmitted, and may receive updates for the same monitors milliseconds apart.

There are two main performance problems that we had to deal with for these monitors.

1. The DOM

As any UI guy will tell you, changing the DOM can cause a lot of CPU cycles to be spent painting the page on the screen. There are many solutions to handling this volume of data from a DOM perspective. React.js is designed to handle the issues of DOM thrashing internally, but if you’re using something like Knockout.js (like we do) you have to handle DOM thrashing manually.

One solution that Knockout.js offers natively is the “throttle” extension. What this does is separate the changing of the observable from its dependencies taking action on the change. So if you throttle the the observable for one second, you can make as many changes to the observable’s value as you want and the dependencies will only act on that change once every second. The throttle extension uses a setTimeout call internally to handle this functionality.

The throttle extension was the wrong decision for us to monitor pages with. While it dramatically reduced the amount of DOM thrashing that could occur, it raised up a different problem: setTimeout was resource expensive. Overzealous use of the throttle created many setTimeout instances and those ate memory and CPU cycles quickly. We limit use of throttle to direct UI user changes, i.e. changing a search filter or clicking a toggle.

While throttle was the right direction, doing it piecemeal was too expensive. This led to using a static interval. An interval allows us to marshal the accumulation of changes to the monitor entity, only updating the DOM at a set timing and only for those entities that actually did change. The DOM can now change at a measured and predictable pace for the entire set of entities, rather than thrashing as individual entities are changing. We also found that absolute real time updates don’t add any additional user experience benefit over a relatively fast interval update.

2. Identifying the Entity to Update

The monitors that are updated are sorted, but not in a linear fashion. The ID of the monitor does not correspond at all to an order on the page. We also receive the data haphazardly, so seek performance in the javascript is paramount. Choosing the correct approach to find the entity to update is very important to avoid unnecessary CPU cycles.

If you have a small array, using a simple linear search with find or findIndex might be performant enough. But, when you get into medium, large and really large arrays, find will perform poorly. If you have a large array or you’re doing many find operations, stay far away from a linear search. For the case of the monitors, find was like a rolling roadblock—it brought everything to a halt regardless of the time of day.

If the array you are seeking against is sorted linear in some way then generally a binary search provides the best performance. Binary searches are very fast and if you can use one, do so. In the case of the monitors, the entities were not sorted in a linear fashion and the ID’s of the entities did not correspond to an easy or contiguous index position. We would have loved to use this search but it wasn’t in the cards.

Since the data doesn’t work well with a linear or binary search, we chose a Dictionary approach. Using the ID of the entity you can create a key (e.g. “key_1”) that is predictable, repeatable and simple. Then an index operation can reference the entity stored on the Dictionary. This provides a consistent performance level that doesn’t change all that much with the size of the dictionary.

I generally tend to gravitate towards the Dictionary method because the nature of our data doesn’t match up well to sorted arrays as primary containers. However, this is also a very testable benchmark to make. Here is a JSFiddle that will run performance tests comparing the different seek methods (mileage will vary depending upon your native browser performance):

https://jsfiddle.net/ghmyzty4/show/

The Linear “Find” method had the worst performance of all as you would expect. A linear search is a Big O(n) search. The Binary search against the sorted array was the fastest method. It has a Big O(log n) search performance. The Dictionary method has a very fast performance as well. The results of the fiddle benchmark looks at a glance like Big O(log (n+1)) but take that with a grain of salt.

Now go “test” someone’s browser with an infinite loop!

Dan Gidman

Sr. Developer / Stackify

]]>
Using Jira and Zephyr to show test coverage https://stackify.com/using-jira-and-zephyr-to-show-test-coverage/ Fri, 20 May 2016 07:48:13 +0000 https://stackify.com/?p=5961

So, how do you show management that you are actually testing (you know, besides saying “It all look’s good, ship it”)?

There are two tools we use a lot at Stackify:

Jira

Jira is a great tool for capturing work items and managing workflow from the Development and the QA teams. It helps ensure each release has the proper test case coverage and the ability to “show” that testing actually occurred.

test execution

Zephyr

Zephyr is a perfect tool for Stackify. We are looking to create as many test cases and regression suites for each release as possible without slowing our release cycle down. Especially when we are innovating new products and always adding new features to our core SaaS based platform. Zephyr allows us to easily create the high risk test cases first, and to setup templates for regression tests that will be ran for every release.

test details

This allows us to track each test and capture the number of bugs related to each test case.

bugs

Zephyr has a great dashboard I use to show management our test coverage and give them a “warm fuzzy feeling” that the release is solid.

At Stackify we tend to move quickly and shift gears when needed, so to be able to flow with the development teams a very defined, rigid process just wouldn’t work. As we say around here “Aint nobody got time for that.” This simple process of applying repeatable test cases, automated regression tests, and your basic “open the app and test,” helps ensure us a solid release.

Lamar Clark 

QA Manager / Stackify

]]>
Cleaner Code with Static Factory Methods https://stackify.com/static-factory-methods/ Thu, 28 Apr 2016 15:45:50 +0000 https://stackify.com/?p=5932 A classic creational design pattern from the gang of four is the factory method pattern. Examples of this pattern typically involve a factory class that constructs objects of a different type. The objects that are created are usually implementations of an interface. This pattern provides a layer between consumption (the caller) and creation (the factory). An additional benefit is that the factory provides named methods to the consumer. This can be especially useful depending on the parameters required to construct the object.

An offshoot of this pattern is to provide static factory methods in the class you want an instance of. A static factory method is a public static method on the object that returns a new instance of the object. These type of methods share the same benefits as the traditional factory method design pattern. This is especially useful for value objects that don’t have a separate interface and implementation class.

Static factory methods example

To demonstrate the benefits of static factory methods, let’s jump into an example. Which of these time span objects represent 5 seconds?

newtimespan Static Factory Methods

Not as easy as it sounds unfortunately. This problem is made worse because these constructors take multiple integers. Hours, minutes, seconds, milliseconds. Days? Ticks?

 

Let’s refactor the example to use the static factory methods that already exist in the TimeSpan class.

timespanfrom Static Factory Methods

 

It is pretty obvious now which time span objects represent 5 seconds. No code comments or IntelliSense needed.

The key elements to implement this pattern are simple: the factory method must be public, static, and return an instance of the class in which it is defined. If, like TimeSpan, you will have many factory method variants on your class, it’s helpful to name them similarly (“FromX”) but distinctly, to avoid the kind of ambiguity that we see in TimeSpan’s constructor overloads.

 

Eric Martin Principal Engineer / Stackify

 

 

 

]]>
The Golden Rule of Programming https://stackify.com/golden-rule-programming/ Mon, 21 Jan 2013 16:49:08 +0000 https://stackify.com/?p=3459 There is one particular issue that seems to be the root of most bugs in software programs. I see it over and over and over. Like most programmers, it has caused me heartburn since the day I started programming. So I have worked hard to make sure that my code never breaks my golden rule. I remind my development team every chance I get to also follow what I call the golden rule of programming. I think every new programmer needs a tatoo that says it.

So what is the golden rule of programming?

“If it can be null, it will be null”

Null reference type errors are responsible for a good percentage of all application bugs. They are usually very simple problems. Typically caused by not adding additional logic to ensure that objects have valid values before using them.

How about some simple examples of null values causing problems?

Here is a classic example below. A string variable passed in to a method is used before ensuring it isn’t null. KA-BOOM!

public void DoSomething(string text)
{
     if (text.ToUpper() == "Hello World")
     {
          //do something
     }
}

Some of the most common causes are settings, database calls, or API type calls not returning expected values. For example, you add a new field to your database and don’t populate default values for every record. Randomly records get queried and the code didn’t account for that new field being null. KA-BOOM!

The good news is that a lot of null reference errors can be avoided by adding additional logic and code to ensure objects are not null before trying to use them. Developers should always assume that everything is FUBAR and be very defensive in their code. Pretend every database call is going to fail, every field is going to have messed up data in it.

Some tips to prevent null reference exceptions:

  1. Initialize variables with valid values.
  2. If a variable can be null, then check for null and handle it appropriately
  3. For C# use the ?? operator with strings when appropriate. ex. (stringvar ?? “”).ToUpper()

If you follow my golden rule, I promise you will have far fewer bugs in your apps. Because if it can be null, it will be null!

]]>