Search Results

Search found 11306 results on 453 pages for 'methods'.

Page 1/453 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • F# Extention Methods on Lists, IEnumberable, etc

    - by flevine100
    I have searched StackOverflow (and other sources) for this answer, but can't seem to find anything. In C#, if I had a widget definition, say: class widget { public string PrettyName() { ... do stuff here } } and I wanted to allow for easy printing of a list of Widgets, I might do this: namespace ExtensionMethods { public static PrintAll( this IEnumerable<Widget> widgets, TextWriter writer ) { foreach(var w in widgets) { writer.WriteLine( w.PrettyName() ) } } } How would I accomplish something similar with a record type and a collection (List or Seq preferrably in F#). I'd love to have a list of Widgest and be able to call a function right on the collection that did something like this. Assume (since it's F#) that the function would not be changing the state of the collection that it's attached to, but returning some new value.

    Read the article

  • Are long methods always bad?

    - by wobbily_col
    So looking around earlier I noticed some comments about long methods being bad practice. I am not sure I always agree that long methods are bad (and would like opinions from others). For example I have some Django views that do a bit of processing of the objects before sending them to the view, a long method being 350 lines of code. I have my code written so that it deals with the paramaters - sorting / filtering the queryset, then bit by bit does some processing on the objects my query has returned. So the processing is mainly conditional aggregation, that has complex enough rules it can't easily be done in the database, so I have some variables declared outside the main loop then get altered during the loop. varaible_1 = 0 variable_2 = 0 for object in queryset : if object.condition_condition_a and variable_2 > 0 : variable 1+= 1 ..... ... . more conditions to alter the variables return queryset, and context So according to the theory I should factor out all the code into smaller methods, so That I have the view method as being maximum one page long. However having worked on various code bases in the past, I sometimes find it makes the code less readable, when you need to constantly jump from one method to the next figuring out all the parts of it, while keeping the outermost method in your head. I find that having a long method that is well formatted, you can see the logic more easily, as it isn't getting hidden away in inner methods. I could factor out the code into smaller methods, but often there is is an inner loop being used for two or three things, so it would result in more complex code, or methods that don't do one thing but two or three (alternatively I could repeat inner loops for each task, but then there will be a performance hit). So is there a case that long methods are not always bad? Is there always a case for writing methods, when they will only be used in one place?

    Read the article

  • Read XML Files using LINQ to XML and Extension Methods

    - by psheriff
    In previous blog posts I have discussed how to use XML files to store data in your applications. I showed you how to read those XML files from your project and get XML from a WCF service. One of the problems with reading XML files is when elements or attributes are missing. If you try to read that missing data, then a null value is returned. This can cause a problem if you are trying to load that data into an object and a null is read. This blog post will show you how to create extension methods to detect null values and return valid values to load into your object. The XML Data An XML data file called Product.xml is located in the \Xml folder of the Silverlight sample project for this blog post. This XML file contains several rows of product data that will be used in each of the samples for this post. Each row has 4 attributes; namely ProductId, ProductName, IntroductionDate and Price. <Products>  <Product ProductId="1"           ProductName="Haystack Code Generator for .NET"           IntroductionDate="07/01/2010"  Price="799" />  <Product ProductId="2"           ProductName="ASP.Net Jumpstart Samples"           IntroductionDate="05/24/2005"  Price="0" />  ...  ...</Products> The Product Class Just as you create an Entity class to map each column in a table to a property in a class, you should do the same for an XML file too. In this case you will create a Product class with properties for each of the attributes in each element of product data. The following code listing shows the Product class. public class Product : CommonBase{  public const string XmlFile = @"Xml/Product.xml";   private string _ProductName;  private int _ProductId;  private DateTime _IntroductionDate;  private decimal _Price;   public string ProductName  {    get { return _ProductName; }    set {      if (_ProductName != value) {        _ProductName = value;        RaisePropertyChanged("ProductName");      }    }  }   public int ProductId  {    get { return _ProductId; }    set {      if (_ProductId != value) {        _ProductId = value;        RaisePropertyChanged("ProductId");      }    }  }   public DateTime IntroductionDate  {    get { return _IntroductionDate; }    set {      if (_IntroductionDate != value) {        _IntroductionDate = value;        RaisePropertyChanged("IntroductionDate");      }    }  }   public decimal Price  {    get { return _Price; }    set {      if (_Price != value) {        _Price = value;        RaisePropertyChanged("Price");      }    }  }} NOTE: The CommonBase class that the Product class inherits from simply implements the INotifyPropertyChanged event in order to inform your XAML UI of any property changes. You can see this class in the sample you download for this blog post. Reading Data When using LINQ to XML you call the Load method of the XElement class to load the XML file. Once the XML file has been loaded, you write a LINQ query to iterate over the “Product” Descendants in the XML file. The “select” portion of the LINQ query creates a new Product object for each row in the XML file. You retrieve each attribute by passing each attribute name to the Attribute() method and retrieving the data from the “Value” property. The Value property will return a null if there is no data, or will return the string value of the attribute. The Convert class is used to convert the value retrieved into the appropriate data type required by the Product class. private void LoadProducts(){  XElement xElem = null;   try  {    xElem = XElement.Load(Product.XmlFile);     // The following will NOT work if you have missing attributes    var products =         from elem in xElem.Descendants("Product")        orderby elem.Attribute("ProductName").Value        select new Product        {          ProductId = Convert.ToInt32(            elem.Attribute("ProductId").Value),          ProductName = Convert.ToString(            elem.Attribute("ProductName").Value),          IntroductionDate = Convert.ToDateTime(            elem.Attribute("IntroductionDate").Value),          Price = Convert.ToDecimal(elem.Attribute("Price").Value)        };     lstData.DataContext = products;  }  catch (Exception ex)  {    MessageBox.Show(ex.Message);  }} This is where the problem comes in. If you have any missing attributes in any of the rows in the XML file, or if the data in the ProductId or IntroductionDate is not of the appropriate type, then this code will fail! The reason? There is no built-in check to ensure that the correct type of data is contained in the XML file. This is where extension methods can come in real handy. Using Extension Methods Instead of using the Convert class to perform type conversions as you just saw, create a set of extension methods attached to the XAttribute class. These extension methods will perform null-checking and ensure that a valid value is passed back instead of an exception being thrown if there is invalid data in your XML file. private void LoadProducts(){  var xElem = XElement.Load(Product.XmlFile);   var products =       from elem in xElem.Descendants("Product")      orderby elem.Attribute("ProductName").Value      select new Product      {        ProductId = elem.Attribute("ProductId").GetAsInteger(),        ProductName = elem.Attribute("ProductName").GetAsString(),        IntroductionDate =            elem.Attribute("IntroductionDate").GetAsDateTime(),        Price = elem.Attribute("Price").GetAsDecimal()      };   lstData.DataContext = products;} Writing Extension Methods To create an extension method you will create a class with any name you like. In the code listing below is a class named XmlExtensionMethods. This listing just shows a couple of the available methods such as GetAsString and GetAsInteger. These methods are just like any other method you would write except when you pass in the parameter you prefix the type with the keyword “this”. This lets the compiler know that it should add this method to the class specified in the parameter. public static class XmlExtensionMethods{  public static string GetAsString(this XAttribute attr)  {    string ret = string.Empty;     if (attr != null && !string.IsNullOrEmpty(attr.Value))    {      ret = attr.Value;    }     return ret;  }   public static int GetAsInteger(this XAttribute attr)  {    int ret = 0;    int value = 0;     if (attr != null && !string.IsNullOrEmpty(attr.Value))    {      if(int.TryParse(attr.Value, out value))        ret = value;    }     return ret;  }   ...  ...} Each of the methods in the XmlExtensionMethods class should inspect the XAttribute to ensure it is not null and that the value in the attribute is not null. If the value is null, then a default value will be returned such as an empty string or a 0 for a numeric value. Summary Extension methods are a great way to simplify your code and provide protection to ensure problems do not occur when reading data. You will probably want to create more extension methods to handle XElement objects as well for when you use element-based XML. Feel free to extend these extension methods to accept a parameter which would be the default value if a null value is detected, or any other parameters you wish. NOTE: You can download the complete sample code at my website. http://www.pdsa.com/downloads. Choose “Tips & Tricks”, then "Read XML Files using LINQ to XML and Extension Methods" from the drop-down. Good Luck with your Coding,Paul D. Sheriff  

    Read the article

  • Naming methods that do the same thing but return different types

    - by Konstantin Ð.
    Let's assume that I'm extending a graphical file chooser class (JFileChooser). This class has methods which display the file chooser dialog and return a status signature in the form of an int: APPROVE_OPTION if the user selects a file and hits Open /Save, CANCEL_OPTION if the user hits Cancel, and ERROR_OPTION if something goes wrong. These methods are called showDialog(). I find this cumbersome, so I decide to make another method that returns a File object: in the case of APPROVE_OPTION, it returns the file selected by the user; otherwise, it returns null. This is where I run into a problem: would it be okay for me to keep the showDialog() name, even though methods with that name — and a different return type — already exist? To top it off, my method takes an additional parameter: a File which denotes in which directory the file chooser should start. My question to you: Is it okay to call a method the same name as a superclass method if they return different types? Or would that be confusing to API users? (If so, what other name could I use?) Alternatively, should I keep the name and change the return type so it matches that of the other methods? public int showDialog(Component parent, String approveButtonText) // Superclass method public File showDialog(Component parent, File location) // My method

    Read the article

  • Extension methods conflict

    - by Yochai Timmer
    Lets say I have 2 extension methods to string, in 2 different namespaces: namespace test1 { public static class MyExtensions { public static int TestMethod(this String str) { return 1; } } } namespace test2 { public static class MyExtensions2 { public static int TestMethod(this String str) { return 2; } } } These methods are just for example, they don't really do anything. Now lets consider this piece of code: using System; using test1; using test2; namespace blah { public static class Blah { public Blah() { string a = "test"; int i = a.TestMethod(); //Which one is chosen ? } } } I know that only one of the extension methods will be chosen. Which one will it be ? and why ? How can I choose a certain method from a certain namespace ? Edit: Usually I'd use Namespace.ClassNAME.Method() ... But that just beats the whole idea of extension methods. And I don't think you can use Variable.Namespace.Method()

    Read the article

  • Do private static methods in C# hurt anything?

    - by fish
    I created a private validation method for a certain validation that happens multiple times in my class (I can't store the validated data for various reasons). Now, ReSharper suggests that the function could be made static. I'm a little reluctant to do so due known problems with static methods. It would be a private static method. My question is, can private static methods cause similar coupling and testing problems like public static methods? Is it a bad practice? I would guess not, but I'm not sure if there is a pitfall here.

    Read the article

  • Can't I just use all static methods?

    - by Reddy S R
    What's the difference between the two UpdateSubject methods below? I felt using static methods is better if you just want to operate on the entities. In which situations should I go with non-static methods? public class Subject { public int Id {get; set;} public string Name { get; set; } public static bool UpdateSubject(Subject subject) { //Do something and return result return true; } public bool UpdateSubject() { //Do something on 'this' and return result return true; } } I know I will be getting many kicks from the community for this really annoying question but I could not stop myself asking it. Does this become impractical when dealing with inheritance?

    Read the article

  • Naming methods that perform HTTP GET/POST calls?

    - by antonpug
    In the application I am currently working on, there are generally 3 types of HTTP calls: pure GETs pure POSTs (updating the model with new data) "GET" POSTs (posting down an object to get some data back, no updates to the model) In the integration service, generally we name methods that post "postSomething()", and methods that get, "getSomething()". So my question is, if we have a "GET" POST, should the method be called: getSomething - seeing as the purpose is to obtain data postSomething - since we are technically using POST performSomeAction - arbitrary name that's more relevant to the action What are everyone's thoughts?

    Read the article

  • The best way to have a pointer to several methods - critique requested

    - by user827992
    I'm starting with a short introduction of what i know from the C language: a pointer is a type that stores an adress or a NULL the * operator reads the left value of the variable on its right and use this value as address and reads the value of the variable at that address the & operator generate a pointer to the variable on its right so i was thinking that in C++ the pointers can work this way too, but i was wrong, to generate a pointer to a static method i have to do this: #include <iostream> class Foo{ public: static void dummy(void){ std::cout << "I'm dummy" << std::endl; }; }; int main(){ void (*p)(); p = Foo::dummy; // step 1 p(); p = &(Foo::dummy); // step 2 p(); p = Foo; // step 3 p->dummy(); return(0); } now i have several questions: why step 1 works why step 2 works too, looks like a "pointer to pointer" for p to me, very different from step 1 why step 3 is the only one that doesn't work and is the only one that makes some sort of sense to me, honestly how can i write an array of pointers or a pointer to pointers structure to store methods ( static or non-static from real objects ) what is the best syntax and coding style for generating a pointer to a method?

    Read the article

  • Prefer extension methods for encapsulation and reusability?

    - by tzaman
    edit4: wikified, since this seems to have morphed more into a discussion than a specific question. In C++ programming, it's generally considered good practice to "prefer non-member non-friend functions" instead of instance methods. This has been recommended by Scott Meyers in this classic Dr. Dobbs article, and repeated by Herb Sutter and Andrei Alexandrescu in C++ Coding Standards (item 44); the general argument being that if a function can do its job solely by relying on the public interface exposed by the class, it actually increases encapsulation to have it be external. While this confuses the "packaging" of the class to some extent, the benefits are generally considered worth it. Now, ever since I've started programming in C#, I've had a feeling that here is the ultimate expression of the concept that they're trying to achieve with "non-member, non-friend functions that are part of a class interface". C# adds two crucial components to the mix - the first being interfaces, and the second extension methods: Interfaces allow a class to formally specify their public contract, the methods and properties that they're exposing to the world. Any other class can choose to implement the same interface and fulfill that same contract. Extension methods can be defined on an interface, providing any functionality that can be implemented via the interface to all implementers automatically. And best of all, because of the "instance syntax" sugar and IDE support, they can be called the same way as any other instance method, eliminating the cognitive overhead! So you get the encapsulation benefits of "non-member, non-friend" functions with the convenience of members. Seems like the best of both worlds to me; the .NET library itself providing a shining example in LINQ. However, everywhere I look I see people warning against extension method overuse; even the MSDN page itself states: In general, we recommend that you implement extension methods sparingly and only when you have to. (edit: Even in the current .NET library, I can see places where it would've been useful to have extensions instead of instance methods - for example, all of the utility functions of List<T> (Sort, BinarySearch, FindIndex, etc.) would be incredibly useful if they were lifted up to IList<T> - getting free bonus functionality like that adds a lot more benefit to implementing the interface.) So what's the verdict? Are extension methods the acme of encapsulation and code reuse, or am I just deluding myself? (edit2: In response to Tomas - while C# did start out with Java's (overly, imo) OO mentality, it seems to be embracing more multi-paradigm programming with every new release; the main thrust of this question is whether using extension methods to drive a style change (towards more generic / functional C#) is useful or worthwhile..) edit3: overridable extension methods The only real problem identified so far with this approach, is that you can't specialize extension methods if you need to. I've been thinking about the issue, and I think I've come up with a solution. Suppose I have an interface MyInterface, which I want to extend - I define my extension methods in a MyExtension static class, and pair it with another interface, call it MyExtensionOverrider. MyExtension methods are defined according to this pattern: public static int MyMethod(this MyInterface obj, int arg, bool attemptCast=true) { if (attemptCast && obj is MyExtensionOverrider) { return ((MyExtensionOverrider)obj).MyMethod(arg); } // regular implementation here } The override interface mirrors all of the methods defined in MyExtension, except without the this or attemptCast parameters: public interface MyExtensionOverrider { int MyMethod(int arg); string MyOtherMethod(); } Now, any class can implement the interface and get the default extension functionality: public class MyClass : MyInterface { ... } Anyone that wants to override it with specific implementations can additionally implement the override interface: public class MySpecializedClass : MyInterface, MyExtensionOverrider { public int MyMethod(int arg) { //specialized implementation for one method } public string MyOtherMethod() { // fallback to default for others MyExtension.MyOtherMethod(this, attemptCast: false); } } And there we go: extension methods provided on an interface, with the option of complete extensibility if needed. Fully general too, the interface itself doesn't need to know about the extension / override, and multiple extension / override pairs can be implemented without interfering with each other. I can see three problems with this approach - It's a little bit fragile - the extension methods and override interface have to be kept synchronized manually. It's a little bit ugly - implementing the override interface involves boilerplate for every function you don't want to specialize. It's a little bit slow - there's an extra bool comparison and cast attempt added to the mainline of every method. Still, all those notwithstanding, I think this is the best we can get until there's language support for interface functions. Thoughts?

    Read the article

  • Thoughts on C# Extension Methods

    - by Damon
    I'm not a huge fan of extension methods.  When they first came out, I remember seeing a method on an object that was fairly useful, but when I went to use it another piece of code that method wasn't available.  Turns out it was an extension method and I hadn't included the appropriate assembly and imports statement in my code to use it.  I remember being a bit confused at first about how the heck that could happen (hey, extension methods were new, cut me some slack) and it took a bit of time to track down exactly what it was that I needed to include to get that method back.  I just imagined a new developer trying to figure out why a method was missing and fruitlessly searching on MSDN for a method that didn't exist and it just didn't sit well with me. I am of the opinion that if you have an object, then you shouldn't have to include additional assemblies to get additional instance level methods out of that object.  That opinion applies to namespaces as well - I do not like it when the contents of a namespace are split out into multiple assemblies.  I prefer to have static utility classes instead of extension methods to keep things nicely packaged into a cohesive unit.  It also makes it abundantly clear where utility methods are used in code.  I will concede, however, that it can make code a bit more verbose and lengthy.  There is always a trade-off. Some people harp on extension methods because it breaks the tenants of object oriented development and allows you to add methods to sealed classes.  Whatever.  Extension methods are just utility methods that you can tack onto an object after the fact.  Extension methods do not give you any more access to an object than the developer of that object allows, so I say that those who cry OO foul on extension methods really don't have much of an argument on which to stand.  In fact, I have to concede that my dislike of them is really more about style than anything of great substance. One interesting thing that I found regarding extension methods is that you can call them on null objects. Take a look at this extension method: namespace ExtensionMethods {   public static class StringUtility   {     public static int WordCount(this string str)     {       if(str == null) return 0;       return str.Split(new char[] { ' ', '.', '?' },         StringSplitOptions.RemoveEmptyEntries).Length;     }   }   } Notice that the extension method checks to see if the incoming string parameter is null.  I was worried that the runtime would perform a check on the object instance to make sure it was not null before calling an extension method, but that is apparently not the case.  So, if you call the following code it runs just fine. string s = null; int words = s.WordCount(); I am a big fan of things working, but this seems to go against everything I've come to know about instance level methods.  However, an extension method is really a static method masquerading as an instance-level method, so I suppose it would be far more frustrating if it failed since there is really no reason it shouldn't succeed. Although I'm not a fan of extension methods, I will say that if you ever find yourself at an impasse with a die-hard fan of either the utility class or extension method approach, then there is a common ground.  Extension methods are defined in static classes, and you call them from those static classes as well as directly from the objects they extend.  So if you build your utility classes using extension methods, then you can have it your way and they can have it theirs. 

    Read the article

  • Prefer class members or passing arguments between internal methods?

    - by geoffjentry
    Suppose within the private portion of a class there is a value which is utilized by multiple private methods. Do people prefer having this defined as a member variable for the class or passing it as an argument to each of the methods - and why? On one hand I could see an argument to be made that reducing state (ie member variables) in a class is generally a good thing, although if the same value is being repeatedly used throughout a class' methods it seems like that would be an ideal candidate for representation as state for the class to make the code visibly cleaner if nothing else. Edit: To clarify some of the comments/questions that were raised, I'm not talking about constants and this isn't relating to any particular case rather just a hypothetical that I was talking to some other people about. Ignoring the OOP angle for a moment, the particular use case that I had in mind was the following (assume pass by reference just to make the pseudocode cleaner) int x doSomething(x) doAnotherThing(x) doYetAnotherThing(x) doSomethingElse(x) So what I mean is that there's some variable that is common between multiple functions - in the case I had in mind it was due to chaining of smaller functions. In an OOP system, if these were all methods of a class (say due to refactoring via extracting methods from a large method), that variable could be passed around them all or it could be a class member.

    Read the article

  • Purpose of Instance Methods vs. Class Methods in Objective-C

    - by qegal
    I have checked out all these questions... Difference Class and Instance Methods Difference between class methods and instance methods? Objective-C: Class vs Instance Methods? ...and all they explain is how instance methods are used on instances of a class and class methods are used with the class name, when a message is sent to a class object. This is helpful, but I'm curious to know why one would use a class method vs. an instance method. I'm fairly new to iOS application development, and usually use class methods, and I feel like I'm doing something wrong. Thanks in advanced!

    Read the article

  • evaluating cost/benefits of using extension methods in C# => 3.0

    - by BillW
    Hi, In what circumstances (usage scenarios) would you choose to write an extension rather than sub-classing an object ? < full disclosure : I am not an MS employee; I do not know Mitsu Furota personally; I do know the author of the open-source Componax library mentioned here, but I have no business dealings with him whatsoever; I am not creating, or planning to create any commercial product using extensions : in sum : this post is from pure intellectal curiousity related to my trying to (continually) become aware of "best practices" I find the idea of extension methods "cool," and obviously you can do "far-out" things with them as in the many examples you can in Mitsu Furota's (MS) blog postslink text. A personal friend wrote the open-source Componax librarylink text, and there's some remarkable facilities in there; but he is in complete command of his small company with total control over code guidelines, and every line of code "passes through his hands." While this is speculation on my part : I think/guess other issues might come into play in a medium-to-large software team situation re use of Extensions. Looking at MS's guidelines at link text, you find : In general, you will probably be calling extension methods far more often than implementing your own. ... In general, we recommend that you implement extension methods sparingly and only when you have to. Whenever possible, client code that must extend an existing type should do so by creating a new type derived from the existing type. For more information, see Inheritance (C# Programming Guide). ... When the compiler encounters a method invocation, it first looks for a match in the type's instance methods. If no match is found, it will search for any extension methods that are defined for the type, and bind to the first extension method that it finds. And at Ms's link text : Extension methods present no specific security vulnerabilities. They can never be used to impersonate existing methods on a type, because all name collisions are resolved in favor of the instance or static method defined by the type itself. Extension methods cannot access any private data in the extended class. Factors that seem obvious to me would include : I assume you would not write an extension unless you expected it be used very generally and very frequently. On the other hand : couldn't you say the same thing about sub-classing ? Knowing we can compile them into a seperate dll, and add the compiled dll, and reference it, and then use the extensions : is "cool," but does that "balance out" the cost inherent in the compiler first having to check to see if instance methods are defined as described above. Or the cost, in case of a "name clash," of using the Static invocation methods to make sure your extension is invoked rather than the instance definition ? How frequent use of Extensions would affect run-time performance or memory use : I have no idea. So, I'd appreciate your thoughts, or knowing about how/when you do, or don't do, use Extensions, compared to sub-classing. thanks, Bill

    Read the article

  • How to bundle extension methods requiring configuration in a library

    - by Greg
    Hi, I would like to develop a library that I can re-use to add various methods involved in navigating/searching through a graph (nodes/relationships, or if you like vertexs/edges). The generic requirements would be: There are existing classes in the main project that already implement the equivalent of the graph class (which contains the lists of nodes / relationships), node class and relationship class (which links nodes together) - the main project likely already has persistence mechanisms for the info (e.g. these classes might be built using Entity Framework for persistance) Methods would need to be added to each of these 3 classes: (a) graph class - methods like "search all nodes", (b) node class - methods such as "find all children to depth i", c) relationship class - methods like "return relationship type", "get parent node", "get child node". I assume there would be a need to inform the library with the extending methods the class names for the graph/node/relationships table (as different project might use different names). To some extent it would need to be like how a generics collection works (where you pass the classes to the collection so it knows what they are). Need to be a way to inform the library of which node property to use for equality checks perhaps (e.g. if it were a graph of webpages the equality field to use might be the URI path) I'm assuming that using abstract base classes wouldn't really work as this would tie usage down to have to use the same persistence approach, and same class names etc. Whereas really I want to be able to, for a project that has "graph-like" characteristics, the ability to add graph searching/walking methods to it.

    Read the article

  • Stepping into Ruby Meta-Programming: Generating proxy methods for multiple internal methods

    - by mstksg
    Hi all; I've multiply heard Ruby touted for its super spectacular meta-programming capabilities, and I was wondering if anyone could help me get started with this problem. I have a class that works as an "archive" of sorts, with internal methods that process and output data based on an input. However, the items in the archive in the class itself are represented and processed with integers, for performance purposes. The actual items outside of the archive are known by their string representation, which is simply number_representation.to_s(36). Because of this, I have hooked up each internal method with a "proxy method" that converts the input into the integer form that the archive recognizes, runs the internal method, and converts the output (either a single other item, or a collection of them) back into strings. The naming convention is this: internal methods are represented by _method_name; their corresponding proxy method is represented by method_name, with no leading underscore. For example: class Archive ## PROXY METHODS ## ## input: string representation of id's ## output: string representation of id's def do_something_with id result = _do_something_with id.to_i(36) return nil if result == nil return result.to_s(36) end def do_something_with_pair id_1,id_2 result = _do_something_with_pair id_1.to_i(36), id_2.to_i(36) return nil if result == nil return result.to_s(36) end def do_something_with_these ids result = _do_something_with_these ids.map { |n| n.to_i(36) } return nil if result == nil return result.to_s(36) end def get_many_from id result = _get_many_from id return nil if result == nil # no sparse arrays returned return result.map { |n| n.to_s(36) } end ## INTERNAL METHODS ## ## input: integer representation of id's ## output: integer representation of id's def _do_something_with id # does something with one integer-represented id, # returning an id represented as an integer end def do_something_with_pair id_1,id_2 # does something with two integer-represented id's, # returning an id represented as an integer end def _do_something_with_these ids # does something with multiple integer ids, # returning an id represented as an integer end def _get_many_from id # does something with one integer-represented id, # returns a collection of id's represented as integers end end There are a couple of reasons why I can't just convert them if id.class == String at the beginning of the internal methods: These internal methods are somewhat computationally-intensive recursive functions, and I don't want the overhead of checking multiple times at every step There is no way, without adding an extra parameter, to tell whether or not to re-convert at the end I want to think of this as an exercise in understanding ruby meta-programming Does anyone have any ideas? edit The solution I'd like would preferably be able to take an array of method names @@PROXY_METHODS = [:do_something_with, :do_something_with_pair, :do_something_with_these, :get_many_from] iterate through them, and in each iteration, put out the proxy method. I'm not sure what would be done with the arguments, but is there a way to test for arguments of a method? If not, then simple duck typing/analogous concept would do as well.

    Read the article

  • Get and Set property accessors are ‘actually’ methods

    - by nmarun
    Well, they are ‘special’ methods, but they indeed are methods. See the class below: 1: public class Person 2: { 3: private string _name; 4:  5: public string Name 6: { 7: get 8: { 9: return _name; 10: } 11: set 12: { 13: if (value == "aaa") 14: { 15: throw new ArgumentException("Invalid Name"); 16: } 17: _name = value; 18: } 19: } 20:  21: public void Save() 22: { 23: Console.WriteLine("Saving..."); 24: } 25: } Ok, so a class with a field, a property with the get and set accessors and a method. Now my calling code says: 1: static void Main() 2: { 3: try 4: { 5: Person person1 = new Person 6: { 7: Name = "aaa", 8: }; 9:  10: } 11: catch (Exception ex) 12: { 13: Console.WriteLine(ex.Message); 14: Console.WriteLine(ex.StackTrace); 15: Console.WriteLine("--------------------"); 16: } 17: } When the code is run, you’ll get the following exception message displayed: Now, you see the first line of the stack trace where it says that the exception was thrown in the method set_Name(String value). Wait a minute, we have not declared any method with that name in our Person class. Oh no, we actually have. When you create a property, this is what happens behind the screen. The CLR creates two methods for each get and set property accessor. Let’s look at the signature once again: set_Name(String value) This also tells you where the ‘value’ keyword comes from in our set property accessor. You’re actually wiring up a method parameter to a field. 1: set 2: { 3: if (value == "aaa") 4: { 5: throw new ArgumentException("Invalid Name"); 6: } 7: _name = value; 8: } Digging deeper on this, I ran the ILDasm tool and this is what I see: We see the ‘free’ constructor (named .ctor) that the compiler gives us, the _name field, the Name property and the Save method. We also see the get_Name and set_Name methods. In order to compare the Save and the set_Name methods, I double-clicked on the two methods and this is what I see: The ‘.method’ keyword tells that both Save and set_Name are both methods (no guessing there!). Seeing the set_Name method as a public method did kinda surprise me. So I said, why can’t I do a person1.set_Name(“abc”) since it is declared as public. This cannot be done because the get_Name and set_Name methods have an extra attribute called ‘specialname’. This attribute is used to identify an IL (Intermediate Language) token that can be treated with special care by the .net language. So the thumb-rule is that any method with the ‘specialname’ attribute cannot be generally called / invoked by the user (a simple test using intellisense proves this). Their functionality is exposed through other ways. In our case, this is done through the property itself. The same concept gets extended to constructors as well making them special methods too. These so-called ‘special’ methods can be identified through reflection. 1: static void ReflectOnPerson() 2: { 3: Type personType = typeof(Person); 4:  5: MethodInfo[] methods = personType.GetMethods(); 6:  7: for (int i = 0; i < methods.Length; i++) 8: { 9: Console.Write("Method: {0}", methods[i].Name); 10: // Determine whether or not each method is a special name. 11: if (methods[i].IsSpecialName) 12: { 13: Console.Write(" has 'SpecialName' attribute"); 14: } 15: Console.WriteLine(); 16: } 17: } Line 11 shows the ‘IsSpecialName’ boolean property. So a method with a ‘specialname’ attribute gets mapped to the IsSpecialName property. The output is displayed as: Wuhuuu! There they are.. our special guests / methods. Verdict: Getting to know the internals… helps!

    Read the article

  • Extension Methods and Application Code

    - by Mystagogue
    I have seen plenty of online guidelines for authoring extension methods, usually along these lines: 1) Avoid authoring extension methods when practical - prefer other approaches first (e.g. regular static methods). 2) Don't author extension methods to extend code you own or currently develop. Instead, author them to extend 3rd party or BCL code. But I have the impression that a couple more guidelines are either implied or advisable. What does the community think of these two additional guidelines: A) Prefer to author extension methods to contain generic functionality rather than application-specific logic. (This seems to follow from guideline #2 above) B) An extension method should be sizeable enough to justify itself (preferably at least 5 lines of code in length). Item (B) is intended to discourage a develoer from writing dozens of extension methods (totalling X lines of code) to refactor or replace what originally was already about X lines of inline code. Perhaps item (B) is badly qualified, or even misinformed about how a one line extension method is actually powerful and justified. I'm curious to know. But if item (B) is somehow dismissed by the community, I must admist I'm still particularly interested in feedback on guideline (A).

    Read the article

  • Extension methods for encapsulation and reusability

    - by tzaman
    In C++ programming, it's generally considered good practice to "prefer non-member non-friend functions" instead of instance methods. This has been recommended by Scott Meyers in this classic Dr. Dobbs article, and repeated by Herb Sutter and Andrei Alexandrescu in C++ Coding Standards (item 44); the general argument being that if a function can do its job solely by relying on the public interface exposed by the class, it actually increases encapsulation to have it be external. While this confuses the "packaging" of the class to some extent, the benefits are generally considered worth it. Now, ever since I've started programming in C#, I've had a feeling that here is the ultimate expression of the concept that they're trying to achieve with "non-member, non-friend functions that are part of a class interface". C# adds two crucial components to the mix - the first being interfaces, and the second extension methods: Interfaces allow a class to formally specify their public contract, the methods and properties that they're exposing to the world. Any other class can choose to implement the same interface and fulfill that same contract. Extension methods can be defined on an interface, providing any functionality that can be implemented via the interface to all implementers automatically. And best of all, because of the "instance syntax" sugar and IDE support, they can be called the same way as any other instance method, eliminating the cognitive overhead! So you get the encapsulation benefits of "non-member, non-friend" functions with the convenience of members. Seems like the best of both worlds to me; the .NET library itself providing a shining example in LINQ. However, everywhere I look I see people warning against extension method overuse; even the MSDN page itself states: In general, we recommend that you implement extension methods sparingly and only when you have to. So what's the verdict? Are extension methods the acme of encapsulation and code reuse, or am I just deluding myself?

    Read the article

  • How to prevent duplicate data access methods that retrieve similar data?

    - by Ronald Wildenberg
    In almost every project I work on with a team, the same problem seems to creep in. Someone writes UI code that needs data and writes a data access method: AssetDto GetAssetById(int assetId) A week later someone else is working on another part of the application and also needs an AssetDto but now including 'approvers' and writes the following: AssetDto GetAssetWithApproversById(int assetId) A month later someone needs an asset but now including the 'questions' (or the 'owners' or the 'running requests', etc): AssetDto GetAssetWithQuestionsById(int assetId) AssetDto GetAssetWithOwnersById(int assetId) AssetDto GetAssetWithRunningRequestsById(int assetId) And it gets even worse when methods like GetAssetWithOwnerAndQuestionsById start to appear. You see the pattern that emerges: an object is attached to a large object graph and you need different parts of this graph in different locations. Of course, I'd like to prevent having a large number of methods that do almost the same. Is it simply a matter of team discipline or is there some pattern I can use to prevent this? In some cases it might make sense to have separate methods, i.e. getting an asset with running requests may be expensive so I do not want to include these all the time. How to handle such cases?

    Read the article

  • Use python decorators on class methods and subclass methods

    - by AlexH
    Goal: Make it possible to decorate class methods. When a class method gets decorated, it gets stored in a dictionary so that other class methods can reference it by a string name. Motivation: I want to implement the equivalent of ASP.Net's WebMethods. I am building this on top of google app engine, but that does not affect the point of difficulty that I am having. How it Would look if it worked: class UsefulClass(WebmethodBaseClass): def someMethod(self, blah): print(blah) @webmethod def webby(self, blah): print(blah) # the implementation of this class could be completely different, it does not matter # the only important thing is having access to the web methods defined in sub classes class WebmethodBaseClass(): def post(self, methodName): webmethods[methodName]("kapow") ... a = UsefulClass() a.post("someMethod") # should error a.post("webby") # prints "kapow" There could be other ways to go about this. I am very open to suggestions

    Read the article

  • Information on Rojiani's Numerical methods C textbook

    - by yCalleecharan
    Hi, having taken a look at a few textbooks that discuss numerical methods and C programming, I was gladly surprised when browsing through "programming in C with numerical methods for engineers" by Rojiani. I understand of course it's important that one need to have a solid background in numerical methods prior to try implementing them on a computer. I would like to know if someone here has been using this book and if possible point out strengths and weaknesses of this textbook. Thanks a lot...

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >