Solid Principles in C#

It’s time to talk about a topic that every developer should know to work better regardless of the language or framework used: The S.O.L.I.D principles.

What are the S.O.L.I.D. principles?

The S.O.L.I.D. design principles are a collection of best practices for object-oriented design. The term S.O.L.I.D. comes from the initial letter of each of the five principles that were collected in the book Agile Principles, Patterns, and Practices in C# by Robert C. Martin, or Uncle Bob to his friends.

It was written in 2000, 20 years ago since this article was published. But these Principles are still popular and are still being used widely in the world of OOP Paradigm. You can find the original pdf here https://web.archive.org/web/20150906155800/http://www.objectmentor.com/resources/articles/Principles_and_Patterns.pdf

Yes, you’re not reading it wrongly nor I have a typo. It was written in 2000, 20 years ago since this article was published. But these Principles are still quite popular and are still being used widely in the world of OOP Paradigm.

Why should you use the S.O.L.I.D. principles?

Short answer: Software Rot or Code Rot or Software Erosion is either a slow deterioration of software quality over time or its decreasing responsiveness, which will eventually lead to software becoming faulty, unusable, and in need of upgrade.

Long answer: Software rot refers to the slow degradation in the performance of computer software. Such software shows diminished responsiveness, lacks updates, may become faulty overtime owing to changes in the operating system it is running on and thus may need upgrading.

These are some signs for identifying Software Rot:

  • Rigidity: Difficult to modify the code. New requirements or small changes leads to rebuild the entire software.
  • Fragility: New modifications introduce bugs and vulnerability in the code.
  • Immobility: Non-portability of the code. if a component/module/function cannot be used in another system, this is considered as immobile.
  • Viscosity: When implementing and testing are difficult to perform and also take a long time to execute.
  • Changing Requirements or Changing Needs: Often changes need to be made quickly and may be made by engineers who are not familiar with the code. We cannot dodge the new requirements but we must somehow find a way to make our designs/project resilient to such changes and protect them from rotting.
  • Dependency Management: We know changes introduce new and unplanned for dependencies, so inappropriate module dependencies and increased coupling between systems make the source code more difficult to manage. In order to prevent the degradation of the dependency architecture, the dependencies between modules in an application must be managed.

What will you achieve by using the S.O.L.I.D. Principles?

  • Code More Maintainable
    • Using the Single Responsibility Principle (SRP) and the Open closed principle (OCP) you will be easier in maintaining your code.
  • Code More Flexible
    • It’s quite easy when you need to add features in your code because all codes are loosely coupled.
  • Code More Understandable
    • When you come back to your code six months later, you still understand what you wrote back then.

So what are you waiting for? Try opening your own old project and start applying the principles. You will only see improvements.

(S) Single Responsibility Principle – SRP

The Single Responsibility Principle (SRP) states that each software module should have one and only one reason to change.

(O) Open closed principle – OCP

The Open closed principle (OCP) states that software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

(L) Liskov substitution principle – LSP

The Liskov substitution principle – (LSP) states that objects of a superclass shall be replaceable with objects of its subclasses without breaking the application.

(I) Interface segregation principle – ISP

The Interface segregation principle – (ISP) states that no client should be forced to depend on methods it does not use

(D) Dependency inversion principle – DIP

The Dependency inversion principle – (DIP) introduces an abstraction that decouples the high-level and low-level modules from each other.

 

If you think your friends/network would find this useful, please share it with them. I’d really appreciate it.

Thanks for reading! 🌟

 

 

Nuget TextCase library for .NET

I have often used and created nuget packages in many companies and never had the desire or time to create/manage my own nuget package that could help other fellow developers.

So i decide to create the TextCase library for .NET, it helps changing the cases of existing texts.

Nuget TextCase library for .NET

There are the cases currently available:

  • UpperCase
  • LowerCase
  • TitleCase
  • CapitaliseCase
  • CapitaliseWordsCase
  • ReverseCase
  • AlternateCase
  • CamelCase
  • PascalCase
  • KebabCase
  • SnackCase
  • HashtagCase

Continue reading

How to localize info.plist in Xcode

As you know with iOS 14 Apple requires consent to access the IDFA (Identifier for Advertisers), you need to display the App Tracking Transparency authorization request for accessing the IDFA. How to implement this change? Just update your Info.plist and add the NSUserTrackingUsageDescription key with a custom message describing your usage. My app supports more languages and the info.plist file is only one… 🤔

How to localize info.plist in Xcode ?

<key>NSUserTrackingUsageDescription</key>
<string>This identifier will be used to deliver personalized ads to you.</string>

I read a lot of articles about automatically localize the info.plist file but i had several problems. The easiest solution was to:

  • Add in the project a new Strings file InfoPlist.strings (case sensitive), I’ve already written it but I want to repeat it otherwise it won’t work. You need to create the InfoPlist.strings file, not Infoplist.strings or infoPlist.strings.
  • Open the InfoPlist.strings file and add your keys and custom descriptions.
"NSUserTrackingUsageDescription" = "My app will use this identifier to provide you with personalized ads.";
  • Select the InfoPlist.strings and use the Localization section in the File Inspector to localize the file. Press the Localize… button to add additional Localizations to your app.
  • Run the simulator in each languages and this will work 👍

 

If you think your friends/network would find this useful, please share it with them. I’d really appreciate it.

Thanks for reading! 🌟

 

Reference: About Information Property List Files

How to Take a Screenshot or Record a Video using the iOS Simulator

As an iOS  to show my project or to publish an app on the AppStore I need to take screenshots or to record a video.

The first idea was to use the Simulator and press the button Save Screen when i need, for the video to use QuickTime Player, you can follow this link to understand how to do.

I’ve been using the xcrun command for some time and now I feel comfortable with it. You can automate it by creating a script.

What is xcrum command ?

xcrun is a tool provided by Apple to run any tool inside Xcode from the command line, usually it’s available with the installation of xcode but you can get downloading the Command Line Tools package from the Developer website. The Command Line Tools package is available for download on the Download for Apple Developers page. Log in with your Apple ID, then search and download the Command Line Tools package appropriate for your machine

How to Take a Screenshot with xcrum ?

  1. Run your app in the Simulator.
  2. Launch Terminal.app (in /Applications/Utilities) and run this command:

1
xcrun simctl io booted screenshot screenshot.png

xcrun simctl io booted screenshot screenshot.png

There are several option to use with this command to improve your screenshot:

  • –type
    • Can be “png”, “tiff”, “bmp”, “gif”, “jpeg”. Default is png.
  • –display
    • iOS: supports “internal” or “external”. Default is “internal”
    • tvOS: supports only “external.
    • watchOS: supports only “internal.
  • –mask
    • You may also specify a port by UUID. For non-rectangular displays, handle the mask by policy:
      • ignored: The mask is ignored and the unmasked framebuffer is saved.
      • alpha: The mask is used as premultiplied alpha.
      • black: The mask is rendered black.

How to Record a Video with xcrum ?

  1. Run your app in the Simulator.
  2. Launch Terminal.app (in /Applications/Utilities) and run this command:

1
xcrun simctl io booted recordVideo video.mov

There are several option to use with this command to improve your video:

  • –codec
    • Specifies the codec type: “h264” or “hevc”. Default is “hevc”.
  • –display
    • iOS: supports “internal” or “external”. Default is “internal”
    • tvOS: supports only “external.
    • watchOS: supports only “internal.
  • –mask
    • For non-rectangular displays, handle the mask by policy:
      • ignored: The mask is ignored and the unmasked framebuffer is saved.
      • alpha: Not supported, but retained for compatibility; the mask is rendered black.
      • black: The mask is rendered black.
  • –force
    • Force the output file to be written to, even if the file already exists.

 

If you think your friends/network would find this useful, please share it with them. I’d really appreciate it.

Thanks for reading! 🌟

What should be the Sprint Length?

Agile-Scum-Sprint-Length

Recently with my team we had a discussion about the use of Scrum and what should be the sprint length.

I was not very polite in presenting my ideas based on experience, so I decided to collect them and use this space to write them down and explain my motivations.

I’m not a Scrum Master and I don’t have any certification about it but I can tell you practically what worked and didn’t work in my previous projects. I have also read several blogs and I agree with this approach.

 

Let’s start from the beginning, What are Agile and Scrum ?

Agile is a development methodology based on iterative and incremental approach.

Scrum is one of the implementations of agile methodology, is a framework for developing, delivering, and sustaining complex products.

 

I will immediately answer the question so you don’t have to read everything but I would rather you did.

What should be the Sprint Length?

Simple, for me 2-3 weeks. This approach always worked and is still working. Why ?

  • 2 week cycles create and maintain a sense of urgency within the scrum team.
  • If sprint lengths are of 4 weeks then chances of the teams losing focus or wandering away is higher.
  • Sprint review and retrospectives are far more meaningful when you have 2-3 week sprints.
  • When a team is new or developers do not have the same experience/skills, shorter Sprints help the team learn its capacity/velocity faster.

Continue reading

How to fix error Profile doesn’t match the entitlements file’s values for the application-identifier and keychain-access-groups entitlements

Finally you completed your task, everything is working on your dev machine and you need only to upload the app to the app store and you get this error…”Profile doesn’t match the entitlements file’s values for the application-identifier and keychain-access-groups entitlements” 🙁

Profile doesn't match the entitlements file's values for the application-identifier and keychain-access-groups entitlements

Usually this happen when you need to regenerate provisioning profile and get rid of the old one!

Continue reading

Type Conversion in C#

Type Conversion

The process of converting one type to another is called type conversion. In C#, you can perform the following kinds of conversions:

  • Implicit conversions
  • Explicit conversions
  • User-defined conversions
  • Conversion with a helper class

To go more in detail about Implicit and Explicit conversions read my previous article Boxing and Unboxing in C#.

Implicit conversions

An implicit conversion doesn’t need any special syntax, it can be executed because the compiler knows that the conversion is allowed and that it’s safe to convert.

A value type such as int can be stored as a double because an int can fit inside a double without losing any precision or from a reference type to one of its base types.

In this example, num is int and will be converted to double and no data will be lost.

int num = 123456;
double bigNum = num;
Console.WriteLine("bigNum: {0}", bigNum); 
/* Output:
    bigNum: 123456
*/

Also for reference types, no special syntax is necessary because a derived class always contains all the members of a base class. In these cases, the cast is done implicitly by the compiler.

Rectangle rectangle = new Rectangle();
Shape shape = rectangle;

Continue reading

Boxing and Unboxing in C#

C# is, for the most part, a statically typed language, this means that the compiler will check the type of every expression and you sometimes have to convert between types. The concept of boxing and unboxing is the starting point in C# type system in which a value of any type can be treated as an object.

As mentioned in my previous article C# Difference between Struct and Class, the important difference between a value type and a reference type is that the value type stores its value directly. A reference type stores a reference that points to an object on the heap that contains the value.

Boxing and Unboxing in C#

Boxing

Boxing is the process of taking a value type, putting it inside a new object on the heap and storing a reference to it on the stack. Boxing is an implicit conversion.

public class Program
{
    public static void Main(string[] args)
    {
        int total = 1976;
        object obj = total; // Boxing

        total = 2020;  

        System.Console.WriteLine("The value-type value = {0}", total); 
        System.Console.WriteLine("The reference-type value = {0}", obj); 
    } 
} 
/* Output: 
    The value-type value = 2020 
    The reference-type value = 1976 
*/

Unboxing

Unboxing is the exact opposite, it takes the item from the heap and returns a value type that contains the value from the heap. Unboxing is an explicit conversion. Attempting to unbox null or to unbox a reference to an incompatible value type causes an Exception.

public class Program
{
    public static void Main(string[] args)
    {
        int total = 1976;
        object obj = total;  // Boxing
        
        total = (int)obj; // Unboxing
        System.Console.WriteLine("The value-type value = {0}", total); 
        System.Console.WriteLine("The reference-type value = {0}", obj); 
    } 
} 
/* Output: 
    The value-type value = 1976 
    The reference-type value = 1976 
*/

Performance

There are some performance implications and memory requirements with each box and unboxing operation. When using the non-generic collections to store a value type, the boxing and unboxing operations can hurt performance.

Thanks for reading! 🌟

Difference between Struct and Class in C#

A good understanding of the differences in the behaviour of a Class and a Struct is crucial in creating a good software and developing in csharp.

Struct

A Struct is a value type that is typically used to encapsulate small groups of related variables and it is suitable for representing lightweight objects.

public struct Point 
{ 
    public int x;
    public int y; 
}

Class

A class is a reference type that enables to create your own custom types by grouping together variables of other types, methods and events. It defines the data and behaviour of a type.

public class Person 
{ 
    public string name;
    public Person() 
    { 
        name = "Steve"; 
    }
}

In .NET there are two locations in which a type can be stored in memory:

  • Stack;
  • Heap;

Stack

Value types are stored in the stack.

In this example, we create a variable int a = 3, after a variable int b = 4. On the stack, each variable is stored in the order it was created. In the end, we create a variable int c = b with the same value of b. So they both have 4 as value. For value types, each variable stores its own data.

Heap

The value of a reference type is stored on the heap and the address to this value is stored on the stack.

In this example, we create a class Student with a field name. Then we create an instance of the class Student called a and we set the value name to Alex. In the stack we store variable a and its value Alex on the heap. In the Stack, we store a pointer to the data. After we create another instance of the class Student called and we set the value name to Steve. In the Stack, we store variable b and its value Steve on the heap. Then we create another object called c and we set to b, in the stack we store variable c but its address is the same of b. If we change c name to Robert we are also changing the value of b that now is Robert and not Steve.

Memory

The benefit of storing data on the stack is that it’s faster, smaller, and doesn’t need the attention of the garbage collector, required for the heap. Value types are on the stack most of the time and are freed when the current method ends.

Reference types are on the heap and managed by the garbage collector. When a value type is on the stack, it takes up less memory than it would on the heap.

Difference

These are the main difference between Struct and Class in C#:

Difference between Struct and Class in C#

Tips

Microsoft suggests using a Struct instead of a Class if :

Instances of the type are small and commonly short-lived.

and to avoid Struct if:

It will have to be boxed frequently.

It isn’t immutable.

It has not an instance size under 16 bytes.

It logically doesn’t represent a single value, similar to primitive types.

Thanks for reading! 🌟

.NET Framework

Microsoft .NET Framework

Microsoft .NET Framework

Microsoft .NET is a free, cross-platform, open source developer platform for building many different types of applications.

With .NET, you can use multiple languages, editors, and libraries to build for web, mobile, desktop, gaming and IoT.

You can write .NET apps in C#, F#, or Visual Basic.

.NET Framework is Cross-Platform

  • .NET Core is a cross-platform .NET implementation for websites, servers, and console apps on macOS, Windows, and Linux.
  • .NET Framework supports websites, services, desktop apps, and more on Windows.
  • Xamarin/Mono is a .NET implementation for running apps on all the major mobile operating systems.

The first version was released in 2002 and the current version is 4.7.1.

Dot Net History

Continue reading