Search Results

Search found 58 results on 3 pages for 'immutability'.

Page 1/3 | 1 2 3  | Next Page >

  • Does immutability entirely eliminate the need for locks in multi-processor programming?

    - by GlenPeterson
    Part 1 Clearly Immutability minimizes the need for locks in multi-processor programming, but does it eliminate that need, or are there instances where immutability alone is not enough? It seems to me that you can only defer processing and encapsulate state so long before most programs have to actually DO something. If a program performs actions on multiple processors, something needs to collect and aggregate the results. All this involves multi-process communication before, after, and possibly during some transformations. The start and end state of the machines are different. Can this always be done with no locks just by throwing out each object and creating a new one instead of changing the original (a crude view of immutability)? What cases still require locking? I'm interested in both the theoretical/academic answer and the practical/real-world answer. I know a lot of functional programmers like to talk about "no side effect" but in the "real world" everything has a side effect. Every processor click takes time and electricity and machine resources away from other processes. So I understand that there may be more than one perspective to answer this question from. If immutability is safe, given certain bounds or assumptions, I want to know what the borders of the "safety zone" are exactly. Some examples of possible boundaries: I/O Exceptions/errors Interfaces with programs written in other languages Interfaces with other machines (physical, virtual, or theoretical) Special thanks to @JimmaHoffa for his comment which started this question! Part 2 Multi-processor programming is often used as an optimization technique - to make some code run faster. When is it faster to use locks vs. immutable objects? Given the limits set out in Amdahl's Law, when can you achieve better over-all performance (with or without the garbage collector taken into account) with immutable objects vs. locking mutable ones? Summary I'm combining these two questions into one to try to get at where the bounding box is for Immutability as a solution to threading problems.

    Read the article

  • Python metaclass for enforcing immutability of custom types

    - by Mark Lehmacher
    Having searched for a way to enforce immutability of custom types and not having found a satisfactory answer I came up with my own shot at a solution in form of a metaclass: class ImmutableTypeException( Exception ): pass class Immutable( type ): ''' Enforce some aspects of the immutability contract for new-style classes: - attributes must not be created, modified or deleted after object construction - immutable types must implement __eq__ and __hash__ ''' def __new__( meta, classname, bases, classDict ): instance = type.__new__( meta, classname, bases, classDict ) # Make sure __eq__ and __hash__ have been implemented by the immutable type. # In the case of __hash__ also make sure the object default implementation has been overridden. # TODO: the check for eq and hash functions could probably be done more directly and thus more efficiently # (hasattr does not seem to traverse the type hierarchy) if not '__eq__' in dir( instance ): raise ImmutableTypeException( 'Immutable types must implement __eq__.' ) if not '__hash__' in dir( instance ): raise ImmutableTypeException( 'Immutable types must implement __hash__.' ) if _methodFromObjectType( instance.__hash__ ): raise ImmutableTypeException( 'Immutable types must override object.__hash__.' ) instance.__setattr__ = _setattr instance.__delattr__ = _delattr return instance def __call__( self, *args, **kwargs ): obj = type.__call__( self, *args, **kwargs ) obj.__immutable__ = True return obj def _setattr( self, attr, value ): if '__immutable__' in self.__dict__ and self.__immutable__: raise AttributeError( "'%s' must not be modified because '%s' is immutable" % ( attr, self ) ) object.__setattr__( self, attr, value ) def _delattr( self, attr ): raise AttributeError( "'%s' must not be deleted because '%s' is immutable" % ( attr, self ) ) def _methodFromObjectType( method ): ''' Return True if the given method has been defined by object, False otherwise. ''' try: # TODO: Are we exploiting an implementation detail here? Find better solution! return isinstance( method.__objclass__, object ) except: return False However, while the general approach seems to be working rather well there are still some iffy implementation details (also see TODO comments in code): How do I check if a particular method has been implemented anywhere in the type hierarchy? How do I check which type is the origin of a method declaration (i.e. as part of which type a method has been defined)?

    Read the article

  • Getting My Head Around Immutability

    - by Michael Mangold
    I'm new to object-oriented programming, and one concept that has been taking me a while to grasp is immutability. I think the light bulb went off last night but I want to verify: When I come across statements that an immutable object cannot be changed, I'm puzzled because I can, for instance, do the following: NSString *myName = @"Bob"; myName = @"Mike"; There, I just changed myName, of immutable type NSString. My problem is that the word, "object" can refer to the physical object in memory, or the abstraction, "myName." The former definition applies to the concept of immutability. As for the variable, a more clear (to me) definition of immutability is that the value of an immutable object can only be changed by also changing its location in memory, i.e. its reference (also known as its pointer). Is this correct, or am I still lost in the woods?

    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

  • What are the consequences of immutable classes with references to mutable classes?

    - by glenviewjeff
    I've recently begun adopting the best practice of designing my classes to be immutable per Effective Java [Bloch2008]. I have a series of interrelated questions about degrees of mutability and their consequences. I have run into situations where a (Java) class I implemented is only "internally immutable" because it uses references to other mutable classes. In this case, the class under development appears from the external environment to have state. Do any of the benefits (see below) of immutable classes hold true even by only "internally immutable" classes? Is there an accepted term for the aforementioned "internal mutability"? Wikipedia's immutable object page uses the unsourced term "deep immutability" to describe an object whose references are also immutable. Is the distinction between mutability and side-effect-ness/state important? Josh Bloch lists the following benefits of immutable classes: are simple to construct, test, and use are automatically thread-safe and have no synchronization issues do not need a copy constructor do not need an implementation of clone allow hashCode to use lazy initialization, and to cache its return value do not need to be copied defensively when used as a field make good Map keys and Set elements (these objects must not change state while in the collection) have their class invariant established once upon construction, and it never needs to be checked again always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state

    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

  • 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

  • Internal Mutation of Persistent Data Structures

    - by Greg Ros
    To clarify, when I mean use the terms persistent and immutable on a data structure, I mean that: The state of the data structure remains unchanged for its lifetime. It always holds the same data, and the same operations always produce the same results. The data structure allows Add, Remove, and similar methods that return new objects of its kind, modified as instructed, that may or may not share some of the data of the original object. However, while a data structure may seem to the user as persistent, it may do other things under the hood. To be sure, all data structures are, internally, at least somewhere, based on mutable storage. If I were to base a persistent vector on an array, and copy it whenever Add is invoked, it would still be persistent, as long as I modify only locally created arrays. However, sometimes, you can greatly increase performance by mutating a data structure under the hood. In more, say, insidious, dangerous, and destructive ways. Ways that might leave the abstraction untouched, not letting the user know anything has changed about the data structure, but being critical in the implementation level. For example, let's say that we have a class called ArrayVector implemented using an array. Whenever you invoke Add, you get a ArrayVector build on top of a newly allocated array that has an additional item. A sequence of such updates will involve n array copies and allocations. Here is an illustration: However, let's say we implement a lazy mechanism that stores all sorts of updates -- such as Add, Set, and others in a queue. In this case, each update requires constant time (adding an item to a queue), and no array allocation is involved. When a user tries to get an item in the array, all the queued modifications are applied under the hood, requiring a single array allocation and copy (since we know exactly what data the final array will hold, and how big it will be). Future get operations will be performed on an empty cache, so they will take a single operation. But in order to implement this, we need to 'switch' or mutate the internal array to the new one, and empty the cache -- a very dangerous action. However, considering that in many circumstances (most updates are going to occur in sequence, after all), this can save a lot of time and memory, it might be worth it -- you will need to ensure exclusive access to the internal state, of course. This isn't a question about the efficacy of such a data structure. It's a more general question. Is it ever acceptable to mutate the internal state of a supposedly persistent or immutable object in destructive and dangerous ways? Does performance justify it? Would you still be able to call it immutable? Oh, and could you implement this sort of laziness without mutating the data structure in the specified fashion?

    Read the article

  • Clean way to use mutable implementation of Immutable interfaces for encapsulation

    - by dsollen
    My code is working on some compost relationship which creates a tree structure, class A has many children of type B, which has many children of type C etc. The lowest level class, call it bar, also points to a connected bar class. This effectively makes nearly every object in my domain inter-connected. Immutable objects would be problematic due to the expense of rebuilding almost all of my domain to make a single change to one class. I chose to go with an interface approach. Every object has an Immutable interface which only publishes the getter methods. I have controller objects which constructs the domain objects and thus has reference to the full objects, thus capable of calling the setter methods; but only ever publishes the immutable interface. Any change requested will go through the controller. So something like this: public interface ImmutableFoo{ public Bar getBar(); public Location getLocation(); } public class Foo implements ImmutableFoo{ private Bar bar; private Location location; @Override public Bar getBar(){ return Bar; } public void setBar(Bar bar){ this.bar=bar; } @Override public Location getLocation(){ return Location; } } public class Controller{ Private Map<Location, Foo> fooMap; public ImmutableFoo addBar(Bar bar){ Foo foo=fooMap.get(bar.getLocation()); if(foo!=null) foo.addBar(bar); return foo; } } I felt the basic approach seems sensible, however, when I speak to others they always seem to have trouble envisioning what I'm describing, which leaves me concerned that I may have a larger design issue then I'm aware of. Is it problematic to have domain objects so tightly coupled, or to use the quasi-mutable approach to modifying them? Assuming that the design approach itself isn't inherently flawed the particular discussion which left me wondering about my approach had to do with the presence of business logic in the domain objects. Currently I have my setter methods in the mutable objects do error checking and all other logic required to verify and make a change to the object. It was suggested that this should be pulled out into a service class, which applies all the business logic, to simplify my domain objects. I understand the advantage in mocking/testing and general separation of logic into two classes. However, with a service method/object It seems I loose some of the advantage of polymorphism, I can't override a base class to add in new error checking or business logic. It seems, if my polymorphic classes were complicated enough, I would end up with a service method that has to check a dozen flags to decide what error checking and business logic applies. So, for example, if I wanted to have a childFoo which also had a size field which should be compared to bar before adding par my current approach would look something like this. public class Foo implements ImmutableFoo{ public void addBar(Bar bar){ if(!getLocation().equals(bar.getLocation()) throw new LocationException(); this.bar=bar; } } public interface ImmutableChildFoo extends ImmutableFoo{ public int getSize(); } public ChildFoo extends Foo implements ImmutableChildFoo{ private int size; @Override public int getSize(){ return size; } @Override public void addBar(Bar bar){ if(getSize()<bar.getSize()){ throw new LocationException(); super.addBar(bar); } My colleague was suggesting instead having a service object that looks something like this (over simplified, the 'service' object would likely be more complex). public interface ImmutableFoo{ ///original interface, presumably used in other methods public Location getLocation(); public boolean isChildFoo(); } public interface ImmutableSizedFoo implements ImmutableFoo{ public int getSize(); } public class Foo implements ImmutableSizedFoo{ public Bar bar; @Override public void addBar(Bar bar){ this.bar=bar; } @Override public int getSize(){ //default size if no size is known return 0; } @Override public boolean isChildFoo return false; } } public ChildFoo extends Foo{ private int size; @Override public int getSize(){ return size; } @Override public boolean isChildFoo(); return true; } } public class Controller{ Private Map<Location, Foo> fooMap; public ImmutableSizedFoo addBar(Bar bar){ Foo foo=fooMap.get(bar.getLocation()); service.addBarToFoo(foo, bar); returned foo; } public class Service{ public static void addBarToFoo(Foo foo, Bar bar){ if(foo==null) return; if(!foo.getLocation().equals(bar.getLocation())) throw new LocationException(); if(foo.isChildFoo() && foo.getSize()<bar.getSize()) throw new LocationException(); foo.setBar(bar); } } } Is the recommended approach of using services and inversion of control inherently superior, or superior in certain cases, to overriding methods directly? If so is there a good way to go with the service approach while not loosing the power of polymorphism to override some of the behavior?

    Read the article

  • Why appending to a list in Scala should have O(n) time complexity?

    - by Jubbat
    I am learning Scala at the moment and I just read that the execution time of the append operation for a list (:+) grows linearly with the size of the list. Appending to a list seems like a pretty common operation. Why should the idiomatic way to do this be prepending the components and then reversing the list? It can't also be a design failure as implementation could be changed at any point. From my point of view, both prepending and appending should be O(1). Is there any legitimate reason for this?

    Read the article

  • Making a class pseudo-immutable by setting a flag

    - by scott_fakename
    I have a java project that involves building some pretty complex objects. There are quite a lot (dozens) of different ones and some of them have a HUGE number of parameters. They also need to be immutable. So I was thinking the builder pattern would work, but it ends up require a lot of boilerplate. Another potential solution I thought of was to make a mutable class, but give it a "frozen" flag, a-la ruby. Here is a simple example: public class EqualRule extends Rule { private boolean frozen; private int target; public EqualRule() { frozen = false; } public void setTarget(int i) { if (frozen) throw new IllegalStateException( "Can't change frozen rule."); target = i; } public int getTarget() { return target; } public void freeze() { frozen = true; } @Override public boolean checkRule(int i) { return (target == i); } } and "Rule" is just an abstract class that has an abstract "checkRule" method. This cuts way down on the number of objects I need to write, while also giving me an object that becomes immutable for all intents and purposes. This kind of act like the object was its own Builder... But not quite. I'm not too excited, however, about having an immutable being disguised as a bean however. So I had two questions: 1. Before I go too far down this path, are there any huge problems that anyone sees right off the bat? For what it's worth, it is planned that this behavior will be well documented... 2. If so, is there a better solution? Thanks

    Read the article

  • Writing a method to 'transform' an immutable object: how should I approach this?

    - by Prog
    (While this question has to do with a concrete coding dilemma, it's mostly about what's the best way to design a function.) I'm writing a method that should take two Color objects, and gradually transform the first Color into the second one, creating an animation. The method will be in a utility class. My problem is that Color is an immutable object. That means that I can't do color.setRGB or color.setBlue inside a loop in the method. What I can do, is instantiate a new Color and return it from the method. But then I won't be able to gradually change the color. So I thought of three possible solutions: 1- The client code includes the method call inside a loop. For example: int duration = 1500; // duration of the animation in milliseconds int steps = 20; // how many 'cycles' the animation will take for(int i=0; i<steps; i++) color = transformColor(color, targetColor, duration, steps); And the method would look like this: Color transformColor(Color original, Color target, int duration, int steps){ int redDiff = target.getRed() - original.getRed(); int redAddition = redDiff / steps; int newRed = original.getRed() + redAddition; // same for green and blue .. Thread.sleep(duration / STEPS); // exception handling omitted return new Color(newRed, newGreen, newBlue); } The disadvantage of this approach is that the client code has to "do part of the method's job" and include a for loop. The method doesn't do it's work entirely on it's own, which I don't like. 2- Make a mutable Color subclass with methods such as setRed, and pass objects of this class into transformColor. Then it could look something like this: void transformColor(MutableColor original, Color target, int duration){ final int STEPS = 20; int redDiff = target.getRed() - original.getRed(); int redAddition = redDiff / steps; int newRed = original.getRed() + redAddition; // same for green and blue .. for(int i=0; i<STEPS; i++){ original.setRed(original.getRed() + redAddition); // same for green and blue .. Thread.sleep(duration / STEPS); // exception handling omitted } } Then the calling code would usually look something like this: // The method will usually transform colors of JComponents JComponent someComponent = ... ; // setting the Color in JComponent to be a MutableColor Color mutableColor = new MutableColor(someComponent.getForeground()); someComponent.setForeground(mutableColor); // later, transforming the Color in the JComponent transformColor((MutableColor)someComponent.getForeground(), new Color(200,100,150), 2000); The disadvantage is - the need to create a new class MutableColor, and also the need to do casting. 3- Pass into the method the actual mutable object that holds the color. Then the method could do object.setColor or similar every iteration of the loop. Two disadvantages: A- Not so elegant. Passing in the object that holds the color just to transform the color feels unnatural. B- While most of the time this method will be used to transform colors inside JComponent objects, other kinds of objects may have colors too. So the method would need to be overloaded to receive other types, or receive Objects and have instanceof checks inside.. Not optimal. Right now I think I like solution #2 the most, than solution #1 and solution #3 the least. However I'd like to hear your opinions and suggestions regarding this.

    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

  • 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

  • How do I rewrite a plist if its data types are immutable?

    - by dugla
    I am getting comfortable with using plists for initializing my app. I now want to save app state back to the plist used to initialize the app and I find myself stuck. At application startup I ingest the plist into an NSDictionary which is immutable. I now want to update the NSDictionary by replacing old values with new values for existing keys and write to the plist via [NSDictionary writeToFile:atomically]. How do I get around the immutability of NSDictionary? Thanks, Doug

    Read the article

  • Downsides to immutable objects in Java?

    - by parkr
    The advantages of immutable objects in Java seem clear: consistent state automatic thread safety simplicity You can favour immutability by using private final fields and constructor injection. But, what are the downsides to favouring immutable objects in Java? i.e. incompatibility with ORM or web presentation tools? Inflexible design? Implementation complexities? Is it possible to design a large-scale system (deep object graph) that predominately uses immutable objects?

    Read the article

  • Is there a quasi-standard set of attributes to annotate thread safety, immutability etc.?

    - by Eugene Beresovksy
    Except for a blog post here and there, describing the custom attributes someone created, but that do not seem to get any traction - like one describing how to enforce immutability, another one on Documenting Thread Safety, modeling the attributes after JCIP annotations - is there any standard emerging? Anything MS might be planning for the future? This is something that should be standard, if there's to be any chance of interoperability between libraries concurrency-wise. Both for documentation purposes, and also to feed static / dynamic test tools. If MS isn't doing anything in that direction, it could be done on CodePlex - but I couldn't find anything there, either. <opinion>Concurrency and thread safety are really hard in imperative and object-languages like C# and Java, we should try to tame it, until we hopefully switch to more appropriate languages.</opinion>

    Read the article

  • Why does Microsoft advise against readonly fields with mutable values?

    - by Weeble
    In the Design Guidelines for Developing Class Libraries, Microsoft say: Do not assign instances of mutable types to read-only fields. The objects created using a mutable type can be modified after they are created. For example, arrays and most collections are mutable types while Int32, Uri, and String are immutable types. For fields that hold a mutable reference type, the read-only modifier prevents the field value from being overwritten but does not protect the mutable type from modification. This simply restates the behaviour of readonly without explaining why it's bad to use readonly. The implication appears to be that many people do not understand what "readonly" does and will wrongly expect readonly fields to be deeply immutable. In effect it advises using "readonly" as code documentation indicating deep immutability - despite the fact that the compiler has no way to enforce this - and disallows its use for its normal function: to ensure that the value of the field doesn't change after the object has been constructed. I feel uneasy with this recommendation to use "readonly" to indicate something other than its normal meaning understood by the compiler. I feel that it encourages people to misunderstand the meaning of "readonly", and furthermore to expect it to mean something that the author of the code might not intend. I feel that it precludes using it in places it could be useful - e.g. to show that some relationship between two mutable objects remains unchanged for the lifetime of one of those objects. The notion of assuming that readers do not understand the meaning of "readonly" also appears to be in contradiction to other advice from Microsoft, such as FxCop's "Do not initialize unnecessarily" rule, which assumes readers of your code to be experts in the language and should know that (for example) bool fields are automatically initialised to false, and stops you from providing the redundancy that shows "yes, this has been consciously set to false; I didn't just forget to initialize it". So, first and foremost, why do Microsoft advise against use of readonly for references to mutable types? I'd also be interested to know: Do you follow this Design Guideline in all your code? What do you expect when you see "readonly" in a piece of code you didn't write?

    Read the article

  • How is ImmutableObjectAttribute used?

    - by Thomas Levesque
    I was looking for a built-in attribute to specify that a type is immutable, and I found only System.ComponentModel.ImmutableObjectAttribute. Using Reflector, I checked where it was used, and it seems that the only public class that uses it is System.Drawing.Image... WTF? It could have been used on string, int or any of the primitive types, but Image is definitely not immutable, there are plenty of ways to alter its internal state (using a Graphics or the Bitmap.SetPixel method for instance). So the only class in the BCL that is explicitly declared as immutable, is mutable! Or am I missing something?

    Read the article

  • How can I avoid mutable variables in Scala when using ZipInputStreams and ZipOutpuStreams?

    - by pr1001
    I'm trying to read a zip file, check that it has some required files, and then write all valid files out to another zip file. The basic introduction to java.util.zip has a lot of Java-isms and I'd love to make my code more Scala-native. Specifically, I'd like to avoid the use of vars. Here's what I have: val fos = new FileOutputStream("new.zip"); val zipOut = new ZipOutputStream(new BufferedOutputStream(fos)); while (zipIn.available == 1) { val entry = zipIn.getNextEntry if (entryIsValid(entry)) { val fos = new FileOutputStream("subdir/" + entry.getName()); val dest = new BufferedOutputStream(fos); // read data into the data Array var data: Array[Byte] = null var count = zip.read(data) while (count != -1) { dest.write(data, 0, count) count = zip.read(data) } dest.flush dest.close } }

    Read the article

  • Creating immutable objects from javabean

    - by redzedi
    Hi All, I am involved in this project where we are building on good bit of legacy code. I have a particular situation about one big java bean object which has to be transferred over wire. So my first thought was to make it immutable and serializable to do the trick .At this point I am faced with a few difficult choices :- 1 Ideally I want some way to automatically generate an immutable, serializable version of this class. I dont have the scope to refactor or alter this class in any way and i would really really hate to have to copy paste the class with a different name ?? 2 Assuming that i gave up on 1 i.e i actually chose to duplicate code of the HUGE javabean class , i still will be in the unsavoury situation of having to write a constructor with some 20-25 parameters to make this class immutable. what is a better way to make a class immutable other than constructor injection ?? Thanks and Regards,

    Read the article

1 2 3  | Next Page >