0

I installed CodeCracker

This is my original method.

//Add
public bool AddItemToMenu(MenuMapper mapperObj)
{
    using (fb_databaseContext entities = new fb_databaseContext())
    {
        try
        {
            FoodItem newItem = new FoodItem();
            newItem.ItemCategoryID = mapperObj.ItemCategory;
            newItem.ItemName = mapperObj.ItemName;
            newItem.ItemNameInHindi = mapperObj.ItemNameinHindi;
            entities.FoodItems.Add(newItem);
            entities.SaveChanges();

            return true;
        }
        catch (Exception ex)
        {
            //handle exception
            return false;
        }
    }
}

This is the recommended method by CodeCracker.

public static bool AddItemToMenu(MenuMapper mapperObj)
{
    using (fb_databaseContext entities = new fb_databaseContext())
    {
        try
        {
            var newItem = new FoodItem
            {
                ItemCategoryID = mapperObj.ItemCategory,
                ItemName = mapperObj.ItemName,
                ItemNameInHindi = mapperObj.ItemNameinHindi,
            };

            entities.FoodItems.Add(newItem);
            entities.SaveChanges();

            return true;
        }
        catch (Exception ex)
        {
            //handle exception
            return false;
        }
    }
}
  • As far as I know Static methods occupy memory when the application intialize irrespective if they are called or not.
  • When I alrady know the return type then why should I use var keyword.
  • Why this way of Object intializer is better.

I am very curios to get these answer, as it can guide me in a long way.

Adding one more method:-

private string GeneratePaymentHash(OrderDetailMapper order)
{
    var payuBizzString = string.Empty;

    payuBizzString = "hello|" + order.OrderID + "|" + order.TotalAmount + "|FoodToken|" + order.CustomerName + "|myemail@gmail.com|||||||||||10000";
    var sha1 = System.Security.Cryptography.SHA512Managed.Create();

    var inputBytes = Encoding.ASCII.GetBytes(payuBizzString);
    var hash = sha1.ComputeHash(inputBytes);

    var sb = new StringBuilder();
    for (var i = 0; i < hash.Length; i++)
    {
        sb.Append(hash[i].ToString("X2"));
    }
    return sb.ToString().ToLower();
}
Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42
Kgn-web
  • 7,047
  • 24
  • 95
  • 161

5 Answers5

4

As far as I know Static methods occupy memory when the application intialize irrespective if they are called or not.

All methods do that. You are probably confusing this with static fields, which occupy memory even when no instances of the class are created. Generally, if a method can be made static, it should be made static, except when it is an implementation of an interface.

When I already know the return type then why should I use var keyword.

To avoid specifying the type twice on the same line of code.

Why this way of Object intializer is better?

Because it groups the assignments visually, and reduces the clutter around them, making it easier to read.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thanks for your post, will this updates boost performance as well?? – Kgn-web Dec 18 '16 at 10:00
  • @Kgn-web Probably not in a measurable way. It does slightly improve readability and ease of understanding, which is the goal of following consistent coding standards in the first place. – Sergey Kalinichenko Dec 18 '16 at 10:03
  • I have added one more method. Here I am passing Instance varilable still it is suggesting me to mark it as static – – Kgn-web Dec 18 '16 at 10:13
  • @Kgn-web It does not know what kind of variable you are passing to the method on the call - it could be an instance variable, but it could also be a local variable. As long as the method itself makes no access to instance variables, it is eligible to become static. – Sergey Kalinichenko Dec 18 '16 at 10:18
  • As long as the method itself makes no access to instance variables, - Can you please elaborate this statement more with an example?? Thanks – Kgn-web Dec 18 '16 at 10:21
  • 1
    @Kgn-web The test is if you can mark a method `static` and it still compiles, then it makes no direct access to instance fields and instance methods. Your second method makes access to local variables and to its parameter. It does not call other instance methods on itself (i.e. without the dot operator or `this.` access), and it does not access fields of the object itself. – Sergey Kalinichenko Dec 18 '16 at 10:27
  • Thanks. I am adding one more query. Hope you don't mind. Suppose approaching this way, all my methods are marked as `static`, then should I go ahead & mark my `class` also static. – Kgn-web Dec 18 '16 at 10:32
1
  1. Static methods don't occupy any more memory than instance methods. Additionally, your method should be static because it doesn't rely in any way on accessing itself (this) as an instance.

  2. Using var is most likely for readability. var is always only 3 letters while many types are much longer and can force the name of the variable much further along the line.

  3. The object initializer is, again, most likely for readability by not having the variable name prefix all the attributes. It also means all your assignments are done at once.

In most cases, this tool you're using seems to be about making code more readable and clean. There may be certain cases where changes will boost performance by hinting to the compiler about your intentions, but generally, this is about being able to understand the code at a glance.

Only concern yourself with performance if you're actually experiencing performance issues. If you are experiencing performance issues then use some profiling tools to measure your application performance and find out which parts of your code are running slowly.

Soviut
  • 88,194
  • 49
  • 192
  • 260
  • Thanks for your post, will this updates boost performance as well?? – Kgn-web Dec 18 '16 at 10:00
  • @Kgn-web readability is almost always more important. Only concern yourself about performance if you're having performance issues. In which case, you should use some profiling tools to see where your code is running slowest. – Soviut Dec 18 '16 at 10:02
  • Nothing such issues. Does changing the instance method to static method improve memory usage?? – Kgn-web Dec 18 '16 at 10:04
  • "...having the same method duplicated over and over again on each instance..." What are you talking about? The compiler doesn't create a new copy of the method for each instance created. – Petter Hesselberg Dec 18 '16 at 10:04
  • @PetterHesselberg I've updated my answer to reflect that. – Soviut Dec 18 '16 at 10:07
  • @PetterHesselberg, I have added one more method. Here I am passing Instance varilable still it is suggesting me to mark it as static – Kgn-web Dec 18 '16 at 10:13
  • @Soviut, Please add your input to the new added – Kgn-web Dec 18 '16 at 10:13
  • @Soviut, since you're passing a reference to an instance, the method has a reference to that instance and doesn't need the `this` reference. Remove the parameter and change `order` to `this`. The method can no longer be static. – Petter Hesselberg Dec 18 '16 at 10:17
  • @PetterHesselberg what's your point? Most static methods could technically be made into instance methods but that doesn't mean they should be. The behaviour of this method is static because it's provided all the context that's needed via the arguments. – Soviut Dec 18 '16 at 10:22
  • It looks like the OP is unclear on the static/non-static distinction, and my point was an attempt to clarify that difference. Did you interpret the last question differently? – Petter Hesselberg Dec 18 '16 at 10:25
1

As far as I know Static methods occupy memory when the application initialize irrespective if they are called or not.

This is true for all kind of methods, so that's irrelevant.

When I already know the return type then why should I use var keyword.

var is a personal preference (which is a syntactic sugar). This analyzer might think since the return type is already known, there is no need to use type explicitly, so, I recommend to use var instead. Personaly, I use var as much as possible. For this issue, you might wanna read Use of var keyword in C#

Why this way of Object intializer is better.

I can't say object initializer is always better but object initialize supplies that either your newItem will be null or it's fully initialized since your;

var newItem = new FoodItem
{
    ItemCategoryID = mapperObj.ItemCategory,
    ItemName = mapperObj.ItemName,
    ItemNameInHindi = mapperObj.ItemNameinHindi,
};

is actually equal to

var temp = new FoodItem();
newItem.ItemCategoryID = mapperObj.ItemCategory;
newItem.ItemName = mapperObj.ItemName;
newItem.ItemNameInHindi = mapperObj.ItemNameinHindi;
var newItem = temp;

so, this is not the same as your first one. There is a nice answer on Code Review about this subject. https://codereview.stackexchange.com/a/4330/6136 Also you might wanna check: http://community.bartdesmet.net/blogs/bart/archive/2007/11/22/c-3-0-object-initializers-revisited.aspx

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • Highly informative. Please add your suggestion for the new added priivate method . I have added one more method. Here I am passing Instance varilable still it is suggesting me to mark it as static – – Kgn-web Dec 18 '16 at 10:16
  • Suppose approaching this way, all my methods are marked as static, then should I go ahead & mark my class also static – Kgn-web Dec 18 '16 at 10:37
0

A lot of these are personal preferences but most coding standards allow other programmers to read your code easier.

Changing the static method to an instance takes more advantage of OO concepts, it limits the amount of mixed state and also allows you to add interfaces so you can mock out the class for testing.

The var keyword is still statically typed but because we should concentrate on naming and giving our objects more meaningful so explicitly declaring the type becomes redundant.

As for the object initialisation this just groups everything that is required to setup the object. Just makes it a little easier to read.

Kevin Smith
  • 13,746
  • 4
  • 52
  • 77
0

As far as I know Static methods occupy memory when the application intialize irrespective if they are called or not.

Methods that are never called may or may not be optimized away, depending on the compiler, debug vs. release and such. Static vs. non-static does not matter.

A method that doesn't need a this reference can (and IMO should) be static.

When I already know the return type then why should I use var keyword

No reason. There's no difference; do whatever you prefer.

Why this way of Object intializer is better.

The object initializer syntax generates the same code for most practical purposes (see answer @SonerGönül for the details). Mostly it's a matter of preference -- personally I find the object initializer syntax easier to read and maintain.

Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42