As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What's the best way for a common library to know what context - a.k.a. the calling app - it is in? I'm in a very controlled enterprise environment... is there a better way for the library to know what application it is getting called from than reading a setting in the config file? What do you use for this type of thing?
//the rest of the story
I work on the Intranet team for a Fortune 500 manufacturing company. I have created a common library that all of our new .Net applications will make use of. It queries a common database for information about the application and a bunch of other things that are irrelevant to the question. As you can imagine, the common library needs to know what application is calling it. I could just force every application to set a property on some static class or something, but instead I wanted to make it a little more behind the scenes. Currently it requires the developer to put a setting in the app.config or web.config with a key of ApplicationName and a value of - you guessed it - the application name (which is a unique non changing id for us). It then uses Currently it uses ConfigurationManager.AppSettings["ApplicationName"] to pull this in.
There may be a way to do it. I will most likely get down votes for this since I don't plan to answer your actual question at all, but I just couldn't move on without saying something. To me this is an example of the worst sort of coupling possible. Your actually has to look at a DB and behave differently depending on the application that is calling it?
You could also just call Assembly.GetEntryAssembly within the common library class.
Then use the .Name property from the returned assembly.
That means those, that your appsettings table (or whatever it is) needs to be keyed by the assembly name, and that if assembly name should change it'd all break. It means you're slightly less flexible on your naming/key choices here.
getenv() will get you environment variables, which in turn should should give you what you want. But generally, having different behavior depending on the name of the calling program is not considered a best practice. An exception would be if you wanted to print out the calling program's name in a log message. There are of course other exceptions, and your situation may be one of them.
You can also probably get the information via the process id (w/ getpid()).
I'm agreeing with EBGreen here. This is a red flag question to me.
That said, I suggest to do exactly the opposite of what you're suggesting, and simply pass the key (application name or whatever) as a parameter to the function you're calling. You could bake it into the program as public static property on whatever you're entry point is, and make a little helper function that basically overloads the call to the repository. That would hide it and reduce error prone repetition..
Better yet, you could also make your entry point classes implement an interface that has a method to get the application name (it just returns a string constant) and methods for setting the values returned from the database.. Call it "IIntranetApp" or something. Then you just pass "this" to a function expecting "IIntranetApp", and it magically fills in the blanks needed from your central repo.
Something like:
public interface IIntranetApp
{
string GetApplicationName();
void SetConnectionString(string connectionString);
// etc... add methods as necessary
}
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I've read some things about this, I even found similar question, but it didn't really answer this. For me it seems that privatizing something only makes my life so much harder when I need to find a private variable in a class to use it elsewhere. So what is would the problem be if everything was public? Would it somehow slow the program itself?
You must consider the maintainability of the code. Accessing all the variables everywhere in your solution is good only if you are the only one in the project and you will be the only one that maintain and use the code. If someone else's entered into project and do completely different things they will be able to access your methods/variables and set the things to unexpected variables. You should think as a OOP design and design your classes like that.
FYI I don't believe you are supposed to ask discussion-based questions like this on SO... But the simplistic answer is this: don't limit your thinking to the logic of the code. We all know there are ten thousand ways to accomplish the same thing. You can probably rewrite a bunch of your code to avoid encapsulation. However, data encapsulation provides a few benefits when you start working on larger projects or with larger teams that go beyond just writing functional code:
(1) organization by concept: if you're coding a bike you would code a class for the wheel, a class for the frame, a class for the handlebars, etc., and you'd know where to go to resolve an issue, perhaps even after months of time away from the code;
(2) separation of implementation and interface: you can tell the world about your public interface and handle the actual implementation privately, so people don't have to know how things work in your code, they just know that it works, like a black box; and if later you have to change your private implementation you can do so freely as long as the public interface still works;
(3) simplification for humans: remember, humans read your code, so would you like to slam them with every bit of data and logic in your project? that would just make for a bunch of angry programmers.
So that's a gentle introduction to encapsulation.
This comes from the fact that, a class should not expose its members directly but must provide a proxy through which the members must be accessed. (Like getters/setters or Properties)
See this question for more info: Why it is recommended to declare instance variables as private?
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
During a code review I presented a method quickly to the team that I had made static and one person agreed that there was no reason for it to not be static and a person disagreed saying that he would not make it static because it wasn't necessary and just to be on the safe side for future modifications and testing.
So I did quite a bit of research and obviously it's a specialized case but I would like to know what you would do in this situation and why?
(Its basically a helper method I call from a few different methods, a very low traffic page. More for my knowledge and learning on Static.)
private IEnumerable<Category> GetCategoryByID(int id, Context context)
{
var categoryQuery = from selectAllProc in context.SelectAll_sp()
where selectAllProc.CategoryID == id
select selectAllProc;
return categoryQuery;
}
Making private methods static is a form of micro-optimization; the method call is slightly faster. But the difference is almost too small to be meaningful.
Generally speaking, you should mark a method static when it:
Doesn't interact in any way with instance members, and
You would like to have the ability to call it without instantiating the class, as in Class.Method()
Ordinarily, methods like your example would go into their own static helper class, if they are used in more than one place.
If I were you I would ask my self the following questions.
Is it something which is related to type or instance of type?
If the answer is yes, I would be slightly inclined to make it static else, make it non static.
If you can give us some more information, the community can come up with some good options.
The first remark that comes to my mind is that by declaring this method static and possibly using it in multiple places in your code you are introducing a Service-locator kind of dependency.
As far as I know the main problem with it is that implicit dependencies are introduced, i.e. they can't be inferred by looking at method signatures.
As a consequence it can be much harder to assess the impact of a modification of your static method on the rest of your system.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I have been working in C# for quite some time but come around this perennial question with colleagues now and then.
The question is: In an inherited class set -- when calling a method should we use keywords 'base.methodname and this.methodname'... irrespective of whether it is a overridden method or not?
My answer is: YES -- its a good practice -use it because that is why those were created for.
Detailed explanation: Moreover the code is likely to undergo changes in terms of logic and maybe some IF-ELSE like conditions may come-in at a later date. So at that time, the developer has to be compelled to revisit each line of code and ensure that he/she makes the right choice of which method is being called --- base.methodname() or this.methodname() ELSE the .NET framework will call the DEFAULT (i think its base.methodname()) and the entire logic can go for a toss.
What do other C# programmers think about it?
Whether or not you use "this." is a matter of opinion. Some like it because it is clear that you are calling something class level, others feel it is redundant noise.
As for base - in my opinion you should only explicitly say "base." if you want to call the base method explicitly and not an overridden method in the current class. Quite often the only place you should even see it is in the overridden method itself.
Don't call base just because it is the implementation in the base class that will be called. It is not meant to be a way of saying "I know the actual implementation is in the base class", it is meant to be a way of saying "specifically do not call the implementation in this class, call the base one". To use it in any other way partly defeats the point of inheritance.
If you are sure that you will always use the method in base class, you can use base.MyMethod.
But be aware of this:
Imagine that you have a method called "GetPrice" in base class and you start using base.GetPrice all over your inherited class (PromoClass). After 3 months someone asks to change the way that price is calculated in Promotions (PromoClass), you (or the new developer) will override or new the method and test it... wait, don't work :|. Because you are always calling for the method in base class. So it will still call the method in base and you need to change all calls in the class.
It's an example of course. If that is standard in your company everyone should know that he should change all over the class the call of that method, if not, be careful.
I prefer to use "base." to use base methods but I normally ignore the "this.".
I concur with #Holstebroe and #Bruno Costa. When you are explicitly calling base.Method every time, you are effectively cutting off the potential for polymorphism, and that's one of the basic reasons to use inheritance in the first place.
I think it smells like bad class design if you in any way could be in doubt whether you are calling a method in a class or a base class.
It is hard for me to find any good examples that would justify explicitly calling overridden base class methods, expect if deriving from legacy or third party classes.
Personally I almost never use virtual methods. You can almost always make a better design with interfaces and abstract methods.
When using base calls it is because you want to extend the functionality of the base method, so you call the base method in the overriding method. Any other usage of base is in my opinion wrong in every way. Also, before overriding a virtual method and calling base you should consider if the extension could be implemented otherwise. For example, if your base method called an abstract method or an interface method that you could either implement or inject in the derived class.
The few times I have used virtual methods are when leaving "blank" methods in a general purpose base class. The blank methods (like InitializeThread() in a thread encapsulation) allows me to optionally extend the base class, but I would never write code in the base methods and never call base.
Calling base is just wrong!
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Why is the default decision in C++, C#, and Ada 95 to use static method binding, rather than dynamic method binding.?
Is the gain in implementation speed worth the loss in abstraction and re-usability?
In general, you can consider that you have todesign the base class for extensibility. If a member function (to use the C++ vocabulary) isn't designed to be overridden, there is a good chance than overriding it will in practice not be possible and for sure it won't it be possible without knowledge of what the class designer think is implementation details and will change without giving you prior notice.
Some additional considerations for two languages (I don't know C# enough to write about it):
Ada 95 would have had compatibility issues with Ada 83 if the choice was different. And considering the whole object model of Ada 95, doing it differently would have make no sense (but you can consider that compatibility was a factor in the choice of the object model).
For C++, performance was certainly a factor. The you don't pay for what you don't use principle and the possibility to use C++ just as a better C was quite instrumental in its success.
The obvious answer is because most functions shouldn't be virtual. As AProgrammer points out, unless a function has been designed explicitly to be overridden, you probably can't override it (virtual or not) without breaking class invariants. (When I work in Java, for example, I end up declaring most functions final, as a matter of good engineering. C++ and Ada make the right decision: the author must explicitly state that the function is designed to be overridden.
Also, C++ and (I think) Ada support value semantics. And value semantics doesn't work well with polymorphism; in Java, classes like java.lang.String are final, in order to simulate value semantics for them. Far to many applications programmers, however, don't bother, since it's not the default. (In a similar manner, far too many C++ programmers omit to inhibit copy and assignment when the class is polymorphic.)
Finally, even when a class is polymorphic, and designed for inheritance, the contract is still specified, and in so far as is reasonable, enforced, in the base class. In C++, typically, this means that public functions are not virtual, since it is the public functions which define and enforce the contract.
I can't speak about Ada, but for C++ two important goals for the design of C++ were:
backwards compatibility with C
you should pay nothing (to the extent possible) for features that you don't use
While neither of these would necessarily dictate that dynamic binding couldn't have been chosen to be the default, having static method binding (I assume you mean non-virtual member functions) does seem to 'fit' better with these design goals.
I'll give one of the other two thirds of Michael Burr's answer.
For Ada it was an important design goal that the language be suitable for system's programming and use on small realtime embedded devices (eg: missile and bomb CPUs). Perhaps there are now techniques that would allow dynamic languages to do such things well, but there certianly weren't back in the late 70's and early 80's when the language was first being designed. Ada95 of course could not radically deviate from the orginal language's basic underlying design, any more than C++ could from C.
That being said, both Ada and C++ (and certianly C# as well?) provide a way to do dynamic method binding ("dynamic dispatch") if you really want it. In both it is accesed via pointers, which IMHO are kind of error-prone. It can also make things a bit of a pain to debug, as it is tough to tell from sources alone exactly what is getting called. So I avoid it unless I really need it.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 13 years ago.
It seems to be the case with the BCL to use underscores for private local variables. I never use them, but get away like this:
int count = 0;
this.Count++;
public int Count
...
public ClassName ( int count )
{
this.Count = count;
}
What are your thoughts on this? Are they are problems with my approach?
This is basically something you'll have to decide upon yourself, just find or make a style guide and follow it.
Personally, I use _ as a prefix for private fields of the class.
The simple rule we use here is: Private implementation details of a class, including variable names, are completely up to the developer who makes it. Public/protected method names, properties, class names, and so on, are subject to best practice guidelines. Internal types can even be considered to be part of this, since they are not publically visible.
When someone else needs to use your library, it will never have to work with internal or private types, will not see if you used underscores, etc. In other words, this is really up to you....
Just keep in mind that if someone else has to maintain your code later that it should not be too obfuscated...
It's not required to use the underscore to denote private variables. It's all personal preference. I use them only so I know I'm using the local variable rather than having Intellisense accidentally use my public Property instead.
IMO, you should never name a private member variable the same as the name of a property, method, or anything else, for that matter. It should be clear which named item you are working with. This will make your code easier to understand and maintain, and will reduce programming errors by yourself, or other developers who need to maintain your code.
Also, if you ever wanted to port the code to VB, that particular naming would not work. Not sure why you would want to switch to VB, but it happens.
I use underscores. It helps me keep variable scope in check and reduce the possibility naming collisions.
Underscores make more sense for languages that are not case sensitive (like VB.Net). In languages like C#, it comes down purely to personal preference.
If you have an aversion to putting this. in the front of some ambiguous assignments, then underscores are for you. Without them, you can occasionally accidentally do things like this:
private int that;
public void AssignThat(int that)
{
that = that; // assigns to method scope variable, not instance scope
}
FXCop or R# should catch this for you, and I believe you get a compiler warning, but it is possible.
There is a practical reason to use a prefix, IntelliSense. ATM it is braindamaged in the way that it does not really distinguish between current instance variables and inherited properties/variables. So using '_' for private variables makes it easier to locate variable within intellisense list and function/variable list in VS code editor. So in a way it is wider-scope hungarian notation.