Все вопросы: [encapsulation]

84 вопросов

похожие теги:
6
голосов
2ответов
3425 просмотров

In C#, can a method return List such that clients can only read it, but not write to it?

Let's say I have a C# class: class Foo { private List<Bar> _barList; List<Bar> GetBarList() { return _barList; } ... } A client can call it: var barList = foo.GetBarList(); barList.Add( ... ); Is there a way to make the Add method fail because only a read-only version of...

1
голосов
3ответов
2099 просмотров

JavaScript function encapsulation outside the object

Please see the following script: var x = function(param){ this.data=param; this.y = function(){ alert(this.data) } return this; } /* x.prototype.z = function(){ alert(this.data); } */ x(123).y(); x(123).z(); // This should behave same as y() When I c...

1
голосов
2ответов
1018 просмотров

Is encapsulation a subset of abstraction?

As both encapsulation and abstraction relate to information hiding, can I understand encapsulation as a subset of abstraction?

8
голосов
2ответов
1206 просмотров

Clojure allows encapsulation and inheritance, but can I combine them?

Here is an overly simplistic example for illustration: I can encapsulate an implementation detail such as using an atom for a counter: (defn make-counter ([] (make-counter 0)) ([init-val] (let [c (atom init-val)] {:get (fn [] @c) :++ (fn [] (swap! c inc))}))) But that means ...

3
голосов
7ответов
2814 просмотров

Access to private Collection fields in Java

One of my classes has a field which contains a Set. This field is only ever filled in the constructor, and then read by other classes. Originally I had something like this: public class Foo { public final Set<String> myItems; public Foo(Collection<String> theirItems) { ...

6
голосов
5ответов
385 просмотров

"Pinnacle" of Encapsulation - Question Regarding Advice from Effective C++

Item 23 of Effective C++ states: Prefer non-member non-friend functions to member functions. The whole purpose of the item was to encourage encapsulation, as well as package flexibility and functional extensibility, but my question is how far do you go when it comes to taking this advice? For ...

1
голосов
3ответов
1712 просмотров

multiple parameters in class method

Total beginner question. I am attempting to create a method for a class that calculates the total price for an object based on int Quantity and decimal price. Both of these are private and have Instance Variable Property Assignments. I cannot figure out how to access them and compute on them ...

88
голосов
24ответов
191762 просмотров

Good way to encapsulate Integer.parseInt()

I have a project in which we often use Integer.parseInt() to convert a String to an int. When something goes wrong (for example, the String is not a number but the letter a, or whatever) this method will throw an exception. However, if I have to handle exceptions in my code everywhere, this start...

0
голосов
1ответов
191 просмотров

Interacting with User Controls through Events

I've browsed through the questions on the site, but haven't found a decent answer yet. My problem is that my main form class is cluttered due to all the events and methods. I decided to break the form into user controls. Unfortunately I am having trouble accessing information from other User co...

2
голосов
3ответов
1189 просмотров

How to encapsulate python modules?

Is it possible to encapsulate python modules 'mechanize' and 'BeautifulSoup' into a single .py file? My problem is the following: I have a python script that requires mechanize and BeautifulSoup. I am calling it from a php page. The webhost server supports python, but doesn't have the modules in...

0
голосов
2ответов
466 просмотров

A question about scope and encapsulation

I have a generic question about scope and encapsulation. Take two scenarios: Scenario 1: // a global application level constant public static const IS_DEMO_MODE:Boolean = false; ... // somewhere deep in the codebase private function _myFunction():void { if (IS_DEMO_MODE == true) { ...

0
голосов
1ответов
350 просмотров

linking methods from an enum to member variables of client class

The following enum structure performs certain operations while remaining agnostic to the client class (for encapsulation reasons) public enum MyEnum implements Commands{ A{ public int method1(int varY) { return varY+2; } public MyEnum method...

0
голосов
6ответов
361 просмотров

Yet another question on mocking

First let me state that, despite being a fairly new practitioner of TDD, I'm pretty much sold on its benefits. I feel like I've progressed enough to consider using mocks and have hit a real brick wall when it comes to understanding where mocks fit in with OOP. I've read as many relevant posts/a...

17
голосов
3ответов
2715 просмотров

Can you explain this thing about encapsulation?

In response to What is your longest-held programming assumption that turned out to be incorrect? question, one of the wrong assumptions was: That private member variables were private to the instance and not the class. (Link) I couldn't catch what he's talking about, can anyone explain...

1
голосов
6ответов
223 просмотров

using another object's functionality following a proper OO design - encapsulation

I am debating the proper, OO-design to use another object's functionality (methods) from a java class, while both objects remain decoupled as much as possible. For example, at some point in my class, to implement my logic, I need to call a method that belongs to another object, say a helper clas...

2
голосов
2ответов
1477 просмотров

Encapsulation Aggregation / Composition

The Wikipedia article about encapsulation states: "Encapsulation also protects the integrity of the component, by preventing users from setting the internal data of the component into an invalid or inconsistent state" I started a discussion about encapsulation on a forum, in which I asked whet...

5
голосов
2ответов
1257 просмотров

does the 'getters and setters are evil' fail for the view layer?

Many people know this article: more on getters and setters. I think it does a convincing job of portraying the evil side of getters/setters. I've also tested it by trying to convert an existing project (unfinished) to code without getters/setters. It worked. Code readability improved greatly, les...

0
голосов
2ответов
138 просмотров

Encapsulating and inheriting methods

I'm wondering if it's possible to encapsulate the methods of a class, but then expose them within a consuming class. For example (JFTR, I know this code is wrong) class Consumer{ public function __construct($obj){ $this->obj = $obj; } public function d...

5
голосов
5ответов
277 просмотров

Should I access POST-Parameters in the model or pass as method arguments from controller?

I have to process about 20 POST-parameters, and I am not sure where to do that. I could define each as an argument of the method on the model, and pass them from the controller when the method is called. This would result in quite a bit of work and make the function call less readable, due to th...

3
голосов
2ответов
876 просмотров

Patterns/Practices for encapsulating predicates

I'm guessing most of us have to deal with this at some point so I thought I'd ask the question. When you have a lot of collections in your BLL and you find that you're writing the same old inline (anonymous) predicates over and over then there's clearly a case for encapsulation there but what's ...

3
голосов
2ответов
130 просмотров

Avoiding casts when translating public APIs to internal glue code

So, I have this public API that my application exposes, allowing customers to write plug-ins. For the sake of this example, let's say it's a fairly simple key-value pair system, something like: public interface Key { // marker interface, guaranteed unique in some scope } public interface KVPS...

97
голосов
2ответов
69861 просмотров

C#: Difference between List<t> and Collection<t> (CA1002, Do not expose generic lists)</t></t>

Tried to run Run Code Analysis on a project here, and got a number of warnings that said something like this: CA1002 : Microsoft.Design : Change 'List&lt;SomeType&gt;' in 'SomeClass.SomeProtectedOrPublicProperty' to use Collection, ReadOnlyCollection or KeyedCollection Why should I use Coll...

4
голосов
5ответов
5058 просмотров

C#: Encapsulation of for example collections

I am wondering which one of these would be considered the cleanest or best to use and why. One of them exposes the a list of passengers, which let the user add and remove etc. The other hides the list and only let the user enumerate them and add using a special method. Example 1 class Bus { ...

13
голосов
8ответов
2934 просмотров

What methods are there to modularize C code?

What methods, practices and conventions do you know of to modularize C code as a project grows in size?

24
голосов
8ответов
2866 просмотров

TDD, DDD and Encapsulation

After several years of following the bad practice handed down from 'architects' at my place of work and thinking that there must be a better way, I've recently been reading up around TDD and DDD and I think the principles and practices would be a great fit for the complexity of the software we wr...

0
голосов
4ответов
313 просмотров

How can/should C++ static member variable and function be hidden?

m_MAX and ask() are used by run() but should otherwise not be public. How can/should this be done? #include &lt;vector&gt; class Q { public: static int const m_MAX=17; int ask(){return 4;} }; class UI { private: std::vector&lt;Q*&gt; m_list; public: void add(Q* a_q){m_list.push_b...

0
голосов
6ответов
191 просмотров

Правильное применение модификаторов доступа

Я студент и ищу ресурсы, которые помогут мне лучше понять, как правильно применять модификаторы доступа к членам / типам по мере их кодирования. Я знаю (на C #), какие модификаторы доступа ограничения, такие как private, public, protected и т. д., вводят в действие. Когда я кодирую свои собст...

3
голосов
11ответов
994 просмотров

Методы инкапсуляции C ++

Я пытаюсь правильно инкапсулировать класс A, который должен использоваться только классом B. Однако я хочу унаследовать от класса B. Иметь друга Б не работает - дружба не передается по наследству. Каков общепринятый способ добиться того, чего я хочу, или я делаю ошибку? Чтобы дать ва...

7
голосов
4ответов
3869 просмотров

Как часто вы наблюдаете злоупотребление сокращенными геттерами / сеттерами C #?

В C # вы можете создавать геттеры / сеттеры более простым способом, чем в других языках: public int FooBar { get; set; } Это создает внутреннюю частную переменную, к которой вы не можете обращаться напрямую, с внешним свойством FooBar для прямого доступа. У меня вопрос: как часто вы на...

5
голосов
6ответов
2421 просмотров

Наследование и инкапсуляция классов коллекций в Java

Предположим, у меня есть следующие типы данных: class Customer { String id; // unique OtherCustData someOtherData; } class Service { String url; // unique OtherServiceData someOtherData; } class LastConnection { Date date; OtherConnData someOtherData; // like request or response...