Search Results

Search found 18220 results on 729 pages for 'generic programming'.

Page 12/729 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • ViewController in programming

    - by Vishwas Gagrani
    ViewController is a term for classes that handle views in a framework. This is especially used in MVC frameworks. I go through various projects, written by various programmers, who implement MVC in different ways. Especially, i get confused, about the relation between the MainView ( parent view ) and some CustomView ( widget etc) in the framework. I personally pass reference of the MainView into the ViewController to be instantiated. All the subviews of ViewController are added to that reference of MainView. Additionally, ViewController itself is added as a child of MainView. Like this : Want to know, if this is the right way to relate each other ?

    Read the article

  • Are non Turing-complete languages considered programming languages at all?

    - by user1598390
    Reading a recent question: Is it actually possible to have a 'useful' programming language that isn't Turing complete?, I've come to wonder if non Turing-complete programming languages are considered programming languages at all. Since Turing-completeness means a language has to have variables to store values as well as control structures ( for, while )... Is a language that lacks these features considered a programming language ?

    Read the article

  • Structure vs. programming

    - by ChristopherW
    Is it bad that I often find myself spending more time on program structure than actually writing code inside methods? Is this common? I feel I spend more time laying the foundation than actually building the house (metaphorically). While I understand that without a good foundation the house will cave in, but does it legitimately need to take half of the project to finalize code structure? I understand design patterns, and I know where to go if I need help on choosing one, but often I find myself doubting my own choices.

    Read the article

  • General List of Common Programming Errors

    - by javamonkey79
    As one journey's from apprentice to journeyman to master I've noticed that one accumulates a list of best practices for things they've been bitten by. Personally, I write most of my stuff in java & SQL so my list tends to be slated towards them. I've accumulated the following: When doing list removal, always reverse iterate Avoid adding items to a list you are currently iterating on Watch out for NullPointerExceptions Now, I know there are language specific "common errors" links out there like this one. And I'm also aware of the pragmatic programmer tips, Martin Fowler's "code smells". Does anyone know of any good lists out there of things like I've listed above (re: list removal, adding items, etc). My guess is that there are some good QA folks out there that can probably throw me a bone here. I'm not looking for things the compiler can catch - I'm looking for common things that cause bugs. In the event that there isn't a list out there already then I welcome posting your own findings here. Thanks in advance!

    Read the article

  • how to really master a programming language

    - by cprogcr
    I know that learning a language, you can simply buy a book, follow the examples, and whenever possible try the exercises. But what I'm really looking is how to master the language once you've learned it. Now I know that experience is one major factor, but what about learning the internals of the language, what is the underlying structure, etc. There are articles out there saying read this book, read that book, make this game and that game. But to me this doesn't mean to master a language. I want to be able to read other people's code and understand it, no matter how hard that is. To understand when to use a function and when another, etc etc. The list could go on and on but I believe I've made the point. :) And finally, take whatever language as an example if needed, though best would be if C was taken as an example.

    Read the article

  • Why are there different programming languages [closed]

    - by Velizar Hristov
    I'm not asking about the usefulness of the languages that do exist already: I already know, and agree, that different languages are better for different purposes. However, why don't they just have a single language that can do it all? Why, when C# was created, they didn't keep everything from C and C++ and just add a few things, so that it can be used as both a low-level and high-level language? I see no harm in adding all kinds of commands to a single language that would allow it to be good for everything, and even eliminate the need for all other languages. Someone from another thread said that if there's a flaw in a certain language, its successor might not have it. However, why don't we just update that language to remove the flaw, and/or add anything that's missing? Arrays are different in Java and C#, but why not have them both, just use different commands for them? And so on...

    Read the article

  • Event Driven Programming 101

    - by JHarley1
    Good Morning, I previously asked the Q. of how Event Handlers Work (which I got a great answer for). I would now like to understand the basics of how are events are associated with on-screen objects? An explanation of how Events are associated with on Screen Objects: The application registers the Event, the Event Handler and the Component with the GUI Server. When an Event is detected the GUI Server has to link an Event to a Window and then to a Component, it then consults the Event / Component Table to identify which Handler (s) to be executed. I am having problems finding resources/papers that have mention of this process - especially of a Event / Component Table - can anyone clarify?

    Read the article

  • Which ebook format is better to read programming books on ipad [closed]

    - by user1713836
    I tried reading the pdf books on ipad but i don't feel cpmfortable after reading 40 odd pages. don't know why. I just want to know is there any other format which can sooth the eys and behave exactly like hard books. Any other ebooks reader which is better than ipad. But iwant the color display of code syntax as well I am fed up of printing the pdfs as every few months we have new documentation of new version of softwares

    Read the article

  • Question on methods in Object Oriented Programming

    - by mal
    I’m learning Java at the minute (first language), and as a project I’m looking at developing a simple puzzle game. My question relates to the methods within a class. I have my Block type class; it has its many attributes, set methods, get methods and just plain methods. There are quite a few. Then I have my main board class. At the moment it does most of the logic, positioning of sprites collision detection and then draws the sprites etc... As I am learning to program as much as I’m learning to program games I’m curious to know how much code is typically acceptable within a given method. Is there such thing as having too many methods? All my draw functionality happens in one method, should I break this into a few ‘sub’ methods? My thinking is if I find at a later stage that the for loop I’m using to cycle through the array of sprites searching for collisions in the spriteCollision() method is inefficient I code a new method and just replace the old method calls with the new one, leaving the old code intact. Is it bad practice to have a method that contains one if statement, and place the call for that method in the for loop? I’m very much in the early stages of coding/designing and I need all the help I can get! I find it a little intimidating when people are talking about throwing together a prototype in a day too! Can’t wait until I’m that good!

    Read the article

  • A completely free and open programming language

    - by XGouchet
    With Oracle vs Google trial, it seems that Java is not entirely Open and free (as free software) as I expected. Although there exists completely free/open JVM, it's hard to know what is a copyright infringement with Java, and what is not. So I'd like to know if there is a completely Open and free language with open and free IDE (Eclipse-like) out there, Object Oriented if possible, and able to make window-based applications for the main OSs (Linux, Mac, Windows).

    Read the article

  • Why do programming language (open) standards cost money?

    - by fish
    Isn't it counter-productive to ask for 384 Swiss franks for C11 or 352 Swiss franks for C++11, if the aim is to make the standards widely adopted? Please note, I'm not ranting at all, and I'm not against paying; I would like to understand the rationale behind setting the prices as such, especially knowing that ISO is network of national standard institutes (i.e. funded by governments). And I also doubt that these prices would generate enough income to fund an organization like that, so there must be another reason.

    Read the article

  • Functional Programming, JavaScript and UI - some neophyte questions

    - by jamesson
    This has been discussed in other threads, however I am hoping for some comments relevant to UI and an explanation of some vitriol I had flung my way in a Certain IRC Channel Which shall remain nameless. In the discussion here, the comments in the accepted answer suggest that I approach the given code from a functional perspective, which was new to me at the time. Wikipedia said, among other things, that FP "avoids state and mutable data", which includes according to the discussion global vars. Now, being that I am already pretty far along in my project I am not going to learn FP before I finish, but... How is it possible to avoid global vars if, for instance, I have a UI whose entire functionality changes if a mousebutton is down? I have a number of things like this. Why was there a strong negative reaction in the Certain IRC channel to implementing FP in JS? When I Brought up what seemed to me to be supportive comments by Crockford, people got even madder. Now, this being IRC there is no rep system, but they at least gave indication of having read TGP (which I haven't gotten to yet) so I'm assuming they're not idiots. Many thanks in advance Joe

    Read the article

  • How can I really master a programming language?

    - by cprogcr
    I know that learning a language, you can simply buy a book, follow the examples, and whenever possible try the exercises. But what I'm really looking is how to master the language once you've learned it. Now I know that experience is one major factor, but what about learning the internals of the language, what is the underlying structure, etc. There are articles out there saying read this book, read that book, make this game and that game. But to me this doesn't mean to master a language. I want to be able to read other people's code and understand it, no matter how hard that is. To understand when to use a function and when another, etc etc. The list could go on and on but I believe I've made the point. :) And finally, take whatever language as an example if needed, though best would be if C was taken as an example.

    Read the article

  • Why use other number bases when programming

    - by JMD
    My coworkers and I have been bending our minds to figuring out why anyone would go out of their way to program numbers in a base other than base 10. I suggested that perhaps you could optimize longer equations by putting the variables in the correct base you are working with (for instance, if you have only sets of 5 of something with no remainders you could use base 5), but I'm not sure if that's true. Any thoughts?

    Read the article

  • New to Java Programming - Error help

    - by JJJ
    I am going through a Java book and drafting the examples and have run into the following error when compiling this code. Any help would be appreciated thank you. Error: Main.java:3: class Addition is public, should be declared in a file named Addition.java public class Addition        ^ 1 error Code: import java.io.*; import java.util.Scanner; public class Addition {   public static void main(String[] args) { java.util.Scanner input = new java.util.Scanner(System.in);  int number1; int number2; int sum; System.out.print( "Enter first digit: " ); number1 = input.nextInt(); System.out.print( "Enter second digit:" ); number2 = input.nextInt(); sum = number1 + number2; System.out.printf( "Sum is %d\n, sum" );      } }

    Read the article

  • Choosing a new programming language to learn [on hold]

    - by Xelom
    I'm a Microsoft Stack(ASP.NET, C#) developer. Mainly, I develop server side software, windows services, restful apis etc. My client side interaction is really really low. So aside from C# I want to learn a new language. Time is precious and I want to give my focus to a language which have a future. My language list is: Scala (Powerful usage in Twitter) Go (Getting popular and channels are pretty awesome) Erlang (Stable server side programs. Used at Whatsapp) You can give advice for the above or you can give me a better option. My only exception is Objective-C. I don't want to get in that one. Thanks

    Read the article

  • Programming in R help

    - by mary
    I needed help in converting the temperature from Farenheit to Celsius. Below are several attempts and each of these fails. I have ran the following below and need help in saying what error message is created by: a) (temp -32) Can you please let me know the error message in a comment, and what it means and how to directly relate the wording of the error message with the problem you find in the expression. likewise for: b) (temp - 32)5/9 don't know the erorr on this one c) 5/9(temp - 32) need an asterisk, but not specific enough d) [temp - 32]5/9 I know braces is off.

    Read the article

  • Stats on programming languages usage

    - by sameold
    I'm doing some research for a project and I'm trying to find out what are the 5 most-used server-side languages. I found this chart (http://i.stack.imgur.com/vPXgR.jpg) on css-tricks.com (produced from a poll the site owner ran), but in the comments, some suggested that the poll may be skewed in favor of php because most of the site visitors are designers. I'm not sure if this chart looks realistic. Does anyone know of similar stats?

    Read the article

  • Is aspect oriented programming a misnomer?

    - by glenviewjeff
    From everything I have learned about "Aspect Oriented Programming" or "Aspect Oriented Software Development," labeling it as a programming paradigm or methodology appears to be inaccurate. From what I can tell it is not a fundamental technique for programming. To nail down what is meant by "paradigm" and "methodology," please refer to the following definitions from the American Heritage Dictionary. Compare how well or poorly "Object-Oriented Programming" applies to each vs. how well AOP fits. Paradigm: A set of assumptions, concepts, values, and practices that constitutes a way of viewing reality for the community that shares them, especially in an intellectual discipline. Methodology: A body of practices, procedures, and rules used by those who work in a discipline or engage in an inquiry; a set of working methods. "Evidence-based medicine" satisfies the definition of paradigm, but "hysterectomy-based medicine" would be a misnomer because the problem space is too narrow. I am getting the impression that AOP may be misnamed because based on the "oriented-programming" suffix, AOP is alleging to be both a paradigm and a methodology in the same way "Object-Oriented Programming" is. Both of these terms (paradigm and methodology) indicate a fundamental technique, where what I understand about aspects is a technology for solving a narrow problem scope, maybe comparable in magnitude to the static variable feature of Java. If it's true that aspects solve a narrow set of problems, and AOP isn't a misnomer, then why shouldn't all programming techniques be given the "oriented-programming" suffix, such as "inheritance-oriented programming," "dependency-oriented programming," or "scope-oriented programming?"

    Read the article

  • Help with understanding generic relations in Django (and usage in Admin)

    - by saturdayplace
    I'm building a CMS for my company's website (I've looked at the existing Django solutions and want something that's much slimmer/simpler, and that handles our situation specifically.. Plus, I'd like to learn this stuff better). I'm having trouble wrapping my head around generic relations. I have a Page model, a SoftwareModule model, and some other models that define content on our website, each with their get_absolute_url() defined. I'd like for my users to be able to assign any Page instance a list of objects, of any type, including other page instances. This list will become that Page instance's sub-menu. I've tried the following: class Page(models.Model): body = models.TextField() links = generic.GenericRelation("LinkedItem") @models.permalink def get_absolute_url(self): # returns the right URL class LinkedItem(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') title = models.CharField(max_length=100) def __unicode__(self): return self.title class SoftwareModule(models.Model): name = models.CharField(max_length=100) description = models.TextField() def __unicode__(self): return self.name @models.permalink def get_absolute_url(self): # returns the right URL This gets me a generic relation with an API to do page_instance.links.all(). We're on our way. What I'm not sure how to pull off, is on the page instance's change form, how to create the relationship between that page, and any other extant object in the database. My desired end result: to render the following in a template: <ul> {% for link in page.links.all %} <li><a href='{{ link.content_object.get_absolute_url() }}'>{{ link.title }}</a></li> {% endfor%} </ul> Obviously, there's something I'm unaware of or mis-understanding, but I feel like I'm, treading into that area where I don't know what I don't know. What am I missing?

    Read the article

  • C#/.NET Little Wonders: The Generic Func Delegates

    - by James Michael Hare
    Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. Back in one of my three original “Little Wonders” Trilogy of posts, I had listed generic delegates as one of the Little Wonders of .NET.  Later, someone posted a comment saying said that they would love more detail on the generic delegates and their uses, since my original entry just scratched the surface of them. Last week, I began our look at some of the handy generic delegates built into .NET with a description of delegates in general, and the Action family of delegates.  For this week, I’ll launch into a look at the Func family of generic delegates and how they can be used to support generic, reusable algorithms and classes. Quick Delegate Recap Delegates are similar to function pointers in C++ in that they allow you to store a reference to a method.  They can store references to either static or instance methods, and can actually be used to chain several methods together in one delegate. Delegates are very type-safe and can be satisfied with any standard method, anonymous method, or a lambda expression.  They can also be null as well (refers to no method), so care should be taken to make sure that the delegate is not null before you invoke it. Delegates are defined using the keyword delegate, where the delegate’s type name is placed where you would typically place the method name: 1: // This delegate matches any method that takes string, returns nothing 2: public delegate void Log(string message); This delegate defines a delegate type named Log that can be used to store references to any method(s) that satisfies its signature (whether instance, static, lambda expression, etc.). Delegate instances then can be assigned zero (null) or more methods using the operator = which replaces the existing delegate chain, or by using the operator += which adds a method to the end of a delegate chain: 1: // creates a delegate instance named currentLogger defaulted to Console.WriteLine (static method) 2: Log currentLogger = Console.Out.WriteLine; 3:  4: // invokes the delegate, which writes to the console out 5: currentLogger("Hi Standard Out!"); 6:  7: // append a delegate to Console.Error.WriteLine to go to std error 8: currentLogger += Console.Error.WriteLine; 9:  10: // invokes the delegate chain and writes message to std out and std err 11: currentLogger("Hi Standard Out and Error!"); While delegates give us a lot of power, it can be cumbersome to re-create fairly standard delegate definitions repeatedly, for this purpose the generic delegates were introduced in various stages in .NET.  These support various method types with particular signatures. Note: a caveat with generic delegates is that while they can support multiple parameters, they do not match methods that contains ref or out parameters. If you want to a delegate to represent methods that takes ref or out parameters, you will need to create a custom delegate. We’ve got the Func… delegates Just like it’s cousin, the Action delegate family, the Func delegate family gives us a lot of power to use generic delegates to make classes and algorithms more generic.  Using them keeps us from having to define a new delegate type when need to make a class or algorithm generic. Remember that the point of the Action delegate family was to be able to perform an “action” on an item, with no return results.  Thus Action delegates can be used to represent most methods that take 0 to 16 arguments but return void.  You can assign a method The Func delegate family was introduced in .NET 3.5 with the advent of LINQ, and gives us the power to define a function that can be called on 0 to 16 arguments and returns a result.  Thus, the main difference between Action and Func, from a delegate perspective, is that Actions return nothing, but Funcs return a result. The Func family of delegates have signatures as follows: Func<TResult> – matches a method that takes no arguments, and returns value of type TResult. Func<T, TResult> – matches a method that takes an argument of type T, and returns value of type TResult. Func<T1, T2, TResult> – matches a method that takes arguments of type T1 and T2, and returns value of type TResult. Func<T1, T2, …, TResult> – and so on up to 16 arguments, and returns value of type TResult. These are handy because they quickly allow you to be able to specify that a method or class you design will perform a function to produce a result as long as the method you specify meets the signature. For example, let’s say you were designing a generic aggregator, and you wanted to allow the user to define how the values will be aggregated into the result (i.e. Sum, Min, Max, etc…).  To do this, we would ask the user of our class to pass in a method that would take the current total, the next value, and produce a new total.  A class like this could look like: 1: public sealed class Aggregator<TValue, TResult> 2: { 3: // holds method that takes previous result, combines with next value, creates new result 4: private Func<TResult, TValue, TResult> _aggregationMethod; 5:  6: // gets or sets the current result of aggregation 7: public TResult Result { get; private set; } 8:  9: // construct the aggregator given the method to use to aggregate values 10: public Aggregator(Func<TResult, TValue, TResult> aggregationMethod = null) 11: { 12: if (aggregationMethod == null) throw new ArgumentNullException("aggregationMethod"); 13:  14: _aggregationMethod = aggregationMethod; 15: } 16:  17: // method to add next value 18: public void Aggregate(TValue nextValue) 19: { 20: // performs the aggregation method function on the current result and next and sets to current result 21: Result = _aggregationMethod(Result, nextValue); 22: } 23: } Of course, LINQ already has an Aggregate extension method, but that works on a sequence of IEnumerable<T>, whereas this is designed to work more with aggregating single results over time (such as keeping track of a max response time for a service). We could then use this generic aggregator to find the sum of a series of values over time, or the max of a series of values over time (among other things): 1: // creates an aggregator that adds the next to the total to sum the values 2: var sumAggregator = new Aggregator<int, int>((total, next) => total + next); 3:  4: // creates an aggregator (using static method) that returns the max of previous result and next 5: var maxAggregator = new Aggregator<int, int>(Math.Max); So, if we were timing the response time of a web method every time it was called, we could pass that response time to both of these aggregators to get an idea of the total time spent in that web method, and the max time spent in any one call to the web method: 1: // total will be 13 and max 13 2: int responseTime = 13; 3: sumAggregator.Aggregate(responseTime); 4: maxAggregator.Aggregate(responseTime); 5:  6: // total will be 20 and max still 13 7: responseTime = 7; 8: sumAggregator.Aggregate(responseTime); 9: maxAggregator.Aggregate(responseTime); 10:  11: // total will be 40 and max now 20 12: responseTime = 20; 13: sumAggregator.Aggregate(responseTime); 14: maxAggregator.Aggregate(responseTime); The Func delegate family is useful for making generic algorithms and classes, and in particular allows the caller of the method or user of the class to specify a function to be performed in order to generate a result. What is the result of a Func delegate chain? If you remember, we said earlier that you can assign multiple methods to a delegate by using the += operator to chain them.  So how does this affect delegates such as Func that return a value, when applied to something like the code below? 1: Func<int, int, int> combo = null; 2:  3: // What if we wanted to aggregate the sum and max together? 4: combo += (total, next) => total + next; 5: combo += Math.Max; 6:  7: // what is the result? 8: var comboAggregator = new Aggregator<int, int>(combo); Well, in .NET if you chain multiple methods in a delegate, they will all get invoked, but the result of the delegate is the result of the last method invoked in the chain.  Thus, this aggregator would always result in the Math.Max() result.  The other chained method (the sum) gets executed first, but it’s result is thrown away: 1: // result is 13 2: int responseTime = 13; 3: comboAggregator.Aggregate(responseTime); 4:  5: // result is still 13 6: responseTime = 7; 7: comboAggregator.Aggregate(responseTime); 8:  9: // result is now 20 10: responseTime = 20; 11: comboAggregator.Aggregate(responseTime); So remember, you can chain multiple Func (or other delegates that return values) together, but if you do so you will only get the last executed result. Func delegates and co-variance/contra-variance in .NET 4.0 Just like the Action delegate, as of .NET 4.0, the Func delegate family is contra-variant on its arguments.  In addition, it is co-variant on its return type.  To support this, in .NET 4.0 the signatures of the Func delegates changed to: Func<out TResult> – matches a method that takes no arguments, and returns value of type TResult (or a more derived type). Func<in T, out TResult> – matches a method that takes an argument of type T (or a less derived type), and returns value of type TResult(or a more derived type). Func<in T1, in T2, out TResult> – matches a method that takes arguments of type T1 and T2 (or less derived types), and returns value of type TResult (or a more derived type). Func<in T1, in T2, …, out TResult> – and so on up to 16 arguments, and returns value of type TResult (or a more derived type). Notice the addition of the in and out keywords before each of the generic type placeholders.  As we saw last week, the in keyword is used to specify that a generic type can be contra-variant -- it can match the given type or a type that is less derived.  However, the out keyword, is used to specify that a generic type can be co-variant -- it can match the given type or a type that is more derived. On contra-variance, if you are saying you need an function that will accept a string, you can just as easily give it an function that accepts an object.  In other words, if you say “give me an function that will process dogs”, I could pass you a method that will process any animal, because all dogs are animals.  On the co-variance side, if you are saying you need a function that returns an object, you can just as easily pass it a function that returns a string because any string returned from the given method can be accepted by a delegate expecting an object result, since string is more derived.  Once again, in other words, if you say “give me a method that creates an animal”, I can pass you a method that will create a dog, because all dogs are animals. It really all makes sense, you can pass a more specific thing to a less specific parameter, and you can return a more specific thing as a less specific result.  In other words, pay attention to the direction the item travels (parameters go in, results come out).  Keeping that in mind, you can always pass more specific things in and return more specific things out. For example, in the code below, we have a method that takes a Func<object> to generate an object, but we can pass it a Func<string> because the return type of object can obviously accept a return value of string as well: 1: // since Func<object> is co-variant, this will access Func<string>, etc... 2: public static string Sequence(int count, Func<object> generator) 3: { 4: var builder = new StringBuilder(); 5:  6: for (int i=0; i<count; i++) 7: { 8: object value = generator(); 9: builder.Append(value); 10: } 11:  12: return builder.ToString(); 13: } Even though the method above takes a Func<object>, we can pass a Func<string> because the TResult type placeholder is co-variant and accepts types that are more derived as well: 1: // delegate that's typed to return string. 2: Func<string> stringGenerator = () => DateTime.Now.ToString(); 3:  4: // This will work in .NET 4.0, but not in previous versions 5: Sequence(100, stringGenerator); Previous versions of .NET implemented some forms of co-variance and contra-variance before, but .NET 4.0 goes one step further and allows you to pass or assign an Func<A, BResult> to a Func<Y, ZResult> as long as A is less derived (or same) as Y, and BResult is more derived (or same) as ZResult. Sidebar: The Func and the Predicate A method that takes one argument and returns a bool is generally thought of as a predicate.  Predicates are used to examine an item and determine whether that item satisfies a particular condition.  Predicates are typically unary, but you may also have binary and other predicates as well. Predicates are often used to filter results, such as in the LINQ Where() extension method: 1: var numbers = new[] { 1, 2, 4, 13, 8, 10, 27 }; 2:  3: // call Where() using a predicate which determines if the number is even 4: var evens = numbers.Where(num => num % 2 == 0); As of .NET 3.5, predicates are typically represented as Func<T, bool> where T is the type of the item to examine.  Previous to .NET 3.5, there was a Predicate<T> type that tended to be used (which we’ll discuss next week) and is still supported, but most developers recommend using Func<T, bool> now, as it prevents confusion with overloads that accept unary predicates and binary predicates, etc.: 1: // this seems more confusing as an overload set, because of Predicate vs Func 2: public static SomeMethod(Predicate<int> unaryPredicate) { } 3: public static SomeMethod(Func<int, int, bool> binaryPredicate) { } 4:  5: // this seems more consistent as an overload set, since just uses Func 6: public static SomeMethod(Func<int, bool> unaryPredicate) { } 7: public static SomeMethod(Func<int, int, bool> binaryPredicate) { } Also, even though Predicate<T> and Func<T, bool> match the same signatures, they are separate types!  Thus you cannot assign a Predicate<T> instance to a Func<T, bool> instance and vice versa: 1: // the same method, lambda expression, etc can be assigned to both 2: Predicate<int> isEven = i => (i % 2) == 0; 3: Func<int, bool> alsoIsEven = i => (i % 2) == 0; 4:  5: // but the delegate instances cannot be directly assigned, strongly typed! 6: // ERROR: cannot convert type... 7: isEven = alsoIsEven; 8:  9: // however, you can assign by wrapping in a new instance: 10: isEven = new Predicate<int>(alsoIsEven); 11: alsoIsEven = new Func<int, bool>(isEven); So, the general advice that seems to come from most developers is that Predicate<T> is still supported, but we should use Func<T, bool> for consistency in .NET 3.5 and above. Sidebar: Func as a Generator for Unit Testing One area of difficulty in unit testing can be unit testing code that is based on time of day.  We’d still want to unit test our code to make sure the logic is accurate, but we don’t want the results of our unit tests to be dependent on the time they are run. One way (of many) around this is to create an internal generator that will produce the “current” time of day.  This would default to returning result from DateTime.Now (or some other method), but we could inject specific times for our unit testing.  Generators are typically methods that return (generate) a value for use in a class/method. For example, say we are creating a CacheItem<T> class that represents an item in the cache, and we want to make sure the item shows as expired if the age is more than 30 seconds.  Such a class could look like: 1: // responsible for maintaining an item of type T in the cache 2: public sealed class CacheItem<T> 3: { 4: // helper method that returns the current time 5: private static Func<DateTime> _timeGenerator = () => DateTime.Now; 6:  7: // allows internal access to the time generator 8: internal static Func<DateTime> TimeGenerator 9: { 10: get { return _timeGenerator; } 11: set { _timeGenerator = value; } 12: } 13:  14: // time the item was cached 15: public DateTime CachedTime { get; private set; } 16:  17: // the item cached 18: public T Value { get; private set; } 19:  20: // item is expired if older than 30 seconds 21: public bool IsExpired 22: { 23: get { return _timeGenerator() - CachedTime > TimeSpan.FromSeconds(30.0); } 24: } 25:  26: // creates the new cached item, setting cached time to "current" time 27: public CacheItem(T value) 28: { 29: Value = value; 30: CachedTime = _timeGenerator(); 31: } 32: } Then, we can use this construct to unit test our CacheItem<T> without any time dependencies: 1: var baseTime = DateTime.Now; 2:  3: // start with current time stored above (so doesn't drift) 4: CacheItem<int>.TimeGenerator = () => baseTime; 5:  6: var target = new CacheItem<int>(13); 7:  8: // now add 15 seconds, should still be non-expired 9: CacheItem<int>.TimeGenerator = () => baseTime.AddSeconds(15); 10:  11: Assert.IsFalse(target.IsExpired); 12:  13: // now add 31 seconds, should now be expired 14: CacheItem<int>.TimeGenerator = () => baseTime.AddSeconds(31); 15:  16: Assert.IsTrue(target.IsExpired); Now we can unit test for 1 second before, 1 second after, 1 millisecond before, 1 day after, etc.  Func delegates can be a handy tool for this type of value generation to support more testable code.  Summary Generic delegates give us a lot of power to make truly generic algorithms and classes.  The Func family of delegates is a great way to be able to specify functions to calculate a result based on 0-16 arguments.  Stay tuned in the weeks that follow for other generic delegates in the .NET Framework!   Tweet Technorati Tags: .NET, C#, CSharp, Little Wonders, Generics, Func, Delegates

    Read the article

  • How much is modern programming still tied to underyling digital logic?

    - by New Talk
    First of all: I've got no academic background. I'm working primarily with Java and Spring and I'm also fond of web programming and relational databases. I hope I'm using the right terms and I hope that this vague question makes some sense. Today the following question came to my mind: How much is modern programming still tied to the underlying digital logic? With modern programming I mean concepts like OOP, AOP, Java 7, AJAX, … I hope you get the idea. Do they no longer need the digital logic with which computers are working internally? Or is binary logic still ubiquitous when programming this way? If I'd change the inner workings of a computer overnight, would it matter, because my programming techniques are already that abstract? P. S.: With digital logic I mean the physical representation of everything "inside" the computer as zeroes and ones. Changed "binary" to "digital".

    Read the article

  • Which language and platform features really boosted your coding speed?

    - by Serge
    The question is about delivering working code faster without any regard for design, quality, maintainability, etc. Here is the list of things that help me to write and read code faster: Language: static typing, support for object-oriented and functional programming styles, embedded documentation, short compile-debug-fix cycle or REPL, automatic memory management Platform: "batteries" included (text, regex, IO, threading, networking), thriving community, tons of open-source libs Tools: IDE, visual debugger, code-completion, code navigation, refactoring

    Read the article

  • Complete Math Library for use in OpenGL ES 2.0 Game?

    - by Bunkai.Satori
    Are you aware of a complete (or almost complete) cross platform math library for use in OpenGL ES 2.0 games? The library should contain: Matrix2x2, Matrix 3x3, Matrix4x4 classes Quaternions Vector2, Vector3, Vector4 Classes Euler Angle Class Operations amongh the above mentioned classes, conversions, etc.. Standardly used math operations in 3D graphics (Dot Product, Cross Product, SLERP, etc...) Is there such Math API available either standalone or as a part of any package? Programming Language: Visual C++ but planned to be ported to OS X and Android OS.

    Read the article

  • Collect all extension methods to generic class in another generic class

    - by Hun1Ahpu
    I'd like to create a lot of extension methods for some generic class, e.g. for public class SimpleLinkedList<T> where T:IComparable And I've started creating methods like this: public static class LinkedListExtensions { public static T[] ToArray<T>(this SimpleLinkedList<T> simpleLinkedList) where T:IComparable { //// code } } But when I tried to make LinkedListExtensions class generic like this: public static class LinkedListExtensions<T> where T:IComparable { public static T[] ToArray(this SimpleLinkedList<T> simpleLinkedList) { ////code } } I get "Extension methods can only be declared in non-generic, non-nested static class". And I'm trying to guess where this restriction came from and have no ideas.

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >