Search Results

Search found 30234 results on 1210 pages for 'object oriented'.

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

  • How to design this procedural application into object oriented format?

    - by DavidL
    I'm building an application that basically pulls json data from a bunch of websites, processes it in some way and then writes it to a file. It is very easy to write this in a procedural way. I was wondering how this could be done in an object oriented way. Currently, the application looks something like this: res = get_json(link); process(res); write(res); Even if writing this in an object oriented way is not the best idea, tell me how it could be done because I have trouble with it.

    Read the article

  • JS closures - Passing a function to a child, how should the shared object be accessed

    - by slicedtoad
    I have a design and am wondering what the appropriate way to access variables is. I'll demonstrate with this example since I can't seem to describe it better than the title. Term is an object representing a bunch of time data (a repeating duration of time defined by a bunch of attributes) Term has some print functionality but does not implement the print functions itself, rather they are passed in as anonymous functions by the parent. This would be similar to how shaders can be passed to a renderer rather than defined by the renderer. A container (let's call it Box) has a Schedule object that can understand and use Term objects. Box creates Term objects and passes them to Schedule as required. Box also defines the print functions stored in Term. A print function usually takes an argument and uses it to return a string based on that argument and Term's internal data. Sometime the print function could also use data stored in Schedule, though. I'm calling this data shared. So, the question is, what is the best way to access this shared data. I have a lot of options since JS has closures and I'm not familiar enough to know if I should be using them or avoiding them in this case. Options: Create a local "reference" (term used lightly) to the shared data (data is not a primitive) when defining the print function by accessing the shared data through Schedule from Box. Example: var schedule = function(){ var sched = Schedule(); var t1 = Term( function(x){ // Term.print() return (x + sched.data).format(); }); }; Bind it to Term explicitly. (Pass it in Term's constructor or something). Or bind it in Sched after Box passes it. And then access it as an attribute of Term. Pass it in at the same time x is passed to the print function, (from sched). This is the most familiar way for my but it doesn't feel right given JS's closure ability. Do something weird like bind some context and arguments to print. I'm hoping the correct answer isn't purely subjective. If it is, then I guess the answer is just "do whatever works". But I feel like there are some significant differences between the approaches that could have a large impact when stretched beyond my small example.

    Read the article

  • Criteria for a language to be considered "object oriented"

    - by nist
    I had a discussion about OO programming today and by browsing the internet I found a lot of different specifications for object oriented languages. What are the requirements for a language to be object oriented? For myself an object oriented language must have classes, inheritance and encapsulation. Is C an object oriented language just because you can use structs and program with an object oriented design? Why/ why not? Are there any good sites/articles about this? And please, no Wikipedia links because I've already been there.

    Read the article

  • parse [object XrayWrapper [object HTMLLIElement]] into HTML object

    - by kitokid
    when I access and GM_log the currentLi of li object, it is complaining undefined. So when I GM_log li value as a string , instead of HTML object, I am getting [object XrayWrapper [object HTMLLIElement]]. How can I convert it or how I can access its related elements and value ? $("#result-set li").each(function(index) { var $currentLi = $(this); var $class1link = $currentLi.find("class1"); var $class1href = $class1link.attr("href"); }

    Read the article

  • Using dot To Access Object Attribute and Proper abstraction

    - by cobie
    I have been programming in python and java for quite a number of years and one thing i find myself doing is using the setters and getters from java in python but a number of blogs seem to think using the dot notation for access is the pythonic way. What I would like to know is if using dot to access methods does not violate abstraction principle. If for example I implement an attribute as a single object and use dot notation to access, if I wanted to change the code later so that the attribute is represented by a list of objects, that would require quite some heavy lifting which violates abstraction principle.

    Read the article

  • Handling array passed to object at creation

    - by cecilli0n
    When creating my object I pass it an array of a row from my database. (everything in the array we will need, disregarding unnecessary elements at sql query level) When I need to access certain array elements from within my class, I do so like $this->row['element'] However, As I continue development, I sometimes forget what exactly is in this passed array.(this itself doesn't seem good) I am wondering if their is a professional approach to dealing with this, Or am I the only one who has these "I wonder whats in the array" thoughts. One approach to tackling this could be that when we originally pass the array, in the constructor, we assign each element of the array to its own variable, but is this considered professional practice? Additionally by doing this, we could make those variables constants, in a attempt at immutability. Overall I am trying to adhere to good software craftsmanship. Regards.

    Read the article

  • "Best fit" to avoid reuse of object instances in a collection

    - by Simon
    Imagine I have a collection of object instances which represent activities for a user to undertake. Dependent on user attributes, I have to randomly select instances to present activities to the user. For some users, I need to present more activities to them than there are available activities in which case, I want to use the following algorithm. If all available activities have already been presented to the user, then re-select a "used" activity, selecting the earliest presented activity ordered by frequency of use. In other words, try to reduce repetition and where repetition is unavoidable, use the instances which have been repeated less often and were presented furthest back in time. Before I go on to code that algorithm, I wondered if there is some existing pattern I can re-use? [EDIT] "Furthest back in time" is not relevant as I will pass the algorithm an ordered collection of used instances where the first entry is the first presented.

    Read the article

  • Why am I seeing so many instantiable classes without state?

    - by futlib
    I'm seeing a lot of instantiable classes in the C++ and Java world that don't have any state. I really can't figure out why people do that, they could just use a namespace with free functions in C++, or a class with a private constructor and only static methods in Java. The only benefit I can think of is that you don't have to change most of your code if you later decide that you want a different implementation in certain situations. But isn't that a case of premature design? It could be turned into a class later, when/if it becomes appropriate. Am I getting this wrong? Is it not OOP if I don't put everything into objects (i.e. instantiated classes)? Then why are there so many utility namespaces and classes in the standard libraries of C++ and Java? Update: I've certainly seen a lot examples of this in my previous jobs, but I'm struggling to find open source examples, so maybe it's not that common after all. Still, I'm wondering why people do it, and how common it is.

    Read the article

  • Console.log in IE on an object just outputted [object Object]

    - by LookitsPuck
    All, I'm used to debugging JavaScript in Chrome or Firefox just because their built in developer tools are a lot cleaner than IE's. IE8 came along way with the Developer Tools being more polished, but they're still not completely up to snuff. I like being able to step through code as if I was in Visual Studio, and that is pretty nice about IE, however, when trying to do a simple console.log on an object that I have, in Firefox/Chrome/etc. I can actually explore that object. In IE, the console is simply outputting the following: LOG: [object Object] Is there any way to drill down into that object in IE like in Chrome/Firefox/etc.? Thanks all! -Steve

    Read the article

  • Difference between null==object and object==null

    - by priyank.mp
    Hi I would like to know diff between the above comparisons? I am getting null pointer exception when I check object.getItems() == null. But if I change it to null == object.getItems(), it workes fine. I did look into this http://stackoverflow.com/questions/2938476/what-is-the-difference-between-null-object-and-objectnull-closed But I didnt get satisfactory answer.

    Read the article

  • REST API wrapper - class design for 'lite' object responses

    - by sasfrog
    I am writing a class library to serve as a managed .NET wrapper over a REST API. I'm very new to OOP, and this task is an ideal opportunity for me to learn some OOP concepts in a real-life situation that makes sense to me. Some of the key resources/objects that the API returns are returned with different levels of detail depending on whether the request is for a single instance, a list, or part of a "search all resources" response. This is obviously a good design for the REST API itself, so that full objects aren't returned (thus increasing the size of the response and therefore the time taken to respond) unless they're needed. So, to be clear: .../car/1234.json returns the full Car object for 1234, all its properties like colour, make, model, year, engine_size, etc. Let's call this full. .../cars.json returns a list of Car objects, but only with a subset of the properties returned by .../car/1234.json. Let's call this lite. ...search.json returns, among other things, a list of car objects, but with minimal properties (only ID, make and model). Let's call this lite-lite. I want to know what the pros and cons of each of the following possible designs are, and whether there is a better design that I haven't covered: Create a Car class that models the lite-lite properties, and then have each of the more detailed responses inherit and extend this class. Create separate CarFull, CarLite and CarLiteLite classes corresponding to each of the responses. Create a single Car class that contains (nullable?) properties for the full response, and create constructors for each of the responses which populate it to the extent possible (and maybe include a property that returns the response type from which the instance was created). I expect among other things there will be use cases for consumers of the wrapper where they will want to iterate through lists of Cars, regardless of which response type they were created from, such that the three response types can contribute to the same list. Happy to be pointed to good resources on this sort of thing, and/or even told the name of the concept I'm describing so I can better target my research.

    Read the article

  • bootstrap: Uncaught TypeError: Object [object Object] has no method 'tooltip', 'typeahead'

    - by DarkKnightFan
    I am trying to use the tooltip, typeahead, datepicker features of bootstrap. But I keep getting these errors in the console! Uncaught TypeError: Object [object Object] has no method 'tooltip' Uncaught TypeError: Object [object Object] has no method 'typeahead' This is how my imports look like: <link href="css/bootstrap.css" rel="stylesheet"> <link href="css/datepicker.css" rel="stylesheet"> <link href="css/bootstrap-responsive.css" rel="stylesheet"> <script type="text/javascript" src="js/jquery-1.8.0.js"></script> <script type="text/javascript" src="js/bootstrap.js"></script> <script type="text/javascript" src="js/bootstrap-datepicker.js"></script> <script type="text/javascript" src="js/bootstrap-typeahead.js"></script> <script type="text/javascript" src="js/highcharts.js"></script> <script type="text/javascript" src="js/exporting.js"></script> <link type="text/css" rel="stylesheet" href="css/jquery.dropdown.css" /> <script type="text/javascript" src="js/jquery.dropdown.js"></script> Some sample code: <a class="btn btn-success" data-toggle="modal" href="#payments" rel="tooltip" data-placement="top" title="Record your payments"> <i class="icon-check icon-white"></i> Payments</a> $("#payments").tooltip('show'); Similarly I have code for datepicker and typeahead. any solution?

    Read the article

  • Uncaught TypeError: Property 'dist2' of object [object Object] is not a function

    - by Radu Vlad
    I have this functions that should return me the distance from point p to segment line v-w. The problem i have is after some time i receive the following error: Uncaught TypeError: Property 'dist2' of object [object Object] is not a function. I receive it in distToSegmentSquared directly,not even calling the function dist2().Is it any other dist2() anywhere in jquery?I found none... function sqr(x) { return x * x; } function dist2(v, w) { console.log(v); console.log(w); return sqr(v.x - w.x) + sqr(v.y - w.y); } function distToSegmentSquared(p, v, w) { var l2 = dist2(v, w); if (l2 == 0) return dist2(p, v); var t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2; if (t < 0) return dist2(p, v); if (t > 1) return dist2(p, w); return dist2(p, {x: v.x + t * (w.x - v.x), y: v.y + t * (w.y - v.y)}); } function distToSegment(p, v, w) { return Math.sqrt(distToSegmentSquared(p, v, w)); } The values that are given in for that error are: p: Object x: 461 y: 333 v: Object x: 80 y: 120 w: Object x: 260 y: 120

    Read the article

  • Avoiding Object Oriented Pitfalls, Migrating from C, What Worked for You?

    - by Stephen
    I've been programming in procedural languages for quite some time now, and my first reaction to a problem is to start breaking it down into tasks to perform rather than to consider the different entities (objects) that exist and their relationships. I have had a university course in OOP, and understand the fundamentals of encapsulation, data abstraction, polymorphism, modularity and inheritance. I read Learning to think in the Object Oriented Way and Learning object oriented thinking, and will be looking at some of the books pointed to in those answers. I think that several of my medium to large sized projects will benefit from effective use of OOP but as a novice I would like to avoid time consuming, common errors. Based on your experiences, what are these pitfalls and what are reasonable ways around them? If you could explain why they are pitfalls, and how your suggestion is effective in addressing the issue it'd be appreciated. I'm thinking along the lines of something like "Is it common to have a fair number of observer and modifier methods and use private variables or are there techniques for consolidating/reducing them?" I'm not worried about using C++ as a pure OO language, if there are good reasons to mix methods. (Reminiscent of the reasons to use GOTOs, albeit sparingly.) Thank you!

    Read the article

  • Use a subclass object to modify a protected propety within its superclass object

    - by gadmeer
    Sorry for the crappy title I failed to think of a better version for my Java question. I am right now using Java version: 1.6.0_18 and Netbeans version: 6.8 Now for the question. What I've done is created a class with only one protected int property and next I made a public method to Set the int property to a given value. Then I made an object of that class and used said public method to set the int property to 5. Now I need your help to create another class that will take said object and expose it's protected int property. The way I could think of doing this was to create a sub class to inherit said class and then create a method to Get the int property of the super class. I kind of succeeded to create the code to Get the int property but now I can't figure out how to use this new sub class to reference the object of the super class. Here are the 2 classes I have thus far: public class A { protected int iNumber; public void setNumber ( int aNumber ) { iNumber = aNumber; } } public class B extends A { public int getNumber() { return super.iNumber; } } I created an object of 'A' and used its method to set its property to 5, like this: A objA = new A(); objA.setNumber ( 5 ); Now I want to create an object of 'B' to output the int stored within the property of 'objA'. I've tried to run this code: B objB = (B) objA; String aNumber_String = String.valueOf( objB.getNumber() ); System.out.println( aNumber_String ); but I got the error: "java.lang.ClassCastException" on the first line B objB = (B) objA; Please is there anyway of doing what I am trying to do? P.S. I am hoping to make this idea work because I do not want to edit class A (unless I have no choice) by giving it a getter method. P.P.S Also I know it's a 'bad' idea to expose the property instead of making it private and use public setter / getter methods but I like it this way :). Edit: Added code tags

    Read the article

  • VB.NET - Object reference not set to an instance of an object

    - by Daniel
    I need some help with my program. I get this error when I run my VB.NET program with a custom DayView control. ***** Exception Text ******* System.NullReferenceException: Object reference not set to an instance of an object. at SeaCow.Main.DayView1_ResolveAppointments(Object sender, ResolveAppointmentsEventArgs args) in C:\Users\Daniel\My Programs\Visual Basic\SeaCow\SeaCow\SeaCow\Main.vb:line 120 at Calendar.DayView.OnResolveAppointments(ResolveAppointmentsEventArgs args) at Calendar.DayView.OnPaint(PaintEventArgs e) at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer) at System.Windows.Forms.Control.WmPaint(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) According to the error code, the 'for each' loop below is causing the NullReferenceException error. At default, the 'appointments' list is assigned to nothing and I can't find where the ResolveAppointments function is being called at. Private Sub DayView1_ResolveAppointments(ByVal sender As Object, ByVal args As Calendar.ResolveAppointmentsEventArgs) Handles DayView1.ResolveAppointments Dim m_Apps As New List(Of Calendar.Appointment) For Each m_App As Calendar.Appointment In appointments If (m_App.StartDate >= args.StartDate) AndAlso (m_App.StartDate <= args.EndDate) Then m_Apps.Add(m_App) End If Next args.Appointments = m_Apps End Sub Anyone have any suggestions?

    Read the article

  • which metric(s) show the difference between object-oriented and procedural code

    - by twieger
    Which metric(s) could help to indicate that i have procedural code instead of object-oriented code? I would like to have a set of simple metrics, which indicate with a high probability, that the analyzed code contains procedural transaction scripts and an anemic domain model instead of following sound object-oriented design principles. Would be happy about any set of useful metrics and tools for measuring. Thanks, Thomas!

    Read the article

  • Profile:Object reference not set to an instance of an object

    - by sallalman83
    Hi, i just lunch my web site i used the asp.net routing technology on it, and its work fine in my localhost but when i moved the project to the hosting server(Godaddy.com) its just work fine when there is no virtual sub directories like this(havebreak.com) but when u click on this link (havebreak.com/Registration/) or any other links that contain a virtual sub-directories its give Object reference not set to an instance of an object error on the profile object if (!Profile.IsAnonymous) Line 18: mlvRegistratioin.ActiveViewIndex = 1; i check my IIS settings and found it using the "Integrated pipeline" as recommended (at least at my knowledge), i checked the httpModules and httpHandlers tags under the system.webServer (since my hosting plan use the IIS7) and under the normal tag and every thing is fine then i used the url-rewriting instead of URL-Routing and the same problem exist and i notice that the session also not working in the virtual sub-directories too and by the way the ASP.NET routing work fine with my site its just the profile and session objects that not workin any help will be appreciated

    Read the article

  • Creating a dynamic, extensible C# Expando Object

    - by Rick Strahl
    I love dynamic functionality in a strongly typed language because it offers us the best of both worlds. In C# (or any of the main .NET languages) we now have the dynamic type that provides a host of dynamic features for the static C# language. One place where I've found dynamic to be incredibly useful is in building extensible types or types that expose traditionally non-object data (like dictionaries) in easier to use and more readable syntax. I wrote about a couple of these for accessing old school ADO.NET DataRows and DataReaders more easily for example. These classes are dynamic wrappers that provide easier syntax and auto-type conversions which greatly simplifies code clutter and increases clarity in existing code. ExpandoObject in .NET 4.0 Another great use case for dynamic objects is the ability to create extensible objects - objects that start out with a set of static members and then can add additional properties and even methods dynamically. The .NET 4.0 framework actually includes an ExpandoObject class which provides a very dynamic object that allows you to add properties and methods on the fly and then access them again. For example with ExpandoObject you can do stuff like this:dynamic expand = new ExpandoObject(); expand.Name = "Rick"; expand.HelloWorld = (Func<string, string>) ((string name) => { return "Hello " + name; }); Console.WriteLine(expand.Name); Console.WriteLine(expand.HelloWorld("Dufus")); Internally ExpandoObject uses a Dictionary like structure and interface to store properties and methods and then allows you to add and access properties and methods easily. As cool as ExpandoObject is it has a few shortcomings too: It's a sealed type so you can't use it as a base class It only works off 'properties' in the internal Dictionary - you can't expose existing type data It doesn't serialize to XML or with DataContractSerializer/DataContractJsonSerializer Expando - A truly extensible Object ExpandoObject is nice if you just need a dynamic container for a dictionary like structure. However, if you want to build an extensible object that starts out with a set of strongly typed properties and then allows you to extend it, ExpandoObject does not work because it's a sealed class that can't be inherited. I started thinking about this very scenario for one of my applications I'm building for a customer. In this system we are connecting to various different user stores. Each user store has the same basic requirements for username, password, name etc. But then each store also has a number of extended properties that is available to each application. In the real world scenario the data is loaded from the database in a data reader and the known properties are assigned from the known fields in the database. All unknown fields are then 'added' to the expando object dynamically. In the past I've done this very thing with a separate property - Properties - just like I do for this class. But the property and dictionary syntax is not ideal and tedious to work with. I started thinking about how to represent these extra property structures. One way certainly would be to add a Dictionary, or an ExpandoObject to hold all those extra properties. But wouldn't it be nice if the application could actually extend an existing object that looks something like this as you can with the Expando object:public class User : Westwind.Utilities.Dynamic.Expando { public string Email { get; set; } public string Password { get; set; } public string Name { get; set; } public bool Active { get; set; } public DateTime? ExpiresOn { get; set; } } and then simply start extending the properties of this object dynamically? Using the Expando object I describe later you can now do the following:[TestMethod] public void UserExampleTest() { var user = new User(); // Set strongly typed properties user.Email = "[email protected]"; user.Password = "nonya123"; user.Name = "Rickochet"; user.Active = true; // Now add dynamic properties dynamic duser = user; duser.Entered = DateTime.Now; duser.Accesses = 1; // you can also add dynamic props via indexer user["NickName"] = "AntiSocialX"; duser["WebSite"] = "http://www.west-wind.com/weblog"; // Access strong type through dynamic ref Assert.AreEqual(user.Name,duser.Name); // Access strong type through indexer Assert.AreEqual(user.Password,user["Password"]); // access dyanmically added value through indexer Assert.AreEqual(duser.Entered,user["Entered"]); // access index added value through dynamic Assert.AreEqual(user["NickName"],duser.NickName); // loop through all properties dynamic AND strong type properties (true) foreach (var prop in user.GetProperties(true)) { object val = prop.Value; if (val == null) val = "null"; Console.WriteLine(prop.Key + ": " + val.ToString()); } } As you can see this code somewhat blurs the line between a static and dynamic type. You start with a strongly typed object that has a fixed set of properties. You can then cast the object to dynamic (as I discussed in my last post) and add additional properties to the object. You can also use an indexer to add dynamic properties to the object. To access the strongly typed properties you can use either the strongly typed instance, the indexer or the dynamic cast of the object. Personally I think it's kinda cool to have an easy way to access strongly typed properties by string which can make some data scenarios much easier. To access the 'dynamically added' properties you can use either the indexer on the strongly typed object, or property syntax on the dynamic cast. Using the dynamic type allows all three modes to work on both strongly typed and dynamic properties. Finally you can iterate over all properties, both dynamic and strongly typed if you chose. Lots of flexibility. Note also that by default the Expando object works against the (this) instance meaning it extends the current object. You can also pass in a separate instance to the constructor in which case that object will be used to iterate over to find properties rather than this. Using this approach provides some really interesting functionality when use the dynamic type. To use this we have to add an explicit constructor to the Expando subclass:public class User : Westwind.Utilities.Dynamic.Expando { public string Email { get; set; } public string Password { get; set; } public string Name { get; set; } public bool Active { get; set; } public DateTime? ExpiresOn { get; set; } public User() : base() { } // only required if you want to mix in seperate instance public User(object instance) : base(instance) { } } to allow the instance to be passed. When you do you can now do:[TestMethod] public void ExpandoMixinTest() { // have Expando work on Addresses var user = new User( new Address() ); // cast to dynamicAccessToPropertyTest dynamic duser = user; // Set strongly typed properties duser.Email = "[email protected]"; user.Password = "nonya123"; // Set properties on address object duser.Address = "32 Kaiea"; //duser.Phone = "808-123-2131"; // set dynamic properties duser.NonExistantProperty = "This works too"; // shows default value Address.Phone value Console.WriteLine(duser.Phone); } Using the dynamic cast in this case allows you to access *three* different 'objects': The strong type properties, the dynamically added properties in the dictionary and the properties of the instance passed in! Effectively this gives you a way to simulate multiple inheritance (which is scary - so be very careful with this, but you can do it). How Expando works Behind the scenes Expando is a DynamicObject subclass as I discussed in my last post. By implementing a few of DynamicObject's methods you can basically create a type that can trap 'property missing' and 'method missing' operations. When you access a non-existant property a known method is fired that our code can intercept and provide a value for. Internally Expando uses a custom dictionary implementation to hold the dynamic properties you might add to your expandable object. Let's look at code first. The code for the Expando type is straight forward and given what it provides relatively short. Here it is.using System; using System.Collections.Generic; using System.Linq; using System.Dynamic; using System.Reflection; namespace Westwind.Utilities.Dynamic { /// <summary> /// Class that provides extensible properties and methods. This /// dynamic object stores 'extra' properties in a dictionary or /// checks the actual properties of the instance. /// /// This means you can subclass this expando and retrieve either /// native properties or properties from values in the dictionary. /// /// This type allows you three ways to access its properties: /// /// Directly: any explicitly declared properties are accessible /// Dynamic: dynamic cast allows access to dictionary and native properties/methods /// Dictionary: Any of the extended properties are accessible via IDictionary interface /// </summary> [Serializable] public class Expando : DynamicObject, IDynamicMetaObjectProvider { /// <summary> /// Instance of object passed in /// </summary> object Instance; /// <summary> /// Cached type of the instance /// </summary> Type InstanceType; PropertyInfo[] InstancePropertyInfo { get { if (_InstancePropertyInfo == null && Instance != null) _InstancePropertyInfo = Instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); return _InstancePropertyInfo; } } PropertyInfo[] _InstancePropertyInfo; /// <summary> /// String Dictionary that contains the extra dynamic values /// stored on this object/instance /// </summary> /// <remarks>Using PropertyBag to support XML Serialization of the dictionary</remarks> public PropertyBag Properties = new PropertyBag(); //public Dictionary<string,object> Properties = new Dictionary<string, object>(); /// <summary> /// This constructor just works off the internal dictionary and any /// public properties of this object. /// /// Note you can subclass Expando. /// </summary> public Expando() { Initialize(this); } /// <summary> /// Allows passing in an existing instance variable to 'extend'. /// </summary> /// <remarks> /// You can pass in null here if you don't want to /// check native properties and only check the Dictionary! /// </remarks> /// <param name="instance"></param> public Expando(object instance) { Initialize(instance); } protected virtual void Initialize(object instance) { Instance = instance; if (instance != null) InstanceType = instance.GetType(); } /// <summary> /// Try to retrieve a member by name first from instance properties /// followed by the collection entries. /// </summary> /// <param name="binder"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryGetMember(GetMemberBinder binder, out object result) { result = null; // first check the Properties collection for member if (Properties.Keys.Contains(binder.Name)) { result = Properties[binder.Name]; return true; } // Next check for Public properties via Reflection if (Instance != null) { try { return GetProperty(Instance, binder.Name, out result); } catch { } } // failed to retrieve a property result = null; return false; } /// <summary> /// Property setter implementation tries to retrieve value from instance /// first then into this object /// </summary> /// <param name="binder"></param> /// <param name="value"></param> /// <returns></returns> public override bool TrySetMember(SetMemberBinder binder, object value) { // first check to see if there's a native property to set if (Instance != null) { try { bool result = SetProperty(Instance, binder.Name, value); if (result) return true; } catch { } } // no match - set or add to dictionary Properties[binder.Name] = value; return true; } /// <summary> /// Dynamic invocation method. Currently allows only for Reflection based /// operation (no ability to add methods dynamically). /// </summary> /// <param name="binder"></param> /// <param name="args"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (Instance != null) { try { // check instance passed in for methods to invoke if (InvokeMethod(Instance, binder.Name, args, out result)) return true; } catch { } } result = null; return false; } /// <summary> /// Reflection Helper method to retrieve a property /// </summary> /// <param name="instance"></param> /// <param name="name"></param> /// <param name="result"></param> /// <returns></returns> protected bool GetProperty(object instance, string name, out object result) { if (instance == null) instance = this; var miArray = InstanceType.GetMember(name, BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance); if (miArray != null && miArray.Length > 0) { var mi = miArray[0]; if (mi.MemberType == MemberTypes.Property) { result = ((PropertyInfo)mi).GetValue(instance,null); return true; } } result = null; return false; } /// <summary> /// Reflection helper method to set a property value /// </summary> /// <param name="instance"></param> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> protected bool SetProperty(object instance, string name, object value) { if (instance == null) instance = this; var miArray = InstanceType.GetMember(name, BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance); if (miArray != null && miArray.Length > 0) { var mi = miArray[0]; if (mi.MemberType == MemberTypes.Property) { ((PropertyInfo)mi).SetValue(Instance, value, null); return true; } } return false; } /// <summary> /// Reflection helper method to invoke a method /// </summary> /// <param name="instance"></param> /// <param name="name"></param> /// <param name="args"></param> /// <param name="result"></param> /// <returns></returns> protected bool InvokeMethod(object instance, string name, object[] args, out object result) { if (instance == null) instance = this; // Look at the instanceType var miArray = InstanceType.GetMember(name, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance); if (miArray != null && miArray.Length > 0) { var mi = miArray[0] as MethodInfo; result = mi.Invoke(Instance, args); return true; } result = null; return false; } /// <summary> /// Convenience method that provides a string Indexer /// to the Properties collection AND the strongly typed /// properties of the object by name. /// /// // dynamic /// exp["Address"] = "112 nowhere lane"; /// // strong /// var name = exp["StronglyTypedProperty"] as string; /// </summary> /// <remarks> /// The getter checks the Properties dictionary first /// then looks in PropertyInfo for properties. /// The setter checks the instance properties before /// checking the Properties dictionary. /// </remarks> /// <param name="key"></param> /// /// <returns></returns> public object this[string key] { get { try { // try to get from properties collection first return Properties[key]; } catch (KeyNotFoundException ex) { // try reflection on instanceType object result = null; if (GetProperty(Instance, key, out result)) return result; // nope doesn't exist throw; } } set { if (Properties.ContainsKey(key)) { Properties[key] = value; return; } // check instance for existance of type first var miArray = InstanceType.GetMember(key, BindingFlags.Public | BindingFlags.GetProperty); if (miArray != null && miArray.Length > 0) SetProperty(Instance, key, value); else Properties[key] = value; } } /// <summary> /// Returns and the properties of /// </summary> /// <param name="includeProperties"></param> /// <returns></returns> public IEnumerable<KeyValuePair<string,object>> GetProperties(bool includeInstanceProperties = false) { if (includeInstanceProperties && Instance != null) { foreach (var prop in this.InstancePropertyInfo) yield return new KeyValuePair<string, object>(prop.Name, prop.GetValue(Instance, null)); } foreach (var key in this.Properties.Keys) yield return new KeyValuePair<string, object>(key, this.Properties[key]); } /// <summary> /// Checks whether a property exists in the Property collection /// or as a property on the instance /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Contains(KeyValuePair<string, object> item, bool includeInstanceProperties = false) { bool res = Properties.ContainsKey(item.Key); if (res) return true; if (includeInstanceProperties && Instance != null) { foreach (var prop in this.InstancePropertyInfo) { if (prop.Name == item.Key) return true; } } return false; } } } Although the Expando class supports an indexer, it doesn't actually implement IDictionary or even IEnumerable. It only provides the indexer and Contains() and GetProperties() methods, that work against the Properties dictionary AND the internal instance. The reason for not implementing IDictionary is that a) it doesn't add much value since you can access the Properties dictionary directly and that b) I wanted to keep the interface to class very lean so that it can serve as an entity type if desired. Implementing these IDictionary (or even IEnumerable) causes LINQ extension methods to pop up on the type which obscures the property interface and would only confuse the purpose of the type. IDictionary and IEnumerable are also problematic for XML and JSON Serialization - the XML Serializer doesn't serialize IDictionary<string,object>, nor does the DataContractSerializer. The JavaScriptSerializer does serialize, but it treats the entire object like a dictionary and doesn't serialize the strongly typed properties of the type, only the dictionary values which is also not desirable. Hence the decision to stick with only implementing the indexer to support the user["CustomProperty"] functionality and leaving iteration functions to the publicly exposed Properties dictionary. Note that the Dictionary used here is a custom PropertyBag class I created to allow for serialization to work. One important aspect for my apps is that whatever custom properties get added they have to be accessible to AJAX clients since the particular app I'm working on is a SIngle Page Web app where most of the Web access is through JSON AJAX calls. PropertyBag can serialize to XML and one way serialize to JSON using the JavaScript serializer (not the DCS serializers though). The key components that make Expando work in this code are the Properties Dictionary and the TryGetMember() and TrySetMember() methods. The Properties collection is public so if you choose you can explicitly access the collection to get better performance or to manipulate the members in internal code (like loading up dynamic values form a database). Notice that TryGetMember() and TrySetMember() both work against the dictionary AND the internal instance to retrieve and set properties. This means that user["Name"] works against native properties of the object as does user["Name"] = "RogaDugDog". What's your Use Case? This is still an early prototype but I've plugged it into one of my customer's applications and so far it's working very well. The key features for me were the ability to easily extend the type with values coming from a database and exposing those values in a nice and easy to use manner. I'm also finding that using this type of object for ViewModels works very well to add custom properties to view models. I suspect there will be lots of uses for this - I've been using the extra dictionary approach to extensibility for years - using a dynamic type to make the syntax cleaner is just a bonus here. What can you think of to use this for? Resources Source Code and Tests (GitHub) Also integrated in Westwind.Utilities of the West Wind Web Toolkit West Wind Utilities NuGet© Rick Strahl, West Wind Technologies, 2005-2012Posted in CSharp  .NET  Dynamic Types   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Object model design: collections on classes

    - by Luke Puplett
    Hi all, Consider Train.Passengers, what type would you use for Passengers where passengers are not supposed to be added or removed by the consuming code? I'm using .NET Framework, so this discussion would suit .NET, but it could apply to a number of modern languages/frameworks. In the .NET Framework, the List is not supposed to be publicly exposed. There's Collection and ICollection and guidance, which I tend to agree with, is to return the closest concrete type down the inheritance tree, so that'd be Collection since it is already an ICollection. But Collection has read/write semantics and so possibly it should be a ReadOnlyCollection, but its arguably common sense not to alter the contents of a collection that you don't have intimate knowledge about so is it necessary? And it requires extra work internally and can be a pain with (de)serialization. At the extreme ends I could just return Person[] (since LINQ now provides much of the benefits that previously would have been afforded by a more specified collection) or even build a strongly-typed PersonCollection or ReadOnlyPersonCollection! What do you do? Thanks for your time. Luke

    Read the article

  • Circular dependency and object creation when attempting DDD

    - by Matthew
    I have a domain where an Organization has People. Organization Entity public class Organization { private readonly List<Person> _people = new List<Person>(); public Person CreatePerson(string name) { var person = new Person(organization, name); _people.Add(person); return person; } public IEnumerable<Person> People { get { return _people; } } } Person Entity public class Person { public Person(Organization organization, string name) { if (organization == null) { throw new ArgumentNullException("organization"); } Organization = organization; Name = name; } public Organization { get; private set; } public Name { get; private set; } } The rule for this relationship is that a Person must belong to exactly one Organization. The invariants I want to guarantee are: A person must have an organization this is enforced via the Person's constuctor An organization must know of its people this is why the Organization has a CreatePerson method A person must belong to only one organization this is why the organization's people list is not publicly mutable (ignoring the casting to List, maybe ToEnumerable can enforce that, not too concerned about it though) What I want out of this is that if a person is created, that the organization knows about its creation. However, the problem with the model currently is that you are able to create a person without ever adding it to the organizations collection. Here's a failing unit-test to describe my problem [Test] public void AnOrganizationMustKnowOfItsPeople() { var organization = new Organization(); var person = new Person(organization, "Steve McQueen"); CollectionAssert.Contains(organization.People, person); } What is the most idiomatic way to enforce the invariants and the circular relationship?

    Read the article

  • Design for object with optional and modifiable attributtes?

    - by Ikuzen
    I've been using the Builder pattern to create objects with a large number of attributes, where most of them are optional. But up until now, I've defined them as final, as recommended by Joshua Block and other authors, and haven't needed to change their values. I am wondering what should I do though if I need a class with a substantial number of optional but non-final (mutable) attributes? My Builder pattern code looks like this: public class Example { //All possible parameters (optional or not) private final int param1; private final int param2; //Builder class public static class Builder { private final int param1; //Required parameters private int param2 = 0; //Optional parameters - initialized to default //Builder constructor public Builder (int param1) { this.param1 = param1; } //Setter-like methods for optional parameters public Builder param2(int value) { param2 = value; return this; } //build() method public Example build() { return new Example(this); } } //Private constructor private Example(Builder builder) { param1 = builder.param1; param2 = builder.param2; } } Can I just remove the final keyword from the declaration to be able to access the attributes externally (through normal setters, for example)? Or is there a creational pattern that allows optional but non-final attributes that would be better suited in this case?

    Read the article

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