Search Results

Search found 325 results on 13 pages for 'immutable'.

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

  • Hashable, immutable

    - by joaquin
    From a recent SO question I realized I probably had a wrong concept of the meaning of hashable and immutable objects in python. What hashable means in practice?, What the relation between hashable and immmutable is? There are mutable objects that are hashable? And immutable not hashable?

    Read the article

  • Value objects in DDD - Why immutable?

    - by Hobbes
    I don't get why value objects in DDD should be immutable, nor do I see how this is easily done. (I'm focusing on C# and Entity Framework, if that matters.) For example, let's consider the classic Address value object. If you needed to change "123 Main St" to "123 Main Street", why should I need to construct a whole new object instead of saying myCustomer.Address.AddressLine1 = "123 Main Street"? (Even if Entity Framework supported structs, this would still be a problem, wouldn't it?) I understand (I think) the idea that value objects don't have an identity and are part of a domain object, but can someone explain why immutability is a Good Thing? EDIT: My final question here really should be "Can someone explain why immutability is a Good Thing as applied to Value Objects?" Sorry for the confusion! EDIT: To clairfy, I am not asking about CLR value types (vs reference types). I'm asking about the higher level DDD concept of Value Objects. For example, here is a hack-ish way to implement immutable value types for Entity Framework: http://rogeralsing.com/2009/05/21/entity-framework-4-immutable-value-objects. Basically, he just makes all setters private. Why go through the trouble of doing this?

    Read the article

  • Java: immutability, overuse of stack -- better data structure?

    - by HH
    I overused hashSets but it was slow, then changed to Stacks, speed boost-up. Poly's reply uses Collections.emptyList() as immutable list, cutting out excess null-checkers. No Collections.emptyStack(). Combining the words stack and immutability, from the last experiences, gets "immutable stack" (probably not related to functional prog). Java Api 5 for list interface shows that Stack is an implementing class for list and arraylist, here. The java.coccurrent pkg does not have any immutable Stack data structure. The first hinted of misusing stack. The lack of immutabily in the last and poly's book recommendation leads way to list. Something very primitive, fast, no extra layers, with methods like emptyThing(). Overuse of stack and where I use it DataFile.java: public Stack<DataFile> files; FileObject.java: public Stack<String> printViews = new Stack<String>(); FileObject.java:// private static Stack<Object> getFormat(File f){return (new Format(f)).getFormat();} Format.java: private Stack<Object> getLine(File[] fs,String s){return wF;} Format.java: private Stack<Object> getFormat(){return format;} Positions.java: public static Stack<Integer[]> getPrintPoss(String s,File f,Integer maxViewPerF) Positions.java: Stack<File> possPrint = new Stack<File>(); Positions.java: Stack<Integer> positions=new Stack<Integer>(); Record.java: private String getFormatLine(Stack<Object> st) Record.java: Stack<String> lines=new Stack<String>(); SearchToUser.java: public static final Stack<File> allFiles = findf.getFs(); SearchToUser.java: public static final Stack<File> allDirs = findf.getDs(); SearchToUser.java: private Stack<Integer[]> positionsPrint=new Stack<Integer[]>(); SearchToUser.java: public Stack<String> getSearchResults(String s, Integer countPerFile, Integer resCount) SearchToUser.java: Stack<File> filesToS=Fs2Word.getFs2W(s,50); SearchToUser.java: Stack<String> rs=new Stack<String>(); View.java: public Stack<Integer[]> poss = new Stack<Integer[4]>(); View.java: public static Stack<String> getPrintViewsFileWise(String s,Object[] df,Integer maxViewsPerF) View.java: Stack<String> substrings = new Stack<String>(); View.java: private Stack<String> printViews=new Stack<String>(); View.java: MatchView(Stack<Integer> pss,File f,Integer maxViews) View.java: Stack<String> formatFile; View.java: private Stack<Search> files; View.java: private Stack<File> matchingFiles; View.java: private Stack<String> matchViews; View.java: private Stack<String> searchMatches; View.java: private Stack<String> getSearchResults(Integer numbResults) Easier with List: AllDirs and AllFs, now looping with push, but list has more pow. methods such as addAll [OLD] From Stack to some immutable data structure How to get immutable Stack data structure? Can I box it with list? Should I switch my current implementatios from stacks to Lists to get immutable? Which immutable data structure is Very fast with about similar exec time as Stack? No immutability to Stack with Final import java.io.*; import java.util.*; public class TestStack{ public static void main(String[] args) { final Stack<Integer> test = new Stack<Integer>(); Stack<Integer> test2 = new Stack<Integer>(); test.push(37707); test2.push(80437707); //WHY is there not an error to remove an elment // from FINAL stack? System.out.println(test.pop()); System.out.println(test2.pop()); } }

    Read the article

  • Immutable values in F#

    - by rsteckly
    I'm just getting started in F# and have a basic question. Here's the code: let rec forLoop body times = if times <= 0 then () else body() forLoop body (times -1) I don't get the concept of how when you define a variable it is a value and immutable. Here, the value is changing in order to loop. How is that different from a variable in C#?

    Read the article

  • Constructor for an immutable struct

    - by Danvil
    Consider the following simple immutable struct: struct Stash { public int X { get; private set; } public Stash(int _x) { X = _x; } } This is not working, because the compiler wants me to initialize the "backing field" before I can access the property. How can I solve this?

    Read the article

  • Immutability and shared references - how to reconcile?

    - by davetron5000
    Consider this simplified application domain: Criminal Investigative database Person is anyone involved in an investigation Report is a bit of info that is part of an investigation A Report references a primary Person (the subject of an investigation) A Report has accomplices who are secondarily related (and could certainly be primary in other investigations or reports These classes have ids that are used to store them in a database, since their info can change over time (e.g. we might find new aliases for a person, or add persons of interest to a report) If these are stored in some sort of database and I wish to use immutable objects, there seems to be an issue regarding state and referencing. Supposing that I change some meta-data about a Person. Since my Person objects immutable, I might have some code like: class Person( val id:UUID, val aliases:List[String], val reports:List[Report]) { def addAlias(name:String) = new Person(id,name :: aliases,reports) } So that my Person with a new alias becomes a new object, also immutable. If a Report refers to that person, but the alias was changed elsewhere in the system, my Report now refers to the "old" person, i.e. the person without the new alias. Similarly, I might have: class Report(val id:UUID, val content:String) { /** Adding more info to our report */ def updateContent(newContent:String) = new Report(id,newContent) } Since these objects don't know who refers to them, it's not clear to me how to let all the "referrers" know that there is a new object available representing the most recent state. This could be done by having all objects "refresh" from a central data store and all operations that create new, updated, objects store to the central data store, but this feels like a cheesy reimplementation of the underlying language's referencing. i.e. it would be more clear to just make these "secondary storable objects" mutable. So, if I add an alias to a Person, all referrers see the new value without doing anything. How is this dealt with when we want to avoid mutability, or is this a case where immutability is not helpful?

    Read the article

  • Why might a System.String object not cache its hash code?

    - by Dan Tao
    A glance at the source code for string.GetHashCode using Reflector reveals the following (for mscorlib.dll version 4.0): public override unsafe int GetHashCode() { fixed (char* str = ((char*) this)) { char* chPtr = str; int num = 0x15051505; int num2 = num; int* numPtr = (int*) chPtr; for (int i = this.Length; i > 0; i -= 4) { num = (((num << 5) + num) + (num >> 0x1b)) ^ numPtr[0]; if (i <= 2) { break; } num2 = (((num2 << 5) + num2) + (num2 >> 0x1b)) ^ numPtr[1]; numPtr += 2; } return (num + (num2 * 0x5d588b65)); } } Now, I realize that the implementation of GetHashCode is not specified and is implementation-dependent, so the question "is GetHashCode implemented in the form of X or Y?" is not really answerable. I'm just curious about a few things: If Reflector has disassembled the DLL correctly and this is the implementation of GetHashCode (in my environment), am I correct in interpreting this code to indicate that a string object, based on this particular implementation, would not cache its hash code? Assuming the answer is yes, why would this be? It seems to me that the memory cost would be minimal (one more 32-bit integer, a drop in the pond compared to the size of the string itself) whereas the savings would be significant, especially in cases where, e.g., strings are used as keys in a hashtable-based collection like a Dictionary<string, [...]>. And since the string class is immutable, it isn't like the value returned by GetHashCode will ever even change. What could I be missing? UPDATE: In response to Andras Zoltan's closing remark: There's also the point made in Tim's answer(+1 there). If he's right, and I think he is, then there's no guarantee that a string is actually immutable after construction, therefore to cache the result would be wrong. Whoa, whoa there! This is an interesting point to make (and yes it's very true), but I really doubt that this was taken into consideration in the implementation of GetHashCode. The statement "therefore to cache the result would be wrong" implies to me that the framework's attitude regarding strings is "Well, they're supposed to be immutable, but really if developers want to get sneaky they're mutable so we'll treat them as such." This is definitely not how the framework views strings. It fully relies on their immutability in so many ways (interning of string literals, assignment of all zero-length strings to string.Empty, etc.) that, basically, if you mutate a string, you're writing code whose behavior is entirely undefined and unpredictable. I guess my point is that for the author(s) of this implementation to worry, "What if this string instance is modified between calls, even though the class as it is publicly exposed is immutable?" would be like for someone planning a casual outdoor BBQ to think to him-/herself, "What if someone brings an atomic bomb to the party?" Look, if someone brings an atom bomb, party's over.

    Read the article

  • jQuery object are immutable?

    - by Daniel
    Hello a new noob on jQuery here and I was wondering if jQuery objects are immutable. For example: var obj1 = $("<tag></tag>"); var obj2 = obj1.append("something"); Will obj1 and obj2 be the same meaning obj2 will reference obj1? UPDATE: The above example kind of scratches the surface of what i want to know, a more accurate question is : If i chain function from the jQuery api will they return the same object or a new one (as the case with strings in Java)?

    Read the article

  • C# DDD Populate Immutable Objects

    - by Russel
    Hi I have a immutable Customer class in my domain assembly. It contains the following GET properties : id, firstname and lastname. I have a CustomerRepository class in my persistence assembly. In turn, this CustomerRepository class should populate and return a Customer object using a remote web-serivce. My Customer class contains no setter properties and it contains a private constructor. The reason - I dont want the UI developer to get the wrong idea - He should not be able to create or change a Customer object. My question: How do I get my CustomerRepository to populate my Customer object. Reflection? Or should I sacrifice my design and enable a public constructor for constructing the customer object?

    Read the article

  • Why can't we have an immutable version of operator[] for map

    - by Yan Cheng CHEOK
    The following code works fine : std::map<int, int>& m = std::map<int, int>(); int i = m[0]; But not the following code : // error C2678: binary '[' : no operator... const std::map<int, int>& m = std::map<int, int>(); int i = m[0]; Most of the time, I prefer to make most of my stuff to become immutable, due to reason : http://www.javapractices.com/topic/TopicAction.do?Id=29 I look at map source code. It has mapped_type& operator[](const key_type& _Keyval) Is there any reason, why std::map unable to provide const mapped_type& operator[](const key_type& _Keyval) const

    Read the article

  • Disposing underlying object from finalizer in an immutable object

    - by Juan Luis Soldi
    I'm trying to wrap around Awesomium and make it look to the rest of my code as close as possible to NET's WebBrowser since this is for an existing application that already uses the WebBrowser. In this library, there is a class called JSObject which represents a javascript object. You can get one of this, for instance, by calling the ExecuteJavascriptWithResult method of the WebView class. If you'd call it like myWebView.ExecuteJavascriptWithResult("document", string.Empty).ToObject(), then you'd get a JSObject that represents the document. I'm writing an immutable class (it's only field is a readonly JSObject object) called JSObjectWrap that wraps around JSObject which I want to use as base class for other classes that would emulate .NET classes such as HtmlElement and HtmlDocument. Now, these classes don't implement Dispose, but JSObject does. What I first thought was to call the underlying JSObject's Dispose method in my JSObjectWrap's finalizer (instead of having JSObjectWrap implement Dispose) so that the rest of my code can stay the way it is (instead of having to add using's everywhere and make sure every JSObjectWrap is being properly disposed). But I just realized if more than two JSObjectWrap's have the same underlying JSObject and one of them gets finalized this will mess up the other JSObjectWrap. So now I'm thinking maybe I should keep a static Dictionary of JSObjects and keep count of how many of each of them are being referenced by a JSObjectWrap but this sounds messy and I think could cause major performance issues. Since this sounds to me like a common pattern I wonder if anyone else has a better idea.

    Read the article

  • Which term to use when referring to functional data structures: persistent or immutable?

    - by Bob
    In the context of functional programming which is the correct term to use: persistent or immutable? When I Google "immutable data structures" I get a Wikipedia link to an article on "Persistent data structure" which even goes on to say: such data structures are effectively immutable Which further confuses things for me. Do functional programs rely on persistent data structures or immutable data structures? Or are they always the same thing?

    Read the article

  • Blend Interaction Behaviour gives "points to immutable instance" error

    - by kennethkryger
    I have a UserControl that is a base class for other user controls, that are shown in "modal view". I want to have all user controls fading in, when shown and fading out when closed. I also want a behavior, so that the user can move the controls around.My contructor looks like this: var tg = new TransformGroup(); tg.Children.Add(new ScaleTransform()); RenderTransform = tg; var behaviors = Interaction.GetBehaviors(this); behaviors.Add(new TranslateZoomRotateBehavior()); Loaded += ModalDialogBase_Loaded; And the ModalDialogBase_Loaded method looks like this: private void ModalDialogBase_Loaded(object sender, RoutedEventArgs e) { var fadeInStoryboard = (Storyboard)TryFindResource("modalDialogFadeIn"); fadeInStoryboard.Begin(this); } When I press a Close-button on the control this method is called: protected virtual void Close() { var fadeOutStoryboard = (Storyboard)TryFindResource("modalDialogFadeOut"); fadeOutStoryboard = fadeOutStoryboard.Clone(); fadeOutStoryboard.Completed += delegate { RaiseEvent(new RoutedEventArgs(ClosedEvent)); }; fadeOutStoryboard.Begin(this); } The storyboard for fading out look like this: <Storyboard x:Key="modalDialogFadeOut"> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)" Storyboard.TargetName="{x:Null}"> <EasingDoubleKeyFrame KeyTime="0" Value="1"> <EasingDoubleKeyFrame.EasingFunction> <BackEase EasingMode="EaseIn" Amplitude="0.3" /> </EasingDoubleKeyFrame.EasingFunction> </EasingDoubleKeyFrame> <EasingDoubleKeyFrame KeyTime="0:0:0.4" Value="0"> <EasingDoubleKeyFrame.EasingFunction> <BackEase EasingMode="EaseIn" Amplitude="0.3" /> </EasingDoubleKeyFrame.EasingFunction> </EasingDoubleKeyFrame> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)" Storyboard.TargetName="{x:Null}"> <EasingDoubleKeyFrame KeyTime="0" Value="1"> <EasingDoubleKeyFrame.EasingFunction> <BackEase EasingMode="EaseIn" Amplitude="0.3" /> </EasingDoubleKeyFrame.EasingFunction> </EasingDoubleKeyFrame> <EasingDoubleKeyFrame KeyTime="0:0:0.4" Value="0"> <EasingDoubleKeyFrame.EasingFunction> <BackEase EasingMode="EaseIn" Amplitude="0.3" /> </EasingDoubleKeyFrame.EasingFunction> </EasingDoubleKeyFrame> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="{x:Null}"> <EasingDoubleKeyFrame KeyTime="0" Value="1" /> <EasingDoubleKeyFrame KeyTime="0:0:0.3" Value="0" /> <EasingDoubleKeyFrame KeyTime="0:0:0.4" Value="0" /> </DoubleAnimationUsingKeyFrames> </Storyboard> If the user control is show, and the user does NOT move it around on the screen, everything works fine. However, if the user DOES move the control around, I get the following error when the modalDialogFadeOut storyboard is started: 'Children' property value in the path '(0).(1)[0].(2)' points to immutable instance of 'System.Windows.Media.TransformCollection'. How can fix this?

    Read the article

  • F# &ndash; Immutable List vs a Mutable Collection in Arrays

    - by MarkPearl
    Another day gone by looking into F#. Today I thought I would ramble on about lists and arrays in F#. Coming from a C# background I barely ever use arrays now days in my C# code – why you may ask – because I find lists generally handle most of the business scenario’s that I come across. So it has been an interesting experience with me keep bumping into Array’s & Lists in F# and I wondered why the frequency of coming across arrays was so much more in this language than in C#. Take for instance the code I stumbled across today. let rng = new Random() let shuffle (array : 'a array) = let n = array.Length for x in 1..n do let i = n-x let j = rng.Next(i+1) let tmp = array.[i] array.[i] <- array.[j] array.[j] <- tmp array   Quite simply its purpose is to “shuffle” an array of items. So I thought, why does it have the “a’ array'” explicitly declared? What if I changed it to a list? Well… as I was about to find out there are some subtle differences between array’s & lists in F# that do not exist in C#. Namely, mutability. A list in F# is an ordered, immutable series of elements of the same type, while an array is a fixed-size zero based, mutable collection of consecutive data elements that are all of the same type. For me the keyword is immutable vs mutable collection. That’s why I could not simply swap the ‘a array with ‘a list in my function header because then later on in the code the syntax would not be valid where I “swap” item positions. i.e. array.[i] <- array.[j] would be invalid because if it was a list, it would be immutable and so couldn’t change by its very definition.. So where does that leave me? It’s to early days to say. I don’t know what the balance will be in future code – will I typically always use lists or arrays or even have a balance, but time will tell.

    Read the article

  • Immutability of structs

    - by Joan Venge
    I read it in lots of places including here that it's better to make structs as immutable. What's the reason behind this? I see lots of Microsoft-created structs that are mutable, like the ones in xna. Probably there are many more in the BCL. What are the pros and cons of not following this guideline?

    Read the article

  • what would be a frozen dict ?

    - by dugres
    A frozen set is a frozenset. A frozen list could be a tuple. What would be a frozen dict ? An immutable, hashable dict. I guess it could be something like collections.namedtuple, but namedtuple is more like a frozenkeys dict (an half-frozen dict). No ?

    Read the article

  • Persistent (purely functional) Red-Black trees on disk performance

    - by Waneck
    I'm studying the best data structures to implement a simple open-source object temporal database, and currently I'm very fond of using Persistent Red-Black trees to do it. My main reasons for using persistent data structures is first of all to minimize the use of locks, so the database can be as parallel as possible. Also it will be easier to implement ACID transactions and even being able to abstract the database to work in parallel on a cluster of some kind. The great thing of this approach is that it makes possible implementing temporal databases almost for free. And this is something quite nice to have, specially for web and for data analysis (e.g. trends). All of this is very cool, but I'm a little suspicious about the overall performance of using a persistent data structure on disk. Even though there are some very fast disks available today, and all writes can be done asynchronously, so a response is always immediate, I don't want to build all application under a false premise, only to realize it isn't really a good way to do it. Here's my line of thought: - Since all writes are done asynchronously, and using a persistent data structure will enable not to invalidate the previous - and currently valid - structure, the write time isn't really a bottleneck. - There are some literature on structures like this that are exactly for disk usage. But it seems to me that these techniques will add more read overhead to achieve faster writes. But I think that exactly the opposite is preferable. Also many of these techniques really do end up with a multi-versioned trees, but they aren't strictly immutable, which is something very crucial to justify the persistent overhead. - I know there still will have to be some kind of locking when appending values to the database, and I also know there should be a good garbage collecting logic if not all versions are to be maintained (otherwise the file size will surely rise dramatically). Also a delta compression system could be thought about. - Of all search trees structures, I really think Red-Blacks are the most close to what I need, since they offer the least number of rotations. But there are some possible pitfalls along the way: - Asynchronous writes -could- affect applications that need the data in real time. But I don't think that is the case with web applications, most of the time. Also when real-time data is needed, another solutions could be devised, like a check-in/check-out system of specific data that will need to be worked on a more real-time manner. - Also they could lead to some commit conflicts, though I fail to think of a good example of when it could happen. Also commit conflicts can occur in normal RDBMS, if two threads are working with the same data, right? - The overhead of having an immutable interface like this will grow exponentially and everything is doomed to fail soon, so this all is a bad idea. Any thoughts? Thanks! edit: There seems to be a misunderstanding of what a persistent data structure is: http://en.wikipedia.org/wiki/Persistent_data_structure

    Read the article

  • Mutable objects and hashCode

    - by robert
    Have the following class: public class Member { private int x; private long y; private double d; public Member(int x, long y, double d) { this.x = x; this.y = y; this.d = d; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = (int) (prime * result + y); result = (int) (prime * result + Double.doubleToLongBits(d)); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof Member) { Member other = (Member) obj; return other.x == x && other.y == y && Double.compare(d, other.d) == 0; } return false; } public static void main(String[] args) { Set<Member> test = new HashSet<Member>(); Member b = new Member(1, 2, 3); test.add(b); System.out.println(b.hashCode()); b.x = 0; System.out.println(b.hashCode()); Member first = test.iterator().next(); System.out.println(test.contains(first)); System.out.println(b.equals(first)); System.out.println(test.add(first)); } } It produces the following results: 30814 29853 false true true Because the hashCode depends of the state of the object it can no longer by retrieved properly, so the check for containment fails. The HashSet in no longer working properly. A solution would be to make Member immutable, but is that the only solution? Should all classes added to HashSets be immutable? Is there any other way to handle the situation? Regards.

    Read the article

  • java immutable object question

    - by cometta
    String abc[]={"abc"}; String def[]={}; def=abc; def[0]=def[0]+"changed"; System.out.println(abc[0]); by changing "def" object, my abc object is changed as well. Beside String[] array has this characteristic what other java object has similar characteristic? can explain more? in order to prevent abc from changed when i changed def, i will have to do def = abc.clone();

    Read the article

  • Are some data structures more suitable for functional programming than others?

    - by Rob Lachlan
    In Real World Haskell, there is a section titled "Life without arrays or hash tables" where the authors suggest that list and trees are preferred in functional programming, whereas an array or a hash table might be used instead in an imperative program. This makes sense, since it's much easier to reuse part of an (immutable) list or tree when creating a new one than to do so with an array. So my questions are: Are there really significantly different usage patterns for data structures between functional and imperative programming? If so, is this a problem? What if you really do need a hash table for some application? Do you simply swallow the extra expense incurred for modifications?

    Read the article

  • Change NSNumber value by allocating new NSNumber?

    - by Peter Hajas
    I understand that NSNumber is immutable, but I still have the need to change it in my app. I use it because it's an object, and therefore usable with @property (if I could, I would use float or CGFloat in a heartbeat, but sadly, I can't). Is there any way to just overwrite the old NSNumber instance? I'm trying this: NSNumber *zero = [[NSNumber alloc] initWithFloat:0.0]; myNSNumber = zero but this doesn't change the value. This is a simplified version of my code, as I'm changing the root view controller's parameter (I know, not MVC-friendly). Still, the changing of the value should be the same assignment, right? Should I release myNSNumber first? What should I set the @property at for myNSNumber? Thanks!

    Read the article

  • Immutability of big objects

    - by Malax
    Hi StackOverflow! I have some big (more than 3 fields) Objects which can and should be immutable. Every time I run into that case i tend to create constructor abominations with long parameter lists. It doesn't feel right, is hard to use and readability suffers. It is even worse if the fields are some sort of collection type like lists. A simple addSibling(S s) would ease the object creation so much but renders the object mutable. What do you guys use in such cases? I'm on Scala and Java, but i think the problem is language agnostic as long as the language is object oriented. Solutions I can think of: "Constructor abominations with long parameter lists" The Builder Pattern Thanks for your input!

    Read the article

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